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 fa132cb1bb..0c249109e6 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/AsciidoctorConventions.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/AsciidoctorConventions.java @@ -72,8 +72,9 @@ class AsciidoctorConventions { makeAllWarningsFatal(project); upgradeAsciidoctorJVersion(project); createAsciidoctorExtensionsConfiguration(project); - project.getTasks().withType(AbstractAsciidoctorTask.class, - (asciidoctorTask) -> configureAsciidoctorTask(project, asciidoctorTask)); + project.getTasks() + .withType(AbstractAsciidoctorTask.class, + (asciidoctorTask) -> configureAsciidoctorTask(project, asciidoctorTask)); }); } @@ -87,12 +88,14 @@ class AsciidoctorConventions { private void createAsciidoctorExtensionsConfiguration(Project project) { project.getConfigurations().create(EXTENSIONS_CONFIGURATION_NAME, (configuration) -> { - project.getConfigurations().matching((candidate) -> "dependencyManagement".equals(candidate.getName())) - .all(configuration::extendsFrom); - configuration.getDependencies().add(project.getDependencies() + project.getConfigurations() + .matching((candidate) -> "dependencyManagement".equals(candidate.getName())) + .all(configuration::extendsFrom); + configuration.getDependencies() + .add(project.getDependencies() .create("io.spring.asciidoctor.backends:spring-asciidoctor-backends:0.0.4")); configuration.getDependencies() - .add(project.getDependencies().create("org.asciidoctor:asciidoctorj-pdf:1.5.3")); + .add(project.getDependencies().create("org.asciidoctor:asciidoctorj-pdf:1.5.3")); }); } @@ -140,13 +143,15 @@ class AsciidoctorConventions { private Sync createSyncDocumentationSourceTask(Project project, AbstractAsciidoctorTask asciidoctorTask) { Sync syncDocumentationSource = project.getTasks() - .create("syncDocumentationSourceFor" + StringUtils.capitalize(asciidoctorTask.getName()), Sync.class); + .create("syncDocumentationSourceFor" + StringUtils.capitalize(asciidoctorTask.getName()), Sync.class); File syncedSource = new File(project.getBuildDir(), "docs/src/" + asciidoctorTask.getName()); syncDocumentationSource.setDestinationDir(syncedSource); syncDocumentationSource.from("src/docs/"); asciidoctorTask.dependsOn(syncDocumentationSource); - asciidoctorTask.getInputs().dir(syncedSource).withPathSensitivity(PathSensitivity.RELATIVE) - .withPropertyName("synced source"); + asciidoctorTask.getInputs() + .dir(syncedSource) + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName("synced source"); asciidoctorTask.setSourceDir(project.relativePath(new File(syncedSource, "asciidoc/"))); return syncDocumentationSource; } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/DeployedPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/DeployedPlugin.java index e3afc9f2e9..e2aae45f80 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/DeployedPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/DeployedPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,12 +46,16 @@ public class DeployedPlugin implements Plugin { MavenPublication mavenPublication = publishing.getPublications().create("maven", MavenPublication.class); project.afterEvaluate((evaluated) -> project.getPlugins().withType(JavaPlugin.class).all((javaPlugin) -> { if (((Jar) project.getTasks().getByName(JavaPlugin.JAR_TASK_NAME)).isEnabled()) { - project.getComponents().matching((component) -> component.getName().equals("java")) - .all(mavenPublication::from); + project.getComponents() + .matching((component) -> component.getName().equals("java")) + .all(mavenPublication::from); } })); - project.getPlugins().withType(JavaPlatformPlugin.class).all((javaPlugin) -> project.getComponents() - .matching((component) -> component.getName().equals("javaPlatform")).all(mavenPublication::from)); + project.getPlugins() + .withType(JavaPlatformPlugin.class) + .all((javaPlugin) -> project.getComponents() + .matching((component) -> component.getName().equals("javaPlatform")) + .all(mavenPublication::from)); } } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/JavaConventions.java b/buildSrc/src/main/java/org/springframework/boot/build/JavaConventions.java index e722bffaee..566ae3ab58 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/JavaConventions.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/JavaConventions.java @@ -120,16 +120,18 @@ class JavaConventions { } private void configureJarManifestConventions(Project project) { - ExtractResources extractLegalResources = project.getTasks().create("extractLegalResources", - ExtractResources.class); + ExtractResources extractLegalResources = project.getTasks() + .create("extractLegalResources", ExtractResources.class); extractLegalResources.getDestinationDirectory().set(project.getLayout().getBuildDirectory().dir("legal")); extractLegalResources.setResourcesNames(Arrays.asList("LICENSE.txt", "NOTICE.txt")); extractLegalResources.property("version", project.getVersion().toString()); SourceSetContainer sourceSets = project.getExtensions().getByType(SourceSetContainer.class); - Set sourceJarTaskNames = sourceSets.stream().map(SourceSet::getSourcesJarTaskName) - .collect(Collectors.toSet()); - Set javadocJarTaskNames = sourceSets.stream().map(SourceSet::getJavadocJarTaskName) - .collect(Collectors.toSet()); + Set sourceJarTaskNames = sourceSets.stream() + .map(SourceSet::getSourcesJarTaskName) + .collect(Collectors.toSet()); + Set javadocJarTaskNames = sourceSets.stream() + .map(SourceSet::getJavadocJarTaskName) + .collect(Collectors.toSet()); project.getTasks().withType(Jar.class, (jar) -> project.afterEvaluate((evaluated) -> { jar.metaInf((metaInf) -> metaInf.from(extractLegalResources)); jar.manifest((manifest) -> { @@ -166,7 +168,8 @@ class JavaConventions { testRetry.getFailOnPassedAfterRetry().set(true); testRetry.getMaxRetries().set(isCi() ? 3 : 0); }); - project.getPlugins().withType(JavaPlugin.class, (javaPlugin) -> project.getDependencies() + project.getPlugins() + .withType(JavaPlugin.class, (javaPlugin) -> project.getDependencies() .add(JavaPlugin.TEST_RUNTIME_ONLY_CONFIGURATION_NAME, "org.junit.platform:junit-platform-launcher")); } @@ -214,7 +217,7 @@ class JavaConventions { String version = SpringJavaFormatPlugin.class.getPackage().getImplementationVersion(); DependencySet checkstyleDependencies = project.getConfigurations().getByName("checkstyle").getDependencies(); checkstyleDependencies - .add(project.getDependencies().create("io.spring.javaformat:spring-javaformat-checkstyle:" + version)); + .add(project.getDependencies().create("io.spring.javaformat:spring-javaformat-checkstyle:" + version)); } private void configureDependencyManagement(Project project) { @@ -225,16 +228,19 @@ class JavaConventions { configuration.setCanBeResolved(false); }); configurations - .matching((configuration) -> configuration.getName().endsWith("Classpath") - || JavaPlugin.ANNOTATION_PROCESSOR_CONFIGURATION_NAME.equals(configuration.getName())) - .all((configuration) -> configuration.extendsFrom(dependencyManagement)); + .matching((configuration) -> configuration.getName().endsWith("Classpath") + || JavaPlugin.ANNOTATION_PROCESSOR_CONFIGURATION_NAME.equals(configuration.getName())) + .all((configuration) -> configuration.extendsFrom(dependencyManagement)); String path = project.getName().contains("spring-boot-starter") ? ":spring-boot-project:spring-boot-dependencies" : ":spring-boot-project:spring-boot-parent"; Dependency dependency = project.getDependencies() - .enforcedPlatform(project.getDependencies().project(Collections.singletonMap("path", path))); + .enforcedPlatform(project.getDependencies().project(Collections.singletonMap("path", path))); dependencyManagement.getDependencies().add(dependency); - project.getPlugins().withType(OptionalDependenciesPlugin.class, (optionalDependencies) -> configurations - .getByName(OptionalDependenciesPlugin.OPTIONAL_CONFIGURATION_NAME).extendsFrom(dependencyManagement)); + project.getPlugins() + .withType(OptionalDependenciesPlugin.class, + (optionalDependencies) -> configurations + .getByName(OptionalDependenciesPlugin.OPTIONAL_CONFIGURATION_NAME) + .extendsFrom(dependencyManagement)); } private void configureToolchain(Project project) { @@ -256,9 +262,9 @@ class JavaConventions { } private void createProhibitedDependenciesCheck(Configuration classpath, Project project) { - CheckClasspathForProhibitedDependencies checkClasspathForProhibitedDependencies = project.getTasks().create( - "check" + StringUtils.capitalize(classpath.getName() + "ForProhibitedDependencies"), - CheckClasspathForProhibitedDependencies.class); + CheckClasspathForProhibitedDependencies checkClasspathForProhibitedDependencies = project.getTasks() + .create("check" + StringUtils.capitalize(classpath.getName() + "ForProhibitedDependencies"), + CheckClasspathForProhibitedDependencies.class); checkClasspathForProhibitedDependencies.setClasspath(classpath); project.getTasks().getByName(JavaBasePlugin.CHECK_TASK_NAME).dependsOn(checkClasspathForProhibitedDependencies); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/KotlinConventions.java b/buildSrc/src/main/java/org/springframework/boot/build/KotlinConventions.java index 0d715bde84..c14ac78353 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/KotlinConventions.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/KotlinConventions.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,8 +44,9 @@ import org.jetbrains.kotlin.gradle.tasks.KotlinCompile; class KotlinConventions { void apply(Project project) { - project.getPlugins().withId("org.jetbrains.kotlin.jvm", - (plugin) -> project.getTasks().withType(KotlinCompile.class, this::configure)); + project.getPlugins() + .withId("org.jetbrains.kotlin.jvm", + (plugin) -> project.getTasks().withType(KotlinCompile.class, this::configure)); } private void configure(KotlinCompile compile) { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/MavenPublishingConventions.java b/buildSrc/src/main/java/org/springframework/boot/build/MavenPublishingConventions.java index 7ff8d9fb93..fc1f5cb357 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/MavenPublishingConventions.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/MavenPublishingConventions.java @@ -67,8 +67,9 @@ class MavenPublishingConventions { mavenRepository.setName("deployment"); }); } - publishing.getPublications().withType(MavenPublication.class) - .all((mavenPublication) -> customizeMavenPublication(mavenPublication, project)); + publishing.getPublications() + .withType(MavenPublication.class) + .all((mavenPublication) -> customizeMavenPublication(mavenPublication, project)); project.getPlugins().withType(JavaPlugin.class).all((javaPlugin) -> { JavaPluginExtension extension = project.getExtensions().getByType(JavaPluginExtension.class); extension.withJavadocJar(); @@ -79,8 +80,9 @@ class MavenPublishingConventions { private void customizeMavenPublication(MavenPublication publication, Project project) { customizePom(publication.getPom(), project); - project.getPlugins().withType(JavaPlugin.class) - .all((javaPlugin) -> customizeJavaMavenPublication(publication, project)); + project.getPlugins() + .withType(JavaPlugin.class) + .all((javaPlugin) -> customizeJavaMavenPublication(publication, project)); suppressMavenOptionalFeatureWarnings(publication); } @@ -102,7 +104,7 @@ class MavenPublishingConventions { private void customizeJavaMavenPublication(MavenPublication publication, Project project) { addMavenOptionalFeature(project); publication.versionMapping((strategy) -> strategy.usage(Usage.JAVA_API, (mappingStrategy) -> mappingStrategy - .fromResolutionOf(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME))); + .fromResolutionOf(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME))); publication.versionMapping( (strategy) -> strategy.usage(Usage.JAVA_RUNTIME, VariantVersionMappingStrategy::fromResolutionResult)); } @@ -117,7 +119,7 @@ class MavenPublishingConventions { extension.registerFeature("mavenOptional", (feature) -> feature.usingSourceSet(extension.getSourceSets().getByName("main"))); AdhocComponentWithVariants javaComponent = (AdhocComponentWithVariants) project.getComponents() - .findByName("java"); + .findByName("java"); javaComponent.addVariantsFromConfiguration( project.getConfigurations().findByName("mavenOptionalRuntimeElements"), ConfigurationVariantDetails::mapToOptional); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/MavenRepositoryPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/MavenRepositoryPlugin.java index d7fcbfdcbc..915c3448e4 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/MavenRepositoryPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/MavenRepositoryPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,36 +61,45 @@ public class MavenRepositoryPlugin implements Plugin { mavenRepository.setName("project"); mavenRepository.setUrl(repositoryLocation.toURI()); }); - project.getTasks().matching((task) -> task.getName().equals(PUBLISH_TO_PROJECT_REPOSITORY_TASK_NAME)) - .all((task) -> setUpProjectRepository(project, task, repositoryLocation)); - project.getTasks().matching((task) -> task.getName().equals("publishPluginMavenPublicationToProjectRepository")) - .all((task) -> setUpProjectRepository(project, task, repositoryLocation)); + project.getTasks() + .matching((task) -> task.getName().equals(PUBLISH_TO_PROJECT_REPOSITORY_TASK_NAME)) + .all((task) -> setUpProjectRepository(project, task, repositoryLocation)); + project.getTasks() + .matching((task) -> task.getName().equals("publishPluginMavenPublicationToProjectRepository")) + .all((task) -> setUpProjectRepository(project, task, repositoryLocation)); } private void setUpProjectRepository(Project project, Task publishTask, File repositoryLocation) { publishTask.doFirst(new CleanAction(repositoryLocation)); Configuration projectRepository = project.getConfigurations().create(MAVEN_REPOSITORY_CONFIGURATION_NAME); - project.getArtifacts().add(projectRepository.getName(), repositoryLocation, - (artifact) -> artifact.builtBy(publishTask)); + project.getArtifacts() + .add(projectRepository.getName(), repositoryLocation, (artifact) -> artifact.builtBy(publishTask)); DependencySet target = projectRepository.getDependencies(); - project.getPlugins().withType(JavaPlugin.class).all((javaPlugin) -> addMavenRepositoryDependencies(project, - JavaPlugin.IMPLEMENTATION_CONFIGURATION_NAME, target)); - project.getPlugins().withType(JavaLibraryPlugin.class) - .all((javaLibraryPlugin) -> addMavenRepositoryDependencies(project, JavaPlugin.API_CONFIGURATION_NAME, - target)); - project.getPlugins().withType(JavaPlatformPlugin.class) - .all((javaPlugin) -> addMavenRepositoryDependencies(project, JavaPlatformPlugin.API_CONFIGURATION_NAME, - target)); + project.getPlugins() + .withType(JavaPlugin.class) + .all((javaPlugin) -> addMavenRepositoryDependencies(project, JavaPlugin.IMPLEMENTATION_CONFIGURATION_NAME, + target)); + project.getPlugins() + .withType(JavaLibraryPlugin.class) + .all((javaLibraryPlugin) -> addMavenRepositoryDependencies(project, JavaPlugin.API_CONFIGURATION_NAME, + target)); + project.getPlugins() + .withType(JavaPlatformPlugin.class) + .all((javaPlugin) -> addMavenRepositoryDependencies(project, JavaPlatformPlugin.API_CONFIGURATION_NAME, + target)); } private void addMavenRepositoryDependencies(Project project, String sourceConfigurationName, DependencySet target) { - project.getConfigurations().getByName(sourceConfigurationName).getDependencies() - .withType(ProjectDependency.class).all((dependency) -> { - Map dependencyDescriptor = new HashMap<>(); - dependencyDescriptor.put("path", dependency.getDependencyProject().getPath()); - dependencyDescriptor.put("configuration", MAVEN_REPOSITORY_CONFIGURATION_NAME); - target.add(project.getDependencies().project(dependencyDescriptor)); - }); + project.getConfigurations() + .getByName(sourceConfigurationName) + .getDependencies() + .withType(ProjectDependency.class) + .all((dependency) -> { + Map dependencyDescriptor = new HashMap<>(); + dependencyDescriptor.put("path", dependency.getDependencyProject().getPath()); + dependencyDescriptor.put("configuration", MAVEN_REPOSITORY_CONFIGURATION_NAME); + target.add(project.getDependencies().project(dependencyDescriptor)); + }); } private static final class CleanAction implements Action { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/SyncAppSource.java b/buildSrc/src/main/java/org/springframework/boot/build/SyncAppSource.java index 9d274b8115..5a863d221a 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/SyncAppSource.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/SyncAppSource.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2021 the original author or authors. + * Copyright 2021-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ public class SyncAppSource extends DefaultTask { this.sourceDirectory = objects.directoryProperty(); this.destinationDirectory = objects.directoryProperty(); this.pluginVersion = objects.property(String.class) - .convention(getProject().provider(() -> getProject().getVersion().toString())); + .convention(getProject().provider(() -> getProject().getVersion().toString())); } @TaskAction diff --git a/buildSrc/src/main/java/org/springframework/boot/build/architecture/ArchitecturePlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/architecture/ArchitecturePlugin.java index dbb2842d54..c95c433572 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/architecture/ArchitecturePlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/architecture/ArchitecturePlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,14 +46,14 @@ public class ArchitecturePlugin implements Plugin { JavaPluginExtension javaPluginExtension = project.getExtensions().getByType(JavaPluginExtension.class); List> packageTangleChecks = new ArrayList<>(); for (SourceSet sourceSet : javaPluginExtension.getSourceSets()) { - TaskProvider checkPackageTangles = project.getTasks().register( - "checkForPackageTangles" + StringUtils.capitalize(sourceSet.getName()), PackageTangleCheck.class, - (task) -> { - task.setClasses(sourceSet.getOutput().getClassesDirs()); - task.setDescription("Checks the classes of the " + sourceSet.getName() - + " source set for package tangles."); - task.setGroup(LifecycleBasePlugin.VERIFICATION_GROUP); - }); + TaskProvider checkPackageTangles = project.getTasks() + .register("checkForPackageTangles" + StringUtils.capitalize(sourceSet.getName()), + PackageTangleCheck.class, (task) -> { + task.setClasses(sourceSet.getOutput().getClassesDirs()); + task.setDescription("Checks the classes of the " + sourceSet.getName() + + " source set for package tangles."); + task.setGroup(LifecycleBasePlugin.VERIFICATION_GROUP); + }); packageTangleChecks.add(checkPackageTangles); } if (!packageTangleChecks.isEmpty()) { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/architecture/PackageTangleCheck.java b/buildSrc/src/main/java/org/springframework/boot/build/architecture/PackageTangleCheck.java index 0c4ceb1a8e..715ac5f686 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/architecture/PackageTangleCheck.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/architecture/PackageTangleCheck.java @@ -1,5 +1,5 @@ /* - * Copyright 2022-2022 the original author or authors. + * Copyright 2022-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,7 +62,7 @@ public abstract class PackageTangleCheck extends DefaultTask { @TaskAction void checkForPackageTangles() throws IOException { JavaClasses javaClasses = new ClassFileImporter() - .importPaths(this.classes.getFiles().stream().map(File::toPath).collect(Collectors.toList())); + .importPaths(this.classes.getFiles().stream().map(File::toPath).collect(Collectors.toList())); SliceRule freeOfCycles = SlicesRuleDefinition.slices().matching("(**)").should().beFreeOfCycles(); EvaluationResult result = freeOfCycles.evaluate(javaClasses); File outputFile = getOutputDirectory().file("failure-report.txt").get().getAsFile(); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/autoconfigure/AutoConfigurationMetadata.java b/buildSrc/src/main/java/org/springframework/boot/build/autoconfigure/AutoConfigurationMetadata.java index 13dcd108d3..870201482a 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/autoconfigure/AutoConfigurationMetadata.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/autoconfigure/AutoConfigurationMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,18 +61,19 @@ public class AutoConfigurationMetadata extends DefaultTask { public AutoConfigurationMetadata() { getInputs() - .file((Callable) () -> new File(this.sourceSet.getOutput().getResourcesDir(), - "META-INF/spring.factories")) - .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("spring.factories"); + .file((Callable) () -> new File(this.sourceSet.getOutput().getResourcesDir(), + "META-INF/spring.factories")) + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName("spring.factories"); getInputs() - .file((Callable) () -> new File(this.sourceSet.getOutput().getResourcesDir(), - "META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports")) - .withPathSensitivity(PathSensitivity.RELATIVE) - .withPropertyName("org.springframework.boot.autoconfigure.AutoConfiguration"); + .file((Callable) () -> new File(this.sourceSet.getOutput().getResourcesDir(), + "META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports")) + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName("org.springframework.boot.autoconfigure.AutoConfiguration"); dependsOn((Callable) () -> this.sourceSet.getProcessResourcesTaskName()); getProject().getConfigurations() - .maybeCreate(AutoConfigurationPlugin.AUTO_CONFIGURATION_METADATA_CONFIGURATION_NAME); + .maybeCreate(AutoConfigurationPlugin.AUTO_CONFIGURATION_METADATA_CONFIGURATION_NAME); } public void setSourceSet(SourceSet sourceSet) { @@ -131,7 +132,7 @@ public class AutoConfigurationMetadata extends DefaultTask { } Properties springFactories = readSpringFactories(file); String enableAutoConfiguration = springFactories - .getProperty("org.springframework.boot.autoconfigure.EnableAutoConfiguration"); + .getProperty("org.springframework.boot.autoconfigure.EnableAutoConfiguration"); return StringUtils.commaDelimitedListToSet(enableAutoConfiguration); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/autoconfigure/AutoConfigurationPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/autoconfigure/AutoConfigurationPlugin.java index 52e081d270..f3e751e48b 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/autoconfigure/AutoConfigurationPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/autoconfigure/AutoConfigurationPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,21 +58,27 @@ public class AutoConfigurationPlugin implements Plugin { project.getPlugins().withType(JavaPlugin.class, (javaPlugin) -> { project.getPlugins().apply(ConfigurationPropertiesPlugin.class); Configuration annotationProcessors = project.getConfigurations() - .getByName(JavaPlugin.ANNOTATION_PROCESSOR_CONFIGURATION_NAME); + .getByName(JavaPlugin.ANNOTATION_PROCESSOR_CONFIGURATION_NAME); annotationProcessors.getDependencies() - .add(project.getDependencies().project(Collections.singletonMap("path", + .add(project.getDependencies() + .project(Collections.singletonMap("path", ":spring-boot-project:spring-boot-tools:spring-boot-autoconfigure-processor"))); annotationProcessors.getDependencies() - .add(project.getDependencies().project(Collections.singletonMap("path", + .add(project.getDependencies() + .project(Collections.singletonMap("path", ":spring-boot-project:spring-boot-tools:spring-boot-configuration-processor"))); project.getTasks().create("autoConfigurationMetadata", AutoConfigurationMetadata.class, (task) -> { - SourceSet main = project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets() - .getByName(SourceSet.MAIN_SOURCE_SET_NAME); + SourceSet main = project.getExtensions() + .getByType(JavaPluginExtension.class) + .getSourceSets() + .getByName(SourceSet.MAIN_SOURCE_SET_NAME); task.setSourceSet(main); task.dependsOn(main.getClassesTaskName()); task.setOutputFile(new File(project.getBuildDir(), "auto-configuration-metadata.properties")); - project.getArtifacts().add(AutoConfigurationPlugin.AUTO_CONFIGURATION_METADATA_CONFIGURATION_NAME, - project.provider((Callable) task::getOutputFile), (artifact) -> artifact.builtBy(task)); + project.getArtifacts() + .add(AutoConfigurationPlugin.AUTO_CONFIGURATION_METADATA_CONFIGURATION_NAME, + project.provider((Callable) task::getOutputFile), + (artifact) -> artifact.builtBy(task)); }); }); } 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 c995d3d83b..6abfb3d09d 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 @@ -126,39 +126,41 @@ public class BomExtension { public void effectiveBomArtifact() { Configuration effectiveBomConfiguration = this.project.getConfigurations().create("effectiveBom"); - this.project.getTasks().matching((task) -> task.getName().equals(DeployedPlugin.GENERATE_POM_TASK_NAME)) - .all((task) -> { - Sync syncBom = this.project.getTasks().create("syncBom", Sync.class); - syncBom.dependsOn(task); - File generatedBomDir = new File(this.project.getBuildDir(), "generated/bom"); - syncBom.setDestinationDir(generatedBomDir); - syncBom.from(((GenerateMavenPom) task).getDestination(), (pom) -> pom.rename((name) -> "pom.xml")); - try { - String settingsXmlContent = FileCopyUtils - .copyToString(new InputStreamReader( - getClass().getClassLoader().getResourceAsStream("effective-bom-settings.xml"), - StandardCharsets.UTF_8)) - .replace("localRepositoryPath", - new File(this.project.getBuildDir(), "local-m2-repository").getAbsolutePath()); - syncBom.from(this.project.getResources().getText().fromString(settingsXmlContent), - (settingsXml) -> settingsXml.rename((name) -> "settings.xml")); - } - catch (IOException ex) { - throw new GradleException("Failed to prepare settings.xml", ex); - } - MavenExec generateEffectiveBom = this.project.getTasks().create("generateEffectiveBom", - MavenExec.class); - generateEffectiveBom.setProjectDir(generatedBomDir); - File effectiveBom = new File(this.project.getBuildDir(), - "generated/effective-bom/" + this.project.getName() + "-effective-bom.xml"); - generateEffectiveBom.args("--settings", "settings.xml", "help:effective-pom", - "-Doutput=" + effectiveBom); - generateEffectiveBom.dependsOn(syncBom); - generateEffectiveBom.getOutputs().file(effectiveBom); - generateEffectiveBom.doLast(new StripUnrepeatableOutputAction(effectiveBom)); - this.project.getArtifacts().add(effectiveBomConfiguration.getName(), effectiveBom, + this.project.getTasks() + .matching((task) -> task.getName().equals(DeployedPlugin.GENERATE_POM_TASK_NAME)) + .all((task) -> { + Sync syncBom = this.project.getTasks().create("syncBom", Sync.class); + syncBom.dependsOn(task); + File generatedBomDir = new File(this.project.getBuildDir(), "generated/bom"); + syncBom.setDestinationDir(generatedBomDir); + syncBom.from(((GenerateMavenPom) task).getDestination(), (pom) -> pom.rename((name) -> "pom.xml")); + try { + String settingsXmlContent = FileCopyUtils + .copyToString(new InputStreamReader( + getClass().getClassLoader().getResourceAsStream("effective-bom-settings.xml"), + StandardCharsets.UTF_8)) + .replace("localRepositoryPath", + new File(this.project.getBuildDir(), "local-m2-repository").getAbsolutePath()); + syncBom.from(this.project.getResources().getText().fromString(settingsXmlContent), + (settingsXml) -> settingsXml.rename((name) -> "settings.xml")); + } + catch (IOException ex) { + throw new GradleException("Failed to prepare settings.xml", ex); + } + MavenExec generateEffectiveBom = this.project.getTasks() + .create("generateEffectiveBom", MavenExec.class); + generateEffectiveBom.setProjectDir(generatedBomDir); + File effectiveBom = new File(this.project.getBuildDir(), + "generated/effective-bom/" + this.project.getName() + "-effective-bom.xml"); + generateEffectiveBom.args("--settings", "settings.xml", "help:effective-pom", + "-Doutput=" + effectiveBom); + generateEffectiveBom.dependsOn(syncBom); + generateEffectiveBom.getOutputs().file(effectiveBom); + generateEffectiveBom.doLast(new StripUnrepeatableOutputAction(effectiveBom)); + this.project.getArtifacts() + .add(effectiveBomConfiguration.getName(), effectiveBom, (artifact) -> artifact.builtBy(generateEffectiveBom)); - }); + }); } private String createDependencyNotation(String groupId, String artifactId, DependencyVersion version) { @@ -197,8 +199,9 @@ public class BomExtension { for (Group group : library.getGroups()) { for (Module module : group.getModules()) { putArtifactVersionProperty(group.getId(), module.getName(), module.getClassifier(), versionProperty); - this.dependencyHandler.getConstraints().add(JavaPlatformPlugin.API_CONFIGURATION_NAME, - createDependencyNotation(group.getId(), module.getName(), library.getVersion().getVersion())); + this.dependencyHandler.getConstraints() + .add(JavaPlatformPlugin.API_CONFIGURATION_NAME, createDependencyNotation(group.getId(), + module.getName(), library.getVersion().getVersion())); } for (String bomImport : group.getBoms()) { putArtifactVersionProperty(group.getId(), bomImport, versionProperty); @@ -243,7 +246,7 @@ public class BomExtension { GroupHandler groupHandler = new GroupHandler(id); action.execute(groupHandler); this.groups - .add(new Group(groupHandler.id, groupHandler.modules, groupHandler.plugins, groupHandler.imports)); + .add(new Group(groupHandler.id, groupHandler.modules, groupHandler.plugins, groupHandler.imports)); } public void prohibit(Action action) { @@ -255,7 +258,7 @@ public class BomExtension { public void dependencyVersions(Action action) { DependencyVersionsHandler dependencyVersionsHandler = this.objectFactory - .newInstance(DependencyVersionsHandler.class, this.version); + .newInstance(DependencyVersionsHandler.class, this.version); action.execute(dependencyVersionsHandler); this.dependencyVersions = dependencyVersionsHandler.dependencyVersions; } @@ -337,8 +340,8 @@ public class BomExtension { public void setModules(List modules) { this.modules = modules.stream() - .map((input) -> (input instanceof Module) ? (Module) input : new Module((String) input)) - .collect(Collectors.toList()); + .map((input) -> (input instanceof Module) ? (Module) input : new Module((String) input)) + .collect(Collectors.toList()); } public void setImports(List imports) { @@ -532,8 +535,9 @@ public class BomExtension { org.w3c.dom.Node reporting = (org.w3c.dom.Node) xpath.evaluate("/project/reporting", document, XPathConstants.NODE); reporting.getParentNode().removeChild(reporting); - TransformerFactory.newInstance().newTransformer().transform(new DOMSource(document), - new StreamResult(this.effectiveBom)); + TransformerFactory.newInstance() + .newTransformer() + .transform(new DOMSource(document), new StreamResult(this.effectiveBom)); } catch (Exception ex) { throw new TaskExecutionException(task, ex); 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 5edb09bad9..3d9d1f67cd 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 @@ -60,8 +60,8 @@ public class BomPlugin implements Plugin { JavaPlatformExtension javaPlatform = project.getExtensions().getByType(JavaPlatformExtension.class); javaPlatform.allowDependencies(); createApiEnforcedConfiguration(project); - BomExtension bom = project.getExtensions().create("bom", BomExtension.class, project.getDependencies(), - project); + BomExtension bom = project.getExtensions() + .create("bom", BomExtension.class, project.getDependencies(), project); project.getTasks().create("bomrCheck", CheckBom.class, bom); project.getTasks().create("bomrUpgrade", UpgradeBom.class, bom); project.getTasks().create("moveToSnapshots", MoveToSnapshots.class, bom); @@ -70,16 +70,18 @@ public class BomPlugin implements Plugin { } private void createApiEnforcedConfiguration(Project project) { - Configuration apiEnforced = project.getConfigurations().create(API_ENFORCED_CONFIGURATION_NAME, - (configuration) -> { - configuration.setCanBeConsumed(false); - configuration.setCanBeResolved(false); - configuration.setVisible(false); - }); - project.getConfigurations().getByName(JavaPlatformPlugin.ENFORCED_API_ELEMENTS_CONFIGURATION_NAME) - .extendsFrom(apiEnforced); - project.getConfigurations().getByName(JavaPlatformPlugin.ENFORCED_RUNTIME_ELEMENTS_CONFIGURATION_NAME) - .extendsFrom(apiEnforced); + Configuration apiEnforced = project.getConfigurations() + .create(API_ENFORCED_CONFIGURATION_NAME, (configuration) -> { + configuration.setCanBeConsumed(false); + configuration.setCanBeResolved(false); + configuration.setVisible(false); + }); + project.getConfigurations() + .getByName(JavaPlatformPlugin.ENFORCED_API_ELEMENTS_CONFIGURATION_NAME) + .extendsFrom(apiEnforced); + project.getConfigurations() + .getByName(JavaPlatformPlugin.ENFORCED_RUNTIME_ELEMENTS_CONFIGURATION_NAME) + .extendsFrom(apiEnforced); } private static final class PublishingCustomizer { @@ -155,16 +157,19 @@ public class BomPlugin implements Plugin { for (Node dependency : findChildren(dependencies, "dependency")) { String groupId = findChild(dependency, "groupId").text(); String artifactId = findChild(dependency, "artifactId").text(); - this.bom.getLibraries().stream().flatMap((library) -> library.getGroups().stream()) - .filter((group) -> group.getId().equals(groupId)) - .flatMap((group) -> group.getModules().stream()) - .filter((module) -> module.getName().equals(artifactId)) - .flatMap((module) -> module.getExclusions().stream()).forEach((exclusion) -> { - Node exclusions = findOrCreateNode(dependency, "exclusions"); - Node node = new Node(exclusions, "exclusion"); - node.appendNode("groupId", exclusion.getGroupId()); - node.appendNode("artifactId", exclusion.getArtifactId()); - }); + this.bom.getLibraries() + .stream() + .flatMap((library) -> library.getGroups().stream()) + .filter((group) -> group.getId().equals(groupId)) + .flatMap((group) -> group.getModules().stream()) + .filter((module) -> module.getName().equals(artifactId)) + .flatMap((module) -> module.getExclusions().stream()) + .forEach((exclusion) -> { + Node exclusions = findOrCreateNode(dependency, "exclusions"); + Node node = new Node(exclusions, "exclusion"); + node.appendNode("groupId", exclusion.getGroupId()); + node.appendNode("artifactId", exclusion.getArtifactId()); + }); } } } @@ -175,12 +180,15 @@ public class BomPlugin implements Plugin { for (Node dependency : findChildren(dependencies, "dependency")) { String groupId = findChild(dependency, "groupId").text(); String artifactId = findChild(dependency, "artifactId").text(); - Set types = this.bom.getLibraries().stream() - .flatMap((library) -> library.getGroups().stream()) - .filter((group) -> group.getId().equals(groupId)) - .flatMap((group) -> group.getModules().stream()) - .filter((module) -> module.getName().equals(artifactId)).map(Module::getType) - .filter(Objects::nonNull).collect(Collectors.toSet()); + Set types = this.bom.getLibraries() + .stream() + .flatMap((library) -> library.getGroups().stream()) + .filter((group) -> group.getId().equals(groupId)) + .flatMap((group) -> group.getModules().stream()) + .filter((module) -> module.getName().equals(artifactId)) + .map(Module::getType) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); if (types.size() > 1) { throw new IllegalStateException( "Multiple types for " + groupId + ":" + artifactId + ": " + types); @@ -201,12 +209,15 @@ public class BomPlugin implements Plugin { String groupId = findChild(dependency, "groupId").text(); String artifactId = findChild(dependency, "artifactId").text(); String version = findChild(dependency, "version").text(); - Set classifiers = this.bom.getLibraries().stream() - .flatMap((library) -> library.getGroups().stream()) - .filter((group) -> group.getId().equals(groupId)) - .flatMap((group) -> group.getModules().stream()) - .filter((module) -> module.getName().equals(artifactId)).map(Module::getClassifier) - .filter(Objects::nonNull).collect(Collectors.toSet()); + Set classifiers = this.bom.getLibraries() + .stream() + .flatMap((library) -> library.getGroups().stream()) + .filter((group) -> group.getId().equals(groupId)) + .flatMap((group) -> group.getModules().stream()) + .filter((module) -> module.getName().equals(artifactId)) + .map(Module::getClassifier) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); Node target = dependency; for (String classifier : classifiers) { if (classifier.length() > 0) { @@ -272,8 +283,10 @@ public class BomPlugin implements Plugin { @SuppressWarnings("unchecked") private List findChildren(Node parent, String name) { - return (List) parent.children().stream().filter((child) -> isNodeWithName(child, name)) - .collect(Collectors.toList()); + return (List) parent.children() + .stream() + .filter((child) -> isNodeWithName(child, name)) + .collect(Collectors.toList()); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/CheckBom.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/CheckBom.java index 410aebb09d..3aeaf0161b 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/CheckBom.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/CheckBom.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,14 +59,18 @@ public class CheckBom extends DefaultTask { private void checkExclusions(String groupId, Module module, DependencyVersion version) { Set resolved = getProject().getConfigurations() - .detachedConfiguration( - getProject().getDependencies().create(groupId + ":" + module.getName() + ":" + version)) - .getResolvedConfiguration().getResolvedArtifacts().stream() - .map((artifact) -> artifact.getModuleVersion().getId()) - .map((id) -> id.getGroup() + ":" + id.getModule().getName()).collect(Collectors.toSet()); - Set exclusions = module.getExclusions().stream() - .map((exclusion) -> exclusion.getGroupId() + ":" + exclusion.getArtifactId()) - .collect(Collectors.toSet()); + .detachedConfiguration( + getProject().getDependencies().create(groupId + ":" + module.getName() + ":" + version)) + .getResolvedConfiguration() + .getResolvedArtifacts() + .stream() + .map((artifact) -> artifact.getModuleVersion().getId()) + .map((id) -> id.getGroup() + ":" + id.getModule().getName()) + .collect(Collectors.toSet()); + Set exclusions = module.getExclusions() + .stream() + .map((exclusion) -> exclusion.getGroupId() + ":" + exclusion.getArtifactId()) + .collect(Collectors.toSet()); Set unused = new TreeSet<>(); for (String exclusion : exclusions) { if (!resolved.contains(exclusion)) { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/Library.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/Library.java index 438fb5e095..b7a0bcea3b 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/Library.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/Library.java @@ -322,7 +322,7 @@ public class Library { if (!line.startsWith("#")) { String[] components = line.split(":"); Map groupDependencies = this.dependencyVersions - .computeIfAbsent(components[0], (key) -> new HashMap<>()); + .computeIfAbsent(components[0], (key) -> new HashMap<>()); groupDependencies.put(components[1], components[2]); } } @@ -372,7 +372,7 @@ public class Library { Matcher matcher = CONSTRAINT_PATTERN.matcher(line.trim()); if (matcher.matches()) { Map groupDependencies = this.dependencyVersions - .computeIfAbsent(matcher.group(1), (key) -> new HashMap<>()); + .computeIfAbsent(matcher.group(1), (key) -> new HashMap<>()); groupDependencies.put(matcher.group(2), matcher.group(3)); } } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/InteractiveUpgradeResolver.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/InteractiveUpgradeResolver.java index 7d430b9391..a372d89eb7 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/InteractiveUpgradeResolver.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/InteractiveUpgradeResolver.java @@ -51,7 +51,7 @@ public final class InteractiveUpgradeResolver implements UpgradeResolver { librariesByName.put(library.getName(), library); } List libraryUpdates = this.libraryUpdateResolver - .findLibraryUpdates(librariesToUpgrade, librariesByName); + .findLibraryUpdates(librariesToUpgrade, librariesByName); return libraryUpdates.stream().map(this::resolveUpgrade).filter(Objects::nonNull).collect(Collectors.toList()); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/MavenMetadataVersionResolver.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/MavenMetadataVersionResolver.java index 8f938b755e..b7c23092e6 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/MavenMetadataVersionResolver.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/MavenMetadataVersionResolver.java @@ -75,10 +75,12 @@ final class MavenMetadataVersionResolver implements VersionResolver { URI url = repositoryUrl.resolve(groupId.replace('.', '/') + "/" + artifactId + "/maven-metadata.xml"); try { String metadata = this.rest.getForObject(url, String.class); - Document metadataDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder() - .parse(new InputSource(new StringReader(metadata))); - NodeList versionNodes = (NodeList) XPathFactory.newInstance().newXPath() - .evaluate("/metadata/versioning/versions/version", metadataDocument, XPathConstants.NODESET); + Document metadataDocument = DocumentBuilderFactory.newInstance() + .newDocumentBuilder() + .parse(new InputSource(new StringReader(metadata))); + NodeList versionNodes = (NodeList) XPathFactory.newInstance() + .newXPath() + .evaluate("/metadata/versioning/versions/version", metadataDocument, XPathConstants.NODESET); for (int i = 0; i < versionNodes.getLength(); i++) { versions.add(versionNodes.item(i).getTextContent()); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/StandardLibraryUpdateResolver.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/StandardLibraryUpdateResolver.java index c7c1f45bb8..03f6184dc5 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/StandardLibraryUpdateResolver.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/StandardLibraryUpdateResolver.java @@ -106,14 +106,19 @@ class StandardLibraryUpdateResolver implements LibraryUpdateResolver { getLaterVersionsForModule(group.getId(), plugin, libraryVersion)); } } - List allVersions = moduleVersions.values().stream().flatMap(SortedSet::stream).distinct() - .filter((dependencyVersion) -> isPermitted(dependencyVersion, library.getProhibitedVersions())) - .collect(Collectors.toList()); + List allVersions = moduleVersions.values() + .stream() + .flatMap(SortedSet::stream) + .distinct() + .filter((dependencyVersion) -> isPermitted(dependencyVersion, library.getProhibitedVersions())) + .collect(Collectors.toList()); if (allVersions.isEmpty()) { return Collections.emptyList(); } - return allVersions.stream().map((version) -> new VersionOption.ResolvedVersionOption(version, - getMissingModules(moduleVersions, version))).collect(Collectors.toList()); + return allVersions.stream() + .map((version) -> new VersionOption.ResolvedVersionOption(version, + getMissingModules(moduleVersions, version))) + .collect(Collectors.toList()); } private List determineAlignedVersionOption(Library library, Map libraries) { @@ -165,7 +170,7 @@ class StandardLibraryUpdateResolver implements LibraryUpdateResolver { for (ProhibitedVersion prohibitedVersion : prohibitedVersions) { String dependencyVersionToString = dependencyVersion.toString(); if (prohibitedVersion.getRange() != null && prohibitedVersion.getRange() - .containsVersion(new DefaultArtifactVersion(dependencyVersionToString))) { + .containsVersion(new DefaultArtifactVersion(dependencyVersionToString))) { return false; } for (String startsWith : prohibitedVersion.getStartsWith()) { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/UpgradeApplicator.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/UpgradeApplicator.java index 1588ed7b5b..79f0a3406d 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/UpgradeApplicator.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/UpgradeApplicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,12 +44,12 @@ class UpgradeApplicator { Path apply(Upgrade upgrade) throws IOException { String buildFileContents = new String(Files.readAllBytes(this.buildFile), StandardCharsets.UTF_8); Matcher matcher = Pattern.compile("library\\(\"" + upgrade.getLibrary().getName() + "\", \"(.+)\"\\)") - .matcher(buildFileContents); + .matcher(buildFileContents); if (!matcher.find()) { matcher = Pattern - .compile("library\\(\"" + upgrade.getLibrary().getName() + "\"\\) \\{\\s+version\\(\"(.+)\"\\)", - Pattern.MULTILINE) - .matcher(buildFileContents); + .compile("library\\(\"" + upgrade.getLibrary().getName() + "\"\\) \\{\\s+version\\(\"(.+)\"\\)", + Pattern.MULTILINE) + .matcher(buildFileContents); if (!matcher.find()) { throw new IllegalStateException("Failed to find definition for library '" + upgrade.getLibrary().getName() + "' in bom '" + this.buildFile + "'"); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/UpgradeDependencies.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/UpgradeDependencies.java index 10077afa4e..47c2c0dcf0 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/UpgradeDependencies.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/UpgradeDependencies.java @@ -130,12 +130,14 @@ public abstract class UpgradeDependencies extends DefaultTask { existingUpgradeIssue.label(Arrays.asList("type: task", "status: superseded")); } } - if (new ProcessBuilder().command("git", "add", modified.toFile().getAbsolutePath()).start() - .waitFor() != 0) { + if (new ProcessBuilder().command("git", "add", modified.toFile().getAbsolutePath()) + .start() + .waitFor() != 0) { throw new IllegalStateException("git add failed"); } - if (new ProcessBuilder().command("git", "commit", "-m", commitMessage(upgrade, issueNumber)).start() - .waitFor() != 0) { + if (new ProcessBuilder().command("git", "commit", "-m", commitMessage(upgrade, issueNumber)) + .start() + .waitFor() != 0) { throw new IllegalStateException("git commit failed"); } } @@ -176,7 +178,8 @@ public abstract class UpgradeDependencies extends DefaultTask { private Milestone determineMilestone(GitHubRepository repository) { List milestones = repository.getMilestones(); java.util.Optional matchingMilestone = milestones.stream() - .filter((milestone) -> milestone.getName().equals(getMilestone().get())).findFirst(); + .filter((milestone) -> milestone.getName().equals(getMilestone().get())) + .findFirst(); if (!matchingMilestone.isPresent()) { throw new InvalidUserDataException("Unknown milestone: " + getMilestone().get()); } @@ -186,8 +189,9 @@ public abstract class UpgradeDependencies extends DefaultTask { private Issue findExistingUpgradeIssue(List existingUpgradeIssues, Upgrade upgrade) { String toMatch = "Upgrade to " + upgrade.getLibrary().getName(); for (Issue existingUpgradeIssue : existingUpgradeIssues) { - if (existingUpgradeIssue.getTitle().substring(0, existingUpgradeIssue.getTitle().lastIndexOf(' ')) - .equals(toMatch)) { + if (existingUpgradeIssue.getTitle() + .substring(0, existingUpgradeIssue.getTitle().lastIndexOf(' ')) + .equals(toMatch)) { return existingUpgradeIssue; } } @@ -198,8 +202,8 @@ public abstract class UpgradeDependencies extends DefaultTask { private List resolveUpgrades() { List upgrades = new InteractiveUpgradeResolver(getServices().get(UserInputHandler.class), new MultithreadedLibraryUpdateResolver(new MavenMetadataVersionResolver(getRepositoryUris().get()), - this.bom.getUpgrade().getPolicy(), getThreads().get())).resolveUpgrades( - matchingLibraries(getLibraries().getOrNull()), this.bom.getLibraries()); + this.bom.getUpgrade().getPolicy(), getThreads().get())) + .resolveUpgrades(matchingLibraries(getLibraries().getOrNull()), this.bom.getLibraries()); return upgrades; } @@ -208,8 +212,10 @@ public abstract class UpgradeDependencies extends DefaultTask { return this.bom.getLibraries(); } Predicate libraryPredicate = Pattern.compile(pattern).asPredicate(); - List matchingLibraries = this.bom.getLibraries().stream() - .filter((library) -> libraryPredicate.test(library.getName())).collect(Collectors.toList()); + List matchingLibraries = this.bom.getLibraries() + .stream() + .filter((library) -> libraryPredicate.test(library.getName())) + .collect(Collectors.toList()); if (matchingLibraries.isEmpty()) { throw new InvalidUserDataException("No libraries matched '" + pattern + "'"); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/github/StandardGitHub.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/github/StandardGitHub.java index ec5db84fba..1c880fb99c 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/github/StandardGitHub.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/github/StandardGitHub.java @@ -49,7 +49,8 @@ final class StandardGitHub implements GitHub { Collections.singletonList(new MappingJackson2HttpMessageConverter(new ObjectMapper()))); restTemplate.getInterceptors().add((request, body, execution) -> { request.getHeaders().add("User-Agent", StandardGitHub.this.username); - request.getHeaders().add("Authorization", "Basic " + Base64.getEncoder() + request.getHeaders() + .add("Authorization", "Basic " + Base64.getEncoder() .encodeToString((StandardGitHub.this.username + ":" + StandardGitHub.this.password).getBytes())); request.getHeaders().add("Accept", MediaType.APPLICATION_JSON_VALUE); return execution.execute(request, body); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForConflicts.java b/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForConflicts.java index 0396522e12..f80c144053 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForConflicts.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForConflicts.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,8 +68,9 @@ public class CheckClasspathForConflicts extends DefaultTask { for (File file : this.classpath) { if (file.isDirectory()) { Path root = file.toPath(); - Files.walk(root).filter(Files::isRegularFile) - .forEach((entry) -> classpathContents.add(root.relativize(entry).toString(), root.toString())); + Files.walk(root) + .filter(Files::isRegularFile) + .forEach((entry) -> classpathContents.add(root.relativize(entry).toString(), root.toString())); } else { try (JarFile jar = new JarFile(file)) { @@ -108,9 +109,11 @@ public class CheckClasspathForConflicts extends DefaultTask { } private Map> getConflicts(List> ignores) { - return this.classpathContents.entrySet().stream().filter((entry) -> entry.getValue().size() > 1) - .filter((entry) -> canConflict(entry.getKey(), ignores)) - .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (v1, v2) -> v1, TreeMap::new)); + return this.classpathContents.entrySet() + .stream() + .filter((entry) -> entry.getValue().size() > 1) + .filter((entry) -> canConflict(entry.getKey(), ignores)) + .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (v1, v2) -> v1, TreeMap::new)); } private boolean canConflict(String name, List> ignores) { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForProhibitedDependencies.java b/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForProhibitedDependencies.java index c64c543d45..de76ca1e17 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForProhibitedDependencies.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForProhibitedDependencies.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,9 +52,13 @@ public class CheckClasspathForProhibitedDependencies extends DefaultTask { @TaskAction public void checkForProhibitedDependencies() { - TreeSet prohibited = this.classpath.getResolvedConfiguration().getResolvedArtifacts().stream() - .map((artifact) -> artifact.getModuleVersion().getId()).filter(this::prohibited) - .map((id) -> id.getGroup() + ":" + id.getName()).collect(Collectors.toCollection(TreeSet::new)); + TreeSet prohibited = this.classpath.getResolvedConfiguration() + .getResolvedArtifacts() + .stream() + .map((artifact) -> artifact.getModuleVersion().getId()) + .filter(this::prohibited) + .map((id) -> id.getGroup() + ":" + id.getName()) + .collect(Collectors.toCollection(TreeSet::new)); if (!prohibited.isEmpty()) { StringBuilder message = new StringBuilder(String.format("Found prohibited dependencies:%n")); for (String dependency : prohibited) { 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..6ea9aa3dc9 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,8 +67,8 @@ public class CheckClasspathForUnnecessaryExclusions extends DefaultTask { ConfigurationContainer configurations) { this.dependencyHandler = getProject().getDependencies(); this.configurations = getProject().getConfigurations(); - this.platform = this.dependencyHandler.create( - this.dependencyHandler.platform(this.dependencyHandler.project(SPRING_BOOT_DEPENDENCIES_PROJECT))); + this.platform = this.dependencyHandler + .create(this.dependencyHandler.platform(this.dependencyHandler.project(SPRING_BOOT_DEPENDENCIES_PROJECT))); getOutputs().upToDateWhen((task) -> true); } @@ -86,8 +86,10 @@ public class CheckClasspathForUnnecessaryExclusions extends DefaultTask { private void processDependency(ModuleDependency dependency) { String dependencyId = getId(dependency); - TreeSet exclusions = dependency.getExcludeRules().stream().map(this::getId) - .collect(Collectors.toCollection(TreeSet::new)); + TreeSet exclusions = dependency.getExcludeRules() + .stream() + .map(this::getId) + .collect(Collectors.toCollection(TreeSet::new)); this.exclusionsByDependencyId.put(dependencyId, exclusions); if (!exclusions.isEmpty()) { this.dependencyById.put(dependencyId, getProject().getDependencies().create(dependencyId)); @@ -106,8 +108,12 @@ public class CheckClasspathForUnnecessaryExclusions extends DefaultTask { if (!exclusions.isEmpty()) { Dependency toCheck = this.dependencyById.get(dependencyId); List dependencies = this.configurations.detachedConfiguration(toCheck, this.platform) - .getIncoming().getArtifacts().getArtifacts().stream().map(this::getId) - .collect(Collectors.toList()); + .getIncoming() + .getArtifacts() + .getArtifacts() + .stream() + .map(this::getId) + .collect(Collectors.toList()); exclusions.removeAll(dependencies); removeProfileExclusions(dependencyId, exclusions); if (!exclusions.isEmpty()) { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/constraints/ExtractVersionConstraints.java b/buildSrc/src/main/java/org/springframework/boot/build/constraints/ExtractVersionConstraints.java index 572bf2af3b..4d14b2977d 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/constraints/ExtractVersionConstraints.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/constraints/ExtractVersionConstraints.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,8 +64,10 @@ public class ExtractVersionConstraints extends DefaultTask { } public void enforcedPlatform(String projectPath) { - this.configuration.getDependencies().add(getProject().getDependencies().enforcedPlatform( - getProject().getDependencies().project(Collections.singletonMap("path", projectPath)))); + this.configuration.getDependencies() + .add(getProject().getDependencies() + .enforcedPlatform( + getProject().getDependencies().project(Collections.singletonMap("path", projectPath)))); this.projectPaths.add(projectPath); } @@ -89,8 +91,10 @@ public class ExtractVersionConstraints extends DefaultTask { this.configuration.resolve(); for (String projectPath : this.projectPaths) { extractVersionProperties(projectPath); - for (DependencyConstraint constraint : getProject().project(projectPath).getConfigurations() - .getByName("apiElements").getAllDependencyConstraints()) { + for (DependencyConstraint constraint : getProject().project(projectPath) + .getConfigurations() + .getByName("apiElements") + .getAllDependencyConstraints()) { this.versionConstraints.put(constraint.getGroup() + ":" + constraint.getName(), constraint.getVersionConstraint().toString()); this.constrainedVersions.add(new ConstrainedVersion(constraint.getGroup(), constraint.getName(), diff --git a/buildSrc/src/main/java/org/springframework/boot/build/context/properties/CheckSpringConfigurationMetadata.java b/buildSrc/src/main/java/org/springframework/boot/build/context/properties/CheckSpringConfigurationMetadata.java index a41d1448c7..bf94c97b1e 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/context/properties/CheckSpringConfigurationMetadata.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/context/properties/CheckSpringConfigurationMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -154,8 +154,9 @@ public class CheckSpringConfigurationMetadata extends DefaultTask { else { lines.add("The following properties have no description:"); lines.add(""); - lines.addAll(this.propertiesWithNoDescription.stream().map((line) -> "\t" + line) - .collect(Collectors.toList())); + lines.addAll(this.propertiesWithNoDescription.stream() + .map((line) -> "\t" + line) + .collect(Collectors.toList())); } lines.add(""); return lines.iterator(); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/context/properties/ConfigurationPropertiesPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/context/properties/ConfigurationPropertiesPlugin.java index 2aed10187e..67cda78496 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/context/properties/ConfigurationPropertiesPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/context/properties/ConfigurationPropertiesPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -86,74 +86,101 @@ public class ConfigurationPropertiesPlugin implements Plugin { private void addConfigurationProcessorDependency(Project project) { Configuration annotationProcessors = project.getConfigurations() - .getByName(JavaPlugin.ANNOTATION_PROCESSOR_CONFIGURATION_NAME); - annotationProcessors.getDependencies().add(project.getDependencies().project(Collections.singletonMap("path", - ":spring-boot-project:spring-boot-tools:spring-boot-configuration-processor"))); + .getByName(JavaPlugin.ANNOTATION_PROCESSOR_CONFIGURATION_NAME); + annotationProcessors.getDependencies() + .add(project.getDependencies() + .project(Collections.singletonMap("path", + ":spring-boot-project:spring-boot-tools:spring-boot-configuration-processor"))); } private void disableIncrementalCompilation(Project project) { - SourceSet mainSourceSet = project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets() - .getByName(SourceSet.MAIN_SOURCE_SET_NAME); - project.getTasks().named(mainSourceSet.getCompileJavaTaskName(), JavaCompile.class) - .configure((compileJava) -> compileJava.getOptions().setIncremental(false)); + SourceSet mainSourceSet = project.getExtensions() + .getByType(JavaPluginExtension.class) + .getSourceSets() + .getByName(SourceSet.MAIN_SOURCE_SET_NAME); + project.getTasks() + .named(mainSourceSet.getCompileJavaTaskName(), JavaCompile.class) + .configure((compileJava) -> compileJava.getOptions().setIncremental(false)); } private void addMetadataArtifact(Project project) { - SourceSet mainSourceSet = project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets() - .getByName(SourceSet.MAIN_SOURCE_SET_NAME); + SourceSet mainSourceSet = project.getExtensions() + .getByType(JavaPluginExtension.class) + .getSourceSets() + .getByName(SourceSet.MAIN_SOURCE_SET_NAME); project.getConfigurations().maybeCreate(CONFIGURATION_PROPERTIES_METADATA_CONFIGURATION_NAME); - project.afterEvaluate((evaluatedProject) -> evaluatedProject.getArtifacts().add( - CONFIGURATION_PROPERTIES_METADATA_CONFIGURATION_NAME, - mainSourceSet.getJava().getDestinationDirectory().dir("META-INF/spring-configuration-metadata.json"), - (artifact) -> artifact + project.afterEvaluate((evaluatedProject) -> evaluatedProject.getArtifacts() + .add(CONFIGURATION_PROPERTIES_METADATA_CONFIGURATION_NAME, + mainSourceSet.getJava() + .getDestinationDirectory() + .dir("META-INF/spring-configuration-metadata.json"), + (artifact) -> artifact .builtBy(evaluatedProject.getTasks().getByName(mainSourceSet.getClassesTaskName())))); } private void configureAdditionalMetadataLocationsCompilerArgument(Project project) { - JavaCompile compileJava = project.getTasks().withType(JavaCompile.class) - .getByName(JavaPlugin.COMPILE_JAVA_TASK_NAME); - ((Task) compileJava).getInputs().files(project.getTasks().getByName(JavaPlugin.PROCESS_RESOURCES_TASK_NAME)) - .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("processed resources"); - SourceSet mainSourceSet = project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets() - .getByName(SourceSet.MAIN_SOURCE_SET_NAME); - compileJava.getOptions().getCompilerArgs() - .add("-Aorg.springframework.boot.configurationprocessor.additionalMetadataLocations=" + StringUtils - .collectionToCommaDelimitedString(mainSourceSet.getResources().getSourceDirectories().getFiles() - .stream().map(project.getRootProject()::relativePath).collect(Collectors.toSet()))); + JavaCompile compileJava = project.getTasks() + .withType(JavaCompile.class) + .getByName(JavaPlugin.COMPILE_JAVA_TASK_NAME); + ((Task) compileJava).getInputs() + .files(project.getTasks().getByName(JavaPlugin.PROCESS_RESOURCES_TASK_NAME)) + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName("processed resources"); + SourceSet mainSourceSet = project.getExtensions() + .getByType(JavaPluginExtension.class) + .getSourceSets() + .getByName(SourceSet.MAIN_SOURCE_SET_NAME); + compileJava.getOptions() + .getCompilerArgs() + .add("-Aorg.springframework.boot.configurationprocessor.additionalMetadataLocations=" + + StringUtils.collectionToCommaDelimitedString(mainSourceSet.getResources() + .getSourceDirectories() + .getFiles() + .stream() + .map(project.getRootProject()::relativePath) + .collect(Collectors.toSet()))); } private void registerCheckAdditionalMetadataTask(Project project) { TaskProvider checkConfigurationMetadata = project.getTasks() - .register(CHECK_ADDITIONAL_SPRING_CONFIGURATION_METADATA_TASK_NAME, - CheckAdditionalSpringConfigurationMetadata.class); + .register(CHECK_ADDITIONAL_SPRING_CONFIGURATION_METADATA_TASK_NAME, + CheckAdditionalSpringConfigurationMetadata.class); checkConfigurationMetadata.configure((check) -> { - SourceSet mainSourceSet = project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets() - .getByName(SourceSet.MAIN_SOURCE_SET_NAME); + SourceSet mainSourceSet = project.getExtensions() + .getByType(JavaPluginExtension.class) + .getSourceSets() + .getByName(SourceSet.MAIN_SOURCE_SET_NAME); check.setSource(mainSourceSet.getResources()); check.include("META-INF/additional-spring-configuration-metadata.json"); - check.getReportLocation().set(project.getLayout().getBuildDirectory() + check.getReportLocation() + .set(project.getLayout() + .getBuildDirectory() .file("reports/additional-spring-configuration-metadata/check.txt")); }); - project.getTasks().named(LifecycleBasePlugin.CHECK_TASK_NAME) - .configure((check) -> check.dependsOn(checkConfigurationMetadata)); + project.getTasks() + .named(LifecycleBasePlugin.CHECK_TASK_NAME) + .configure((check) -> check.dependsOn(checkConfigurationMetadata)); } private void registerCheckMetadataTask(Project project) { TaskProvider checkConfigurationMetadata = project.getTasks() - .register(CHECK_SPRING_CONFIGURATION_METADATA_TASK_NAME, CheckSpringConfigurationMetadata.class); + .register(CHECK_SPRING_CONFIGURATION_METADATA_TASK_NAME, CheckSpringConfigurationMetadata.class); checkConfigurationMetadata.configure((check) -> { - SourceSet mainSourceSet = project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets() - .getByName(SourceSet.MAIN_SOURCE_SET_NAME); + SourceSet mainSourceSet = project.getExtensions() + .getByType(JavaPluginExtension.class) + .getSourceSets() + .getByName(SourceSet.MAIN_SOURCE_SET_NAME); Provider metadataLocation = project.getTasks() - .named(mainSourceSet.getCompileJavaTaskName(), JavaCompile.class) - .flatMap((javaCompile) -> javaCompile.getDestinationDirectory() - .file("META-INF/spring-configuration-metadata.json")); + .named(mainSourceSet.getCompileJavaTaskName(), JavaCompile.class) + .flatMap((javaCompile) -> javaCompile.getDestinationDirectory() + .file("META-INF/spring-configuration-metadata.json")); check.getMetadataLocation().set(metadataLocation); - check.getReportLocation().set( - project.getLayout().getBuildDirectory().file("reports/spring-configuration-metadata/check.txt")); + check.getReportLocation() + .set(project.getLayout().getBuildDirectory().file("reports/spring-configuration-metadata/check.txt")); }); - project.getTasks().named(LifecycleBasePlugin.CHECK_TASK_NAME) - .configure((check) -> check.dependsOn(checkConfigurationMetadata)); + project.getTasks() + .named(LifecycleBasePlugin.CHECK_TASK_NAME) + .configure((check) -> check.dependsOn(checkConfigurationMetadata)); } } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/context/properties/SingleRow.java b/buildSrc/src/main/java/org/springframework/boot/build/context/properties/SingleRow.java index 2ced4cf15d..65f6bb3625 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/context/properties/SingleRow.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/context/properties/SingleRow.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,8 +45,9 @@ class SingleRow extends Row { return null; } if (defaultValue.getClass().isArray()) { - return Arrays.stream((Object[]) defaultValue).map(Object::toString) - .collect(Collectors.joining("," + System.lineSeparator())); + return Arrays.stream((Object[]) defaultValue) + .map(Object::toString) + .collect(Collectors.joining("," + System.lineSeparator())); } return defaultValue.toString(); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/context/properties/Snippets.java b/buildSrc/src/main/java/org/springframework/boot/build/context/properties/Snippets.java index 0930b2f7fe..3e7d7ebf19 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/context/properties/Snippets.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/context/properties/Snippets.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,8 +52,10 @@ class Snippets { void writeTo(Path outputDirectory) throws IOException { createDirectory(outputDirectory); - Set remaining = this.properties.stream().filter((property) -> !property.isDeprecated()) - .map(ConfigurationProperty::getName).collect(Collectors.toSet()); + Set remaining = this.properties.stream() + .filter((property) -> !property.isDeprecated()) + .map(ConfigurationProperty::getName) + .collect(Collectors.toSet()); for (Snippet snippet : this.snippets) { Set written = writeSnippet(outputDirectory, snippet, remaining); remaining.removeAll(written); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/devtools/DocumentDevtoolsPropertyDefaults.java b/buildSrc/src/main/java/org/springframework/boot/build/devtools/DocumentDevtoolsPropertyDefaults.java index ef86b4a7ff..515228ce70 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/devtools/DocumentDevtoolsPropertyDefaults.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/devtools/DocumentDevtoolsPropertyDefaults.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +48,9 @@ public class DocumentDevtoolsPropertyDefaults extends DefaultTask { public DocumentDevtoolsPropertyDefaults() { this.devtools = getProject().getConfigurations().create("devtools"); this.outputFile = getProject().getObjects().fileProperty(); - this.outputFile.convention(getProject().getLayout().getBuildDirectory() - .file("docs/generated/using/devtools-property-defaults.adoc")); + this.outputFile.convention(getProject().getLayout() + .getBuildDirectory() + .file("docs/generated/using/devtools-property-defaults.adoc")); Map dependency = new HashMap<>(); dependency.put("path", ":spring-boot-project:spring-boot-devtools"); dependency.put("configuration", "propertyDefaults"); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/docs/ApplicationRunner.java b/buildSrc/src/main/java/org/springframework/boot/build/docs/ApplicationRunner.java index 1895bfde8b..325db94371 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/docs/ApplicationRunner.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/docs/ApplicationRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,8 +58,9 @@ public class ApplicationRunner extends DefaultTask { private final Property expectedLogging = getProject().getObjects().property(String.class); - private final Property applicationJar = getProject().getObjects().property(String.class) - .convention("/opt/apps/myapp.jar"); + private final Property applicationJar = getProject().getObjects() + .property(String.class) + .convention("/opt/apps/myapp.jar"); private final Map normalizations = new HashMap<>(); @@ -119,13 +120,17 @@ public class ApplicationRunner extends DefaultTask { File executable = Jvm.current().getExecutable("java"); command.add(executable.getAbsolutePath()); command.add("-cp"); - command.add(this.classpath.getFiles().stream().map(File::getAbsolutePath) - .collect(Collectors.joining(File.pathSeparator))); + command.add(this.classpath.getFiles() + .stream() + .map(File::getAbsolutePath) + .collect(Collectors.joining(File.pathSeparator))); command.add(this.mainClass.get()); command.addAll(this.args.get()); File outputFile = this.output.getAsFile().get(); - Process process = new ProcessBuilder().redirectOutput(outputFile).redirectError(outputFile).command(command) - .start(); + Process process = new ProcessBuilder().redirectOutput(outputFile) + .redirectError(outputFile) + .command(command) + .start(); awaitLogging(process); process.destroy(); normalizeLogging(); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/DocumentPluginGoals.java b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/DocumentPluginGoals.java index 58c41fa29d..0a0bac5556 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/DocumentPluginGoals.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/DocumentPluginGoals.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -98,10 +98,13 @@ public class DocumentPluginGoals extends DefaultTask { writer.printf("`%s:%s:%s`%n", plugin.getGroupId(), plugin.getArtifactId(), plugin.getVersion()); writer.println(); writer.println(mojo.getDescription()); - List parameters = mojo.getParameters().stream().filter(Parameter::isEditable) - .collect(Collectors.toList()); - List requiredParameters = parameters.stream().filter(Parameter::isRequired) - .collect(Collectors.toList()); + List parameters = mojo.getParameters() + .stream() + .filter(Parameter::isEditable) + .collect(Collectors.toList()); + List requiredParameters = parameters.stream() + .filter(Parameter::isRequired) + .collect(Collectors.toList()); String parametersSectionId = sectionId + "-parameters"; String detailsSectionId = parametersSectionId + "-details"; if (!requiredParameters.isEmpty()) { @@ -111,8 +114,9 @@ public class DocumentPluginGoals extends DefaultTask { writer.println("== Required parameters"); writeParametersTable(writer, detailsSectionId, requiredParameters); } - List optionalParameters = parameters.stream().filter((parameter) -> !parameter.isRequired()) - .collect(Collectors.toList()); + List optionalParameters = parameters.stream() + .filter((parameter) -> !parameter.isRequired()) + .collect(Collectors.toList()); if (!optionalParameters.isEmpty()) { writer.println(); writer.println(); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/MavenExec.java b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/MavenExec.java index d3e9875f4d..70339d0714 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/MavenExec.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/MavenExec.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,9 @@ public class MavenExec extends JavaExec { public void setProjectDir(File projectDir) { this.projectDir = projectDir; - getInputs().file(new File(projectDir, "pom.xml")).withPathSensitivity(PathSensitivity.RELATIVE) - .withPropertyName("pom"); + getInputs().file(new File(projectDir, "pom.xml")) + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName("pom"); } @Override @@ -88,10 +89,11 @@ public class MavenExec extends JavaExec { maven.getDependencies().add(project.getDependencies().create("org.apache.maven:maven-embedder:3.6.2")); maven.getDependencies().add(project.getDependencies().create("org.apache.maven:maven-compat:3.6.2")); maven.getDependencies().add(project.getDependencies().create("org.slf4j:slf4j-simple:1.7.5")); - maven.getDependencies().add( - project.getDependencies().create("org.apache.maven.resolver:maven-resolver-connector-basic:1.4.1")); - maven.getDependencies().add( - project.getDependencies().create("org.apache.maven.resolver:maven-resolver-transport-http:1.4.1")); + maven.getDependencies() + .add(project.getDependencies() + .create("org.apache.maven.resolver:maven-resolver-connector-basic:1.4.1")); + maven.getDependencies() + .add(project.getDependencies().create("org.apache.maven.resolver:maven-resolver-transport-http:1.4.1")); }); } 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 f57c996e71..950dffdf45 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -145,15 +145,15 @@ public class MavenPluginPlugin implements Plugin { private void addPopulateIntTestMavenRepositoryTask(Project project) { Configuration runtimeClasspathWithMetadata = project.getConfigurations().create("runtimeClasspathWithMetadata"); runtimeClasspathWithMetadata - .extendsFrom(project.getConfigurations().getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME)); + .extendsFrom(project.getConfigurations().getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME)); runtimeClasspathWithMetadata.attributes((attributes) -> attributes.attribute(DocsType.DOCS_TYPE_ATTRIBUTE, project.getObjects().named(DocsType.class, "maven-repository"))); RuntimeClasspathMavenRepository runtimeClasspathMavenRepository = project.getTasks() - .create("runtimeClasspathMavenRepository", RuntimeClasspathMavenRepository.class); + .create("runtimeClasspathMavenRepository", RuntimeClasspathMavenRepository.class); runtimeClasspathMavenRepository.getOutputDirectory() - .set(new File(project.getBuildDir(), "runtime-classpath-repository")); + .set(new File(project.getBuildDir(), "runtime-classpath-repository")); project.getDependencies() - .components((components) -> components.all(MavenRepositoryComponentMetadataRule.class)); + .components((components) -> components.all(MavenRepositoryComponentMetadataRule.class)); Sync task = project.getTasks().create("populateIntTestMavenRepository", Sync.class); task.setDestinationDir(new File(project.getBuildDir(), "int-test-maven-repository")); task.with(copyIntTestMavenRepositoryFiles(project, runtimeClasspathMavenRepository)); @@ -236,8 +236,8 @@ public class MavenPluginPlugin implements Plugin { private FormatHelpMojoSource createFormatHelpMojoSource(Project project, MavenExec generateHelpMojoTask, File generatedHelpMojoDir) { - FormatHelpMojoSource formatHelpMojoSource = project.getTasks().create("formatHelpMojoSource", - FormatHelpMojoSource.class); + FormatHelpMojoSource formatHelpMojoSource = project.getTasks() + .create("formatHelpMojoSource", FormatHelpMojoSource.class); formatHelpMojoSource.setGenerator(generateHelpMojoTask); formatHelpMojoSource.setOutputDir(generatedHelpMojoDir); return formatHelpMojoSource; @@ -258,8 +258,10 @@ public class MavenPluginPlugin implements Plugin { MavenExec generatePluginDescriptor = project.getTasks().create("generatePluginDescriptor", MavenExec.class); generatePluginDescriptor.args("org.apache.maven.plugins:maven-plugin-plugin:3.6.0:descriptor"); generatePluginDescriptor.getOutputs().dir(new File(mavenDir, "target/classes/META-INF/maven")); - generatePluginDescriptor.getInputs().dir(new File(mavenDir, "target/classes/org")) - .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("plugin classes"); + generatePluginDescriptor.getInputs() + .dir(new File(mavenDir, "target/classes/org")) + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName("plugin classes"); generatePluginDescriptor.setProjectDir(mavenDir); return generatePluginDescriptor; } @@ -284,10 +286,13 @@ public class MavenPluginPlugin implements Plugin { } private void addExtractVersionPropertiesTask(Project project) { - ExtractVersionProperties extractVersionProperties = project.getTasks().create("extractVersionProperties", - ExtractVersionProperties.class); + ExtractVersionProperties extractVersionProperties = project.getTasks() + .create("extractVersionProperties", ExtractVersionProperties.class); extractVersionProperties.setEffectiveBoms(project.getConfigurations().create("versionProperties")); - extractVersionProperties.getDestination().set(project.getLayout().getBuildDirectory().dir("generated-resources") + extractVersionProperties.getDestination() + .set(project.getLayout() + .getBuildDirectory() + .dir("generated-resources") .map((dir) -> dir.file("extracted-versions.properties"))); } @@ -299,8 +304,9 @@ public class MavenPluginPlugin implements Plugin { void setGenerator(Task generator) { this.generator = generator; - getInputs().files(this.generator).withPathSensitivity(PathSensitivity.RELATIVE) - .withPropertyName("generated source"); + getInputs().files(this.generator) + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName("generated source"); } @OutputDirectory @@ -317,7 +323,7 @@ public class MavenPluginPlugin implements Plugin { FileFormatter formatter = new FileFormatter(FORMATTER_CONFIG); for (File output : this.generator.getOutputs().getFiles()) { formatter.formatFiles(getProject().fileTree(output), StandardCharsets.UTF_8) - .forEach((edit) -> save(output, edit)); + .forEach((edit) -> save(output, edit)); } } @@ -346,10 +352,11 @@ public class MavenPluginPlugin implements Plugin { @Override public void execute(ComponentMetadataContext context) { - context.getDetails().maybeAddVariant("compileWithMetadata", "compile", - (variant) -> configureVariant(context, variant)); - context.getDetails().maybeAddVariant("apiElementsWithMetadata", "apiElements", - (variant) -> configureVariant(context, variant)); + context.getDetails() + .maybeAddVariant("compileWithMetadata", "compile", (variant) -> configureVariant(context, variant)); + context.getDetails() + .maybeAddVariant("apiElementsWithMetadata", "apiElements", + (variant) -> configureVariant(context, variant)); } private void configureVariant(ComponentMetadataContext context, VariantMetadata variant) { @@ -392,12 +399,15 @@ public class MavenPluginPlugin implements Plugin { for (ResolvedArtifactResult result : this.runtimeClasspath.getIncoming().getArtifacts()) { if (result.getId().getComponentIdentifier() instanceof ModuleComponentIdentifier) { ModuleComponentIdentifier identifier = (ModuleComponentIdentifier) result.getId() - .getComponentIdentifier(); - String fileName = result.getFile().getName() - .replace(identifier.getVersion() + "-" + identifier.getVersion(), identifier.getVersion()); - File repositoryLocation = this.outputDirectory.dir(identifier.getGroup().replace('.', '/') + "/" - + identifier.getModule() + "/" + identifier.getVersion() + "/" + fileName).get() - .getAsFile(); + .getComponentIdentifier(); + String fileName = result.getFile() + .getName() + .replace(identifier.getVersion() + "-" + identifier.getVersion(), identifier.getVersion()); + File repositoryLocation = this.outputDirectory + .dir(identifier.getGroup().replace('.', '/') + "/" + identifier.getModule() + "/" + + identifier.getVersion() + "/" + fileName) + .get() + .getAsFile(); repositoryLocation.getParentFile().mkdirs(); try { Files.copy(result.getFile().toPath(), repositoryLocation.toPath(), @@ -504,8 +514,8 @@ public class MavenPluginPlugin implements Plugin { private String get(String expression) { try { - Node node = (Node) this.xpath.compile("/project/" + expression).evaluate(this.document, - XPathConstants.NODE); + Node node = (Node) this.xpath.compile("/project/" + expression) + .evaluate(this.document, XPathConstants.NODE); String text = (node != null) ? node.getTextContent() : null; Assert.hasLength(text, () -> "No result for expression " + expression); return text; diff --git a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/PluginXmlParser.java b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/PluginXmlParser.java index 19f66707e7..c3186f1777 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/PluginXmlParser.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/PluginXmlParser.java @@ -111,10 +111,17 @@ class PluginXmlParser { } private String format(String input) { - return input.replace("", "`").replace("", "`").replace("<", "<").replace(">", ">") - .replace("
", " ").replace("\n", " ").replace(""", "\"").replaceAll("\\{@code (.*?)}", "`$1`") - .replaceAll("\\{@link (.*?)}", "`$1`").replaceAll("\\{@literal (.*?)}", "`$1`") - .replaceAll("(.*?)", "$1[$2]"); + return input.replace("", "`") + .replace("", "`") + .replace("<", "<") + .replace(">", ">") + .replace("
", " ") + .replace("\n", " ") + .replace(""", "\"") + .replaceAll("\\{@code (.*?)}", "`$1`") + .replaceAll("\\{@link (.*?)}", "`$1`") + .replaceAll("\\{@literal (.*?)}", "`$1`") + .replaceAll("(.*?)", "$1[$2]"); } private static final class IterableNodeList implements Iterable { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/PrepareMavenBinaries.java b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/PrepareMavenBinaries.java index a94da2e4fd..b85b24e43b 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/PrepareMavenBinaries.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/PrepareMavenBinaries.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,10 +60,11 @@ public class PrepareMavenBinaries extends DefaultTask { @TaskAction public void prepareBinaries() { for (String version : this.versions) { - Configuration configuration = getProject().getConfigurations().detachedConfiguration( - getProject().getDependencies().create("org.apache.maven:apache-maven:" + version + ":bin@zip")); - getProject().copy( - (copy) -> copy.into(this.outputDir).from(getProject().zipTree(configuration.getSingleFile()))); + Configuration configuration = getProject().getConfigurations() + .detachedConfiguration( + getProject().getDependencies().create("org.apache.maven:apache-maven:" + version + ":bin@zip")); + getProject() + .copy((copy) -> copy.into(this.outputDir).from(getProject().zipTree(configuration.getSingleFile()))); } } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/optional/OptionalDependenciesPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/optional/OptionalDependenciesPlugin.java index 8b37308b15..9dfdfa5176 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/optional/OptionalDependenciesPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/optional/OptionalDependenciesPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,13 +44,16 @@ public class OptionalDependenciesPlugin implements Plugin { optional.setCanBeConsumed(false); optional.setCanBeResolved(false); project.getPlugins().withType(JavaPlugin.class, (javaPlugin) -> { - SourceSetContainer sourceSets = project.getExtensions().getByType(JavaPluginExtension.class) - .getSourceSets(); + SourceSetContainer sourceSets = project.getExtensions() + .getByType(JavaPluginExtension.class) + .getSourceSets(); sourceSets.all((sourceSet) -> { - project.getConfigurations().getByName(sourceSet.getCompileClasspathConfigurationName()) - .extendsFrom(optional); - project.getConfigurations().getByName(sourceSet.getRuntimeClasspathConfigurationName()) - .extendsFrom(optional); + project.getConfigurations() + .getByName(sourceSet.getCompileClasspathConfigurationName()) + .extendsFrom(optional); + project.getConfigurations() + .getByName(sourceSet.getRuntimeClasspathConfigurationName()) + .extendsFrom(optional); }); }); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/starters/DocumentStarters.java b/buildSrc/src/main/java/org/springframework/boot/build/starters/DocumentStarters.java index 52eab4dd80..669eeb40a0 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/starters/DocumentStarters.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/starters/DocumentStarters.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -84,8 +84,10 @@ public class DocumentStarters extends DefaultTask { @TaskAction void documentStarters() { - Set starters = this.starters.getFiles().stream().map(this::loadStarter) - .collect(Collectors.toCollection(TreeSet::new)); + Set starters = this.starters.getFiles() + .stream() + .map(this::loadStarter) + .collect(Collectors.toCollection(TreeSet::new)); writeTable("application-starters", starters.stream().filter(Starter::isApplication)); writeTable("production-starters", starters.stream().filter(Starter::isProduction)); writeTable("technical-starters", starters.stream().filter(Starter::isTechnical)); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/starters/StarterMetadata.java b/buildSrc/src/main/java/org/springframework/boot/build/starters/StarterMetadata.java index 38ce419760..4125182d6e 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/starters/StarterMetadata.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/starters/StarterMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,8 +73,13 @@ public class StarterMetadata extends DefaultTask { Properties properties = CollectionFactory.createSortedProperties(true); properties.setProperty("name", getProject().getName()); properties.setProperty("description", getProject().getDescription()); - properties.setProperty("dependencies", String.join(",", this.dependencies.getResolvedConfiguration() - .getResolvedArtifacts().stream().map(ResolvedArtifact::getName).collect(Collectors.toSet()))); + properties.setProperty("dependencies", + String.join(",", + this.dependencies.getResolvedConfiguration() + .getResolvedArtifacts() + .stream() + .map(ResolvedArtifact::getName) + .collect(Collectors.toSet()))); this.destination.getParentFile().mkdirs(); try (FileWriter writer = new FileWriter(this.destination)) { properties.store(writer, null); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/starters/StarterPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/starters/StarterPlugin.java index ec39845573..846efd43be 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/starters/StarterPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/starters/StarterPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,25 +58,26 @@ public class StarterPlugin implements Plugin { File destination = new File(project.getBuildDir(), "starter-metadata.properties"); starterMetadata.setDestination(destination); configurations.create("starterMetadata"); - project.getArtifacts().add("starterMetadata", project.provider(starterMetadata::getDestination), - (artifact) -> artifact.builtBy(starterMetadata)); + project.getArtifacts() + .add("starterMetadata", project.provider(starterMetadata::getDestination), + (artifact) -> artifact.builtBy(starterMetadata)); createClasspathConflictsCheck(runtimeClasspath, project); createUnnecessaryExclusionsCheck(runtimeClasspath, project); configureJarManifest(project); } private void createClasspathConflictsCheck(Configuration classpath, Project project) { - CheckClasspathForConflicts checkClasspathForConflicts = project.getTasks().create( - "check" + StringUtils.capitalize(classpath.getName() + "ForConflicts"), - CheckClasspathForConflicts.class); + CheckClasspathForConflicts checkClasspathForConflicts = project.getTasks() + .create("check" + StringUtils.capitalize(classpath.getName() + "ForConflicts"), + CheckClasspathForConflicts.class); checkClasspathForConflicts.setClasspath(classpath); project.getTasks().getByName(JavaBasePlugin.CHECK_TASK_NAME).dependsOn(checkClasspathForConflicts); } private void createUnnecessaryExclusionsCheck(Configuration classpath, Project project) { - CheckClasspathForUnnecessaryExclusions checkClasspathForUnnecessaryExclusions = project.getTasks().create( - "check" + StringUtils.capitalize(classpath.getName() + "ForUnnecessaryExclusions"), - CheckClasspathForUnnecessaryExclusions.class); + CheckClasspathForUnnecessaryExclusions checkClasspathForUnnecessaryExclusions = project.getTasks() + .create("check" + StringUtils.capitalize(classpath.getName() + "ForUnnecessaryExclusions"), + CheckClasspathForUnnecessaryExclusions.class); checkClasspathForUnnecessaryExclusions.setClasspath(classpath); project.getTasks().getByName(JavaBasePlugin.CHECK_TASK_NAME).dependsOn(checkClasspathForUnnecessaryExclusions); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/test/IntegrationTestPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/test/IntegrationTestPlugin.java index 29af0140d2..6286df7601 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/test/IntegrationTestPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/test/IntegrationTestPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,8 +55,8 @@ public class IntegrationTestPlugin implements Plugin { project.getTasks().getByName(LifecycleBasePlugin.CHECK_TASK_NAME).dependsOn(intTest); project.getPlugins().withType(EclipsePlugin.class, (eclipsePlugin) -> { EclipseModel eclipse = project.getExtensions().getByType(EclipseModel.class); - eclipse.classpath((classpath) -> classpath.getPlusConfigurations().add( - project.getConfigurations().getByName(intTestSourceSet.getRuntimeClasspathConfigurationName()))); + eclipse.classpath((classpath) -> classpath.getPlusConfigurations() + .add(project.getConfigurations().getByName(intTestSourceSet.getRuntimeClasspathConfigurationName()))); }); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/test/SystemTestPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/test/SystemTestPlugin.java index 777e94fafc..9259f8e369 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/test/SystemTestPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/test/SystemTestPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,8 +59,9 @@ public class SystemTestPlugin implements Plugin { createTestTask(project, systemTestSourceSet); project.getPlugins().withType(EclipsePlugin.class, (eclipsePlugin) -> { EclipseModel eclipse = project.getExtensions().getByType(EclipseModel.class); - eclipse.classpath((classpath) -> classpath.getPlusConfigurations().add( - project.getConfigurations().getByName(systemTestSourceSet.getRuntimeClasspathConfigurationName()))); + eclipse.classpath((classpath) -> classpath.getPlusConfigurations() + .add(project.getConfigurations() + .getByName(systemTestSourceSet.getRuntimeClasspathConfigurationName()))); }); } @@ -69,9 +70,9 @@ public class SystemTestPlugin implements Plugin { SourceSet systemTestSourceSet = sourceSets.create(SYSTEM_TEST_SOURCE_SET_NAME); SourceSet mainSourceSet = sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME); systemTestSourceSet - .setCompileClasspath(systemTestSourceSet.getCompileClasspath().plus(mainSourceSet.getOutput())); + .setCompileClasspath(systemTestSourceSet.getCompileClasspath().plus(mainSourceSet.getOutput())); systemTestSourceSet - .setRuntimeClasspath(systemTestSourceSet.getRuntimeClasspath().plus(mainSourceSet.getOutput())); + .setRuntimeClasspath(systemTestSourceSet.getRuntimeClasspath().plus(mainSourceSet.getOutput())); return systemTestSourceSet; } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/test/autoconfigure/TestSliceMetadata.java b/buildSrc/src/main/java/org/springframework/boot/build/test/autoconfigure/TestSliceMetadata.java index 598ed89954..c32073f492 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/test/autoconfigure/TestSliceMetadata.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/test/autoconfigure/TestSliceMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,9 +67,11 @@ public class TestSliceMetadata extends DefaultTask { public TestSliceMetadata() { getInputs().dir((Callable) () -> this.sourceSet.getOutput().getResourcesDir()) - .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("resources"); + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName("resources"); getInputs().files((Callable) () -> this.sourceSet.getOutput().getClassesDirs()) - .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("classes"); + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName("classes"); } public void setSourceSet(SourceSet sourceSet) { @@ -84,8 +86,9 @@ public class TestSliceMetadata extends DefaultTask { public void setOutputFile(File outputFile) { this.outputFile = outputFile; Configuration testSliceMetadata = getProject().getConfigurations().maybeCreate("testSliceMetadata"); - getProject().getArtifacts().add(testSliceMetadata.getName(), - getProject().provider((Callable) this::getOutputFile), (artifact) -> artifact.builtBy(this)); + getProject().getArtifacts() + .add(testSliceMetadata.getName(), getProject().provider((Callable) this::getOutputFile), + (artifact) -> artifact.builtBy(this)); } @TaskAction @@ -100,8 +103,9 @@ public class TestSliceMetadata extends DefaultTask { private Properties readTestSlices() throws IOException { Properties testSlices = CollectionFactory.createSortedProperties(true); try (URLClassLoader classLoader = new URLClassLoader( - StreamSupport.stream(this.sourceSet.getRuntimeClasspath().spliterator(), false).map(this::toURL) - .toArray(URL[]::new))) { + StreamSupport.stream(this.sourceSet.getRuntimeClasspath().spliterator(), false) + .map(this::toURL) + .toArray(URL[]::new))) { MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(classLoader); Properties springFactories = readSpringFactories( new File(this.sourceSet.getOutput().getResourcesDir(), "META-INF/spring.factories")); @@ -129,8 +133,8 @@ public class TestSliceMetadata extends DefaultTask { for (File file : files) { try { List lines = removeComments(Files.readAllLines(file.toPath())); - String fileNameWithoutExtension = file.getName().substring(0, - file.getName().length() - ".imports".length()); + String fileNameWithoutExtension = file.getName() + .substring(0, file.getName().length() - ".imports".length()); springFactories.setProperty(fileNameWithoutExtension, StringUtils.collectionToCommaDelimitedString(lines)); } @@ -176,9 +180,9 @@ public class TestSliceMetadata extends DefaultTask { Properties springFactories) throws IOException { try (Stream classes = Files.walk(classesDir.toPath())) { classes.filter((path) -> path.toString().endsWith("Test.class")) - .map((path) -> getMetadataReader(path, metadataReaderFactory)) - .filter((metadataReader) -> metadataReader.getClassMetadata().isAnnotation()) - .forEach((metadataReader) -> addTestSlice(testSlices, springFactories, metadataReader)); + .map((path) -> getMetadataReader(path, metadataReaderFactory)) + .filter((metadataReader) -> metadataReader.getClassMetadata().isAnnotation()) + .forEach((metadataReader) -> addTestSlice(testSlices, springFactories, metadataReader)); } } @@ -204,19 +208,20 @@ public class TestSliceMetadata extends DefaultTask { if (annotationMetadata.isAnnotated("org.springframework.boot.autoconfigure.ImportAutoConfiguration")) { importers = Stream.concat(importers, Stream.of(annotationMetadata.getClassName())); } - return importers.flatMap( - (importer) -> StringUtils.commaDelimitedListToSet(springFactories.getProperty(importer)).stream()) - .collect(Collectors.toCollection(TreeSet::new)); + return importers + .flatMap((importer) -> StringUtils.commaDelimitedListToSet(springFactories.getProperty(importer)).stream()) + .collect(Collectors.toCollection(TreeSet::new)); } private Stream findMetaImporters(AnnotationMetadata annotationMetadata) { - return annotationMetadata.getAnnotationTypes().stream() - .filter((annotationType) -> isAutoConfigurationImporter(annotationType, annotationMetadata)); + return annotationMetadata.getAnnotationTypes() + .stream() + .filter((annotationType) -> isAutoConfigurationImporter(annotationType, annotationMetadata)); } private boolean isAutoConfigurationImporter(String annotationType, AnnotationMetadata metadata) { return metadata.getMetaAnnotationTypes(annotationType) - .contains("org.springframework.boot.autoconfigure.ImportAutoConfiguration"); + .contains("org.springframework.boot.autoconfigure.ImportAutoConfiguration"); } } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/testing/TestFailuresPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/testing/TestFailuresPlugin.java index 6fdb9bec49..f9ebc52f78 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/testing/TestFailuresPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/testing/TestFailuresPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,11 +36,13 @@ public class TestFailuresPlugin implements Plugin { @Override public void apply(Project project) { - Provider testResultsOverview = project.getGradle().getSharedServices() - .registerIfAbsent("testResultsOverview", TestResultsOverview.class, (spec) -> { - }); - project.getTasks().withType(Test.class, - (test) -> test.addTestListener(new FailureRecordingTestListener(testResultsOverview, test))); + Provider testResultsOverview = project.getGradle() + .getSharedServices() + .registerIfAbsent("testResultsOverview", TestResultsOverview.class, (spec) -> { + }); + project.getTasks() + .withType(Test.class, + (test) -> test.addTestListener(new FailureRecordingTestListener(testResultsOverview, test))); } private final class FailureRecordingTestListener implements TestListener { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/testing/TestResultsOverview.java b/buildSrc/src/main/java/org/springframework/boot/build/testing/TestResultsOverview.java index 545e8c9086..4d58809bef 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/testing/TestResultsOverview.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/testing/TestResultsOverview.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,10 @@ public abstract class TestResultsOverview private final Object monitor = new Object(); void addFailures(Test test, List failureDescriptors) { - List testFailures = failureDescriptors.stream().map(TestFailure::new).sorted() - .collect(Collectors.toList()); + List testFailures = failureDescriptors.stream() + .map(TestFailure::new) + .sorted() + .collect(Collectors.toList()); synchronized (this.monitor) { this.testFailures.put(test, testFailures); } @@ -67,7 +69,7 @@ public abstract class TestResultsOverview System.err.println(); System.err.println(task.getPath()); failures.forEach((failure) -> System.err - .println(" " + failure.descriptor.getClassName() + " > " + failure.descriptor.getName())); + .println(" " + failure.descriptor.getClassName() + " > " + failure.descriptor.getName())); }); } } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/toolchain/ToolchainPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/toolchain/ToolchainPlugin.java index 395209c81a..82abe1cd65 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/toolchain/ToolchainPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/toolchain/ToolchainPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,16 +52,18 @@ public class ToolchainPlugin implements Plugin { disableToolchainTasks(project); } else { - JavaToolchainSpec toolchainSpec = project.getExtensions().getByType(JavaPluginExtension.class) - .getToolchain(); + JavaToolchainSpec toolchainSpec = project.getExtensions() + .getByType(JavaPluginExtension.class) + .getToolchain(); toolchainSpec.getLanguageVersion().set(toolchain.getJavaVersion()); configureTestToolchain(project, toolchain); } } private boolean isJavaVersionSupported(ToolchainExtension toolchain, JavaLanguageVersion toolchainVersion) { - return toolchain.getMaximumCompatibleJavaVersion().map((version) -> version.canCompileOrRun(toolchainVersion)) - .getOrElse(true); + return toolchain.getMaximumCompatibleJavaVersion() + .map((version) -> version.canCompileOrRun(toolchainVersion)) + .getOrElse(true); } private void disableToolchainTasks(Project project) { diff --git a/buildSrc/src/test/java/org/springframework/boot/build/ConventionsPluginTests.java b/buildSrc/src/test/java/org/springframework/boot/build/ConventionsPluginTests.java index 3665e04e32..5e15a9c8ef 100644 --- a/buildSrc/src/test/java/org/springframework/boot/build/ConventionsPluginTests.java +++ b/buildSrc/src/test/java/org/springframework/boot/build/ConventionsPluginTests.java @@ -88,9 +88,9 @@ class ConventionsPluginTests { assertThatNoticeIsPresent(jar); Attributes mainAttributes = jar.getManifest().getMainAttributes(); assertThat(mainAttributes.getValue("Implementation-Title")) - .isEqualTo("Test project for manifest customization"); + .isEqualTo("Test project for manifest customization"); assertThat(mainAttributes.getValue("Automatic-Module-Name")) - .isEqualTo(this.projectDir.getName().replace("-", ".")); + .isEqualTo(this.projectDir.getName().replace("-", ".")); assertThat(mainAttributes.getValue("Implementation-Version")).isEqualTo("1.2.3"); assertThat(mainAttributes.getValue("Built-By")).isEqualTo("Spring"); assertThat(mainAttributes.getValue("Build-Jdk-Spec")).isEqualTo("1.8"); @@ -117,9 +117,9 @@ class ConventionsPluginTests { assertThatNoticeIsPresent(jar); Attributes mainAttributes = jar.getManifest().getMainAttributes(); assertThat(mainAttributes.getValue("Implementation-Title")) - .isEqualTo("Source for " + this.projectDir.getName()); + .isEqualTo("Source for " + this.projectDir.getName()); assertThat(mainAttributes.getValue("Automatic-Module-Name")) - .isEqualTo(this.projectDir.getName().replace("-", ".")); + .isEqualTo(this.projectDir.getName().replace("-", ".")); assertThat(mainAttributes.getValue("Implementation-Version")).isEqualTo("1.2.3"); assertThat(mainAttributes.getValue("Built-By")).isEqualTo("Spring"); assertThat(mainAttributes.getValue("Build-Jdk-Spec")).isEqualTo("1.8"); @@ -146,9 +146,9 @@ class ConventionsPluginTests { assertThatNoticeIsPresent(jar); Attributes mainAttributes = jar.getManifest().getMainAttributes(); assertThat(mainAttributes.getValue("Implementation-Title")) - .isEqualTo("Javadoc for " + this.projectDir.getName()); + .isEqualTo("Javadoc for " + this.projectDir.getName()); assertThat(mainAttributes.getValue("Automatic-Module-Name")) - .isEqualTo(this.projectDir.getName().replace("-", ".")); + .isEqualTo(this.projectDir.getName().replace("-", ".")); assertThat(mainAttributes.getValue("Implementation-Version")).isEqualTo("1.2.3"); assertThat(mainAttributes.getValue("Built-By")).isEqualTo("Spring"); assertThat(mainAttributes.getValue("Build-Jdk-Spec")).isEqualTo("1.8"); @@ -186,7 +186,8 @@ class ConventionsPluginTests { out.println("}"); } assertThat(runGradle(Collections.singletonMap("CI", "true"), "retryConfig", "--stacktrace").getOutput()) - .contains("maxRetries: 3").contains("failOnPassedAfterRetry: true"); + .contains("maxRetries: 3") + .contains("failOnPassedAfterRetry: true"); } @Test @@ -207,7 +208,8 @@ class ConventionsPluginTests { out.println("}"); } assertThat(runGradle(Collections.singletonMap("CI", "local"), "retryConfig", "--stacktrace").getOutput()) - .contains("maxRetries: 0").contains("failOnPassedAfterRetry: true"); + .contains("maxRetries: 0") + .contains("failOnPassedAfterRetry: true"); } private BuildResult runGradle(String... args) { @@ -215,8 +217,12 @@ class ConventionsPluginTests { } private BuildResult runGradle(Map environment, String... args) { - return GradleRunner.create().withProjectDir(this.projectDir).withEnvironment(environment).withArguments(args) - .withPluginClasspath().build(); + return GradleRunner.create() + .withProjectDir(this.projectDir) + .withEnvironment(environment) + .withArguments(args) + .withPluginClasspath() + .build(); } } diff --git a/buildSrc/src/test/java/org/springframework/boot/build/architecture/PackageTangleCheckTests.java b/buildSrc/src/test/java/org/springframework/boot/build/architecture/PackageTangleCheckTests.java index 78133c063d..a0909e6f8a 100644 --- a/buildSrc/src/test/java/org/springframework/boot/build/architecture/PackageTangleCheckTests.java +++ b/buildSrc/src/test/java/org/springframework/boot/build/architecture/PackageTangleCheckTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,10 +46,11 @@ class PackageTangleCheckTests { void whenPackagesAreTangledTaskFailsAndWritesAReport() throws Exception { prepareTask("tangled", (packageTangleCheck) -> { assertThatExceptionOfType(GradleException.class) - .isThrownBy(() -> packageTangleCheck.checkForPackageTangles()); + .isThrownBy(() -> packageTangleCheck.checkForPackageTangles()); assertThat( new File(packageTangleCheck.getProject().getBuildDir(), "checkForPackageTangles/failure-report.txt") - .length()).isGreaterThan(0); + .length()) + .isGreaterThan(0); }); } @@ -59,7 +60,8 @@ class PackageTangleCheckTests { packageTangleCheck.checkForPackageTangles(); assertThat( new File(packageTangleCheck.getProject().getBuildDir(), "checkForPackageTangles/failure-report.txt") - .length()).isEqualTo(0); + .length()) + .isEqualTo(0); }); } @@ -68,8 +70,9 @@ class PackageTangleCheckTests { projectDir.mkdirs(); copyClasses(classes, projectDir); Project project = ProjectBuilder.builder().withProjectDir(projectDir).build(); - PackageTangleCheck packageTangleCheck = project.getTasks().create("checkForPackageTangles", - PackageTangleCheck.class, (task) -> task.setClasses(project.files("classes"))); + PackageTangleCheck packageTangleCheck = project.getTasks() + .create("checkForPackageTangles", PackageTangleCheck.class, + (task) -> task.setClasses(project.files("classes"))); callback.accept(packageTangleCheck); } diff --git a/buildSrc/src/test/java/org/springframework/boot/build/artifacts/ArtifactReleaseTests.java b/buildSrc/src/test/java/org/springframework/boot/build/artifacts/ArtifactReleaseTests.java index 0a9d5e420a..48ae5db62e 100644 --- a/buildSrc/src/test/java/org/springframework/boot/build/artifacts/ArtifactReleaseTests.java +++ b/buildSrc/src/test/java/org/springframework/boot/build/artifacts/ArtifactReleaseTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -84,7 +84,7 @@ class ArtifactReleaseTests { Project project = ProjectBuilder.builder().build(); project.setVersion("1.2.3"); assertThat(ArtifactRelease.forProject(project).getDownloadRepo()) - .contains("https://repo.maven.apache.org/maven2"); + .contains("https://repo.maven.apache.org/maven2"); } } diff --git a/buildSrc/src/test/java/org/springframework/boot/build/bom/BomPluginIntegrationTests.java b/buildSrc/src/test/java/org/springframework/boot/build/bom/BomPluginIntegrationTests.java index 6bc78ebc58..d6baf87b88 100644 --- a/buildSrc/src/test/java/org/springframework/boot/build/bom/BomPluginIntegrationTests.java +++ b/buildSrc/src/test/java/org/springframework/boot/build/bom/BomPluginIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -319,8 +319,12 @@ class BomPluginIntegrationTests { // } private BuildResult runGradle(String... args) { - return GradleRunner.create().withDebug(true).withProjectDir(this.projectDir).withArguments(args) - .withPluginClasspath().build(); + return GradleRunner.create() + .withDebug(true) + .withProjectDir(this.projectDir) + .withArguments(args) + .withPluginClasspath() + .build(); } private void generatePom(Consumer consumer) { diff --git a/buildSrc/src/test/java/org/springframework/boot/build/context/properties/ConfigurationPropertiesTests.java b/buildSrc/src/test/java/org/springframework/boot/build/context/properties/ConfigurationPropertiesTests.java index 7ab586bc68..5474d4aca0 100644 --- a/buildSrc/src/test/java/org/springframework/boot/build/context/properties/ConfigurationPropertiesTests.java +++ b/buildSrc/src/test/java/org/springframework/boot/build/context/properties/ConfigurationPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ class ConfigurationPropertiesTests { @Test void whenJsonHasAnIntegerDefaultValueThenItRemainsAnIntegerWhenRead() { ConfigurationProperties properties = ConfigurationProperties - .fromFiles(Arrays.asList(new File("src/test/resources/spring-configuration-metadata.json"))); + .fromFiles(Arrays.asList(new File("src/test/resources/spring-configuration-metadata.json"))); assertThat(properties.get("example.counter").getDefaultValue()).isEqualTo(0); } diff --git a/buildSrc/src/test/java/org/springframework/boot/build/context/properties/SingleRowTests.java b/buildSrc/src/test/java/org/springframework/boot/build/context/properties/SingleRowTests.java index 756ab4ce9b..f9b989c30b 100644 --- a/buildSrc/src/test/java/org/springframework/boot/build/context/properties/SingleRowTests.java +++ b/buildSrc/src/test/java/org/springframework/boot/build/context/properties/SingleRowTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -94,8 +94,8 @@ class SingleRowTests { Asciidoc asciidoc = new Asciidoc(); row.write(asciidoc); assertThat(asciidoc.toString()) - .isEqualTo("|[[my.spring.test.prop]]<>" + NEWLINE - + "|+++This is a description.+++" + NEWLINE + "|" + NEWLINE); + .isEqualTo("|[[my.spring.test.prop]]<>" + NEWLINE + + "|+++This is a description.+++" + NEWLINE + "|" + NEWLINE); } @Test diff --git a/buildSrc/src/test/java/org/springframework/boot/build/mavenplugin/PluginXmlParserTests.java b/buildSrc/src/test/java/org/springframework/boot/build/mavenplugin/PluginXmlParserTests.java index e5753824b9..788dc7222d 100644 --- a/buildSrc/src/test/java/org/springframework/boot/build/mavenplugin/PluginXmlParserTests.java +++ b/buildSrc/src/test/java/org/springframework/boot/build/mavenplugin/PluginXmlParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,13 +45,14 @@ class PluginXmlParserTests { assertThat(plugin.getVersion()).isEqualTo("2.2.0.GRADLE-SNAPSHOT"); assertThat(plugin.getGoalPrefix()).isEqualTo("spring-boot"); assertThat(plugin.getMojos().stream().map(PluginXmlParser.Mojo::getGoal).collect(Collectors.toList())) - .containsExactly("build-info", "help", "repackage", "run", "start", "stop"); + .containsExactly("build-info", "help", "repackage", "run", "start", "stop"); } @Test void parseNonExistingFileThrowException() { assertThatThrownBy(() -> this.parser.parse(new File("src/test/resources/nonexistent.xml"))) - .isInstanceOf(RuntimeException.class).hasCauseInstanceOf(FileNotFoundException.class); + .isInstanceOf(RuntimeException.class) + .hasCauseInstanceOf(FileNotFoundException.class); } } diff --git a/buildSrc/src/test/java/org/springframework/boot/build/testing/TestFailuresPluginIntegrationTests.java b/buildSrc/src/test/java/org/springframework/boot/build/testing/TestFailuresPluginIntegrationTests.java index a3088d59e6..cf08854fee 100644 --- a/buildSrc/src/test/java/org/springframework/boot/build/testing/TestFailuresPluginIntegrationTests.java +++ b/buildSrc/src/test/java/org/springframework/boot/build/testing/TestFailuresPluginIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,12 @@ class TestFailuresPluginIntegrationTests { @Test void singleProject() { createProject(this.projectDir); - BuildResult result = GradleRunner.create().withDebug(true).withProjectDir(this.projectDir) - .withArguments("build").withPluginClasspath().buildAndFail(); + BuildResult result = GradleRunner.create() + .withDebug(true) + .withProjectDir(this.projectDir) + .withArguments("build") + .withPluginClasspath() + .buildAndFail(); assertThat(readLines(result.getOutput())).containsSequence("Found test failures in 1 test task:", "", ":test", " example.ExampleTests > bad()", " example.ExampleTests > fail()", " example.MoreTests > bad()", " example.MoreTests > fail()", ""); @@ -61,8 +65,12 @@ class TestFailuresPluginIntegrationTests { @Test void multiProject() { createMultiProjectBuild(); - BuildResult result = GradleRunner.create().withDebug(true).withProjectDir(this.projectDir) - .withArguments("build").withPluginClasspath().buildAndFail(); + BuildResult result = GradleRunner.create() + .withDebug(true) + .withProjectDir(this.projectDir) + .withArguments("build") + .withPluginClasspath() + .buildAndFail(); assertThat(readLines(result.getOutput())).containsSequence("Found test failures in 1 test task:", "", ":project-one:test", " example.ExampleTests > bad()", " example.ExampleTests > fail()", " example.MoreTests > bad()", " example.MoreTests > fail()", ""); @@ -71,8 +79,12 @@ class TestFailuresPluginIntegrationTests { @Test void multiProjectContinue() { createMultiProjectBuild(); - BuildResult result = GradleRunner.create().withDebug(true).withProjectDir(this.projectDir) - .withArguments("build", "--continue").withPluginClasspath().buildAndFail(); + BuildResult result = GradleRunner.create() + .withDebug(true) + .withProjectDir(this.projectDir) + .withArguments("build", "--continue") + .withPluginClasspath() + .buildAndFail(); assertThat(readLines(result.getOutput())).containsSequence("Found test failures in 2 test tasks:", "", ":project-one:test", " example.ExampleTests > bad()", " example.ExampleTests > fail()", " example.MoreTests > bad()", " example.MoreTests > fail()", "", ":project-two:test", @@ -83,8 +95,12 @@ class TestFailuresPluginIntegrationTests { @Test void multiProjectParallel() { createMultiProjectBuild(); - BuildResult result = GradleRunner.create().withDebug(true).withProjectDir(this.projectDir) - .withArguments("build", "--parallel", "--stacktrace").withPluginClasspath().buildAndFail(); + BuildResult result = GradleRunner.create() + .withDebug(true) + .withProjectDir(this.projectDir) + .withArguments("build", "--parallel", "--stacktrace") + .withPluginClasspath() + .buildAndFail(); assertThat(readLines(result.getOutput())).containsSequence("Found test failures in 2 test tasks:", "", ":project-one:test", " example.ExampleTests > bad()", " example.ExampleTests > fail()", " example.MoreTests > bad()", " example.MoreTests > fail()", "", ":project-two:test", diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/OnEndpointElementCondition.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/OnEndpointElementCondition.java index 49c03b2916..5b32336d98 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/OnEndpointElementCondition.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/OnEndpointElementCondition.java @@ -48,7 +48,7 @@ public abstract class OnEndpointElementCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { AnnotationAttributes annotationAttributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(this.annotationType.getName())); + .fromMap(metadata.getAnnotationAttributes(this.annotationType.getName())); String endpointName = annotationAttributes.getString("value"); ConditionOutcome outcome = getEndpointOutcome(context, endpointName); if (outcome != null) { @@ -63,7 +63,7 @@ public abstract class OnEndpointElementCondition extends SpringBootCondition { if (environment.containsProperty(enabledProperty)) { boolean match = environment.getProperty(enabledProperty, Boolean.class, true); return new ConditionOutcome(match, ConditionMessage.forCondition(this.annotationType) - .because(this.prefix + endpointName + ".enabled is " + match)); + .because(this.prefix + endpointName + ".enabled is " + match)); } return null; } @@ -91,9 +91,9 @@ public abstract class OnEndpointElementCondition extends SpringBootCondition { @Deprecated protected ConditionOutcome getDefaultEndpointsOutcome(ConditionContext context) { boolean match = Boolean - .parseBoolean(context.getEnvironment().getProperty(this.prefix + "defaults.enabled", "true")); + .parseBoolean(context.getEnvironment().getProperty(this.prefix + "defaults.enabled", "true")); return new ConditionOutcome(match, ConditionMessage.forCondition(this.annotationType) - .because(this.prefix + "defaults.enabled is considered " + match)); + .because(this.prefix + "defaults.enabled is considered " + match)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsPostProcessor.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsPostProcessor.java index ecc5a80805..fae61a186b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsPostProcessor.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ class AvailabilityProbesHealthEndpointGroupsPostProcessor implements HealthEndpo AvailabilityProbesHealthEndpointGroupsPostProcessor(Environment environment) { this.addAdditionalPaths = "true" - .equalsIgnoreCase(environment.getProperty("management.endpoint.health.probes.add-additional-paths")); + .equalsIgnoreCase(environment.getProperty("management.endpoint.health.probes.add-additional-paths")); } @Override diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscoverer.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscoverer.java index a01fe72a92..288847071e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscoverer.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscoverer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,8 +67,11 @@ public class CloudFoundryWebEndpointDiscoverer extends WebEndpointDiscoverer { } private boolean isHealthEndpointExtension(Class extensionBeanType) { - return MergedAnnotations.from(extensionBeanType).get(EndpointWebExtension.class) - .getValue("endpoint", Class.class).map(HealthEndpoint.class::isAssignableFrom).orElse(false); + return MergedAnnotations.from(extensionBeanType) + .get(EndpointWebExtension.class) + .getValue("endpoint", Class.class) + .map(HealthEndpoint.class::isAssignableFrom) + .orElse(false); } private boolean isCloudFoundryHealthEndpointExtension(Class extensionBeanType) { 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..af921111f4 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -80,12 +80,12 @@ class CloudFoundrySecurityInterceptor { try { Token token = getToken(exchange.getRequest()); return this.tokenValidator.validate(token) - .then(this.cloudFoundrySecurityService.getAccessLevel(token.toString(), this.applicationId)) - .filter((accessLevel) -> accessLevel.isAccessAllowed(id)) - .switchIfEmpty( - Mono.error(new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied"))) - .doOnSuccess((accessLevel) -> exchange.getAttributes().put("cloudFoundryAccessLevel", accessLevel)) - .then(); + .then(this.cloudFoundrySecurityService.getAccessLevel(token.toString(), this.applicationId)) + .filter((accessLevel) -> accessLevel.isAccessAllowed(id)) + .switchIfEmpty( + Mono.error(new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied"))) + .doOnSuccess((accessLevel) -> exchange.getAttributes().put("cloudFoundryAccessLevel", accessLevel)) + .then(); } catch (CloudFoundryAuthorizationException ex) { return Mono.error(ex); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java index 0df6400d0a..3447606f93 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -82,26 +82,26 @@ class CloudFoundryWebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointH public Publisher> links(ServerWebExchange exchange) { ServerHttpRequest request = exchange.getRequest(); return CloudFoundryWebFluxEndpointHandlerMapping.this.securityInterceptor.preHandle(exchange, "") - .map((securityResponse) -> { - if (!securityResponse.getStatus().equals(HttpStatus.OK)) { - return new ResponseEntity<>(securityResponse.getStatus()); - } - AccessLevel accessLevel = exchange.getAttribute(AccessLevel.REQUEST_ATTRIBUTE); - Map links = CloudFoundryWebFluxEndpointHandlerMapping.this.linksResolver - .resolveLinks(request.getURI().toString()); - return new ResponseEntity<>( - Collections.singletonMap("_links", getAccessibleLinks(accessLevel, links)), - HttpStatus.OK); - }); + .map((securityResponse) -> { + if (!securityResponse.getStatus().equals(HttpStatus.OK)) { + return new ResponseEntity<>(securityResponse.getStatus()); + } + AccessLevel accessLevel = exchange.getAttribute(AccessLevel.REQUEST_ATTRIBUTE); + Map links = CloudFoundryWebFluxEndpointHandlerMapping.this.linksResolver + .resolveLinks(request.getURI().toString()); + return new ResponseEntity<>( + Collections.singletonMap("_links", getAccessibleLinks(accessLevel, links)), HttpStatus.OK); + }); } private Map getAccessibleLinks(AccessLevel accessLevel, Map links) { if (accessLevel == null) { return new LinkedHashMap<>(); } - return links.entrySet().stream() - .filter((entry) -> entry.getKey().equals("self") || accessLevel.isAccessAllowed(entry.getKey())) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + return links.entrySet() + .stream() + .filter((entry) -> entry.getKey().equals("self") || accessLevel.isAccessAllowed(entry.getKey())) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } @Override @@ -132,7 +132,7 @@ class CloudFoundryWebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointH @Override public Mono> handle(ServerWebExchange exchange, Map body) { return this.securityInterceptor.preHandle(exchange, this.endpointId.toLowerCaseString()) - .flatMap((securityResponse) -> flatMapResponse(exchange, body, securityResponse)); + .flatMap((securityResponse) -> flatMapResponse(exchange, body, securityResponse)); } private Mono> flatMapResponse(ServerWebExchange exchange, Map body, 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..bdb18ea1ea 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -97,9 +97,9 @@ public class ReactiveCloudFoundryActuatorAutoConfiguration { public CloudFoundryInfoEndpointWebExtension cloudFoundryInfoEndpointWebExtension(GitProperties properties, ObjectProvider infoContributors) { List contributors = infoContributors.orderedStream() - .map((infoContributor) -> (infoContributor instanceof GitInfoContributor) - ? new GitInfoContributor(properties, InfoPropertiesInfoContributor.Mode.FULL) : infoContributor) - .collect(Collectors.toList()); + .map((infoContributor) -> (infoContributor instanceof GitInfoContributor) + ? new GitInfoContributor(properties, InfoPropertiesInfoContributor.Mode.FULL) : infoContributor) + .collect(Collectors.toList()); return new CloudFoundryInfoEndpointWebExtension(new InfoEndpoint(contributors)); } @@ -144,8 +144,8 @@ public class ReactiveCloudFoundryActuatorAutoConfiguration { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin(CorsConfiguration.ALL); corsConfiguration.setAllowedMethods(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); - corsConfiguration.setAllowedHeaders( - Arrays.asList(HttpHeaders.AUTHORIZATION, "X-Cf-App-Instance", HttpHeaders.CONTENT_TYPE)); + corsConfiguration + .setAllowedHeaders(Arrays.asList(HttpHeaders.AUTHORIZATION, "X-Cf-App-Instance", HttpHeaders.CONTENT_TYPE)); return corsConfiguration; } @@ -172,7 +172,7 @@ public class ReactiveCloudFoundryActuatorAutoConfiguration { private WebFilterChainProxy postProcess(WebFilterChainProxy existing) { ServerWebExchangeMatcher cloudFoundryRequestMatcher = ServerWebExchangeMatchers - .pathMatchers("/cloudfoundryapplication/**"); + .pathMatchers("/cloudfoundryapplication/**"); WebFilter noOpFilter = (exchange, chain) -> chain.filter(exchange); MatcherSecurityWebFilterChain ignoredRequestFilterChain = new MatcherSecurityWebFilterChain( cloudFoundryRequestMatcher, Collections.singletonList(noOpFilter)); 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 7f9a83b3f1..2c8d6dd9e7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,8 +71,9 @@ class ReactiveCloudFoundrySecurityService { } private Http11SslContextSpec createSslContextSpec() { - return Http11SslContextSpec.forClient().configure( - (builder) -> builder.sslProvider(SslProvider.JDK).trustManager(InsecureTrustManagerFactory.INSTANCE)); + return Http11SslContextSpec.forClient() + .configure((builder) -> builder.sslProvider(SslProvider.JDK) + .trustManager(InsecureTrustManagerFactory.INSTANCE)); } /** @@ -84,8 +85,13 @@ class ReactiveCloudFoundrySecurityService { */ Mono getAccessLevel(String token, String applicationId) throws CloudFoundryAuthorizationException { String uri = getPermissionsUri(applicationId); - return this.webClient.get().uri(uri).header("Authorization", "bearer " + token).retrieve().bodyToMono(Map.class) - .map(this::getAccessLevel).onErrorMap(this::mapError); + return this.webClient.get() + .uri(uri) + .header("Authorization", "bearer " + token) + .retrieve() + .bodyToMono(Map.class) + .map(this::getAccessLevel) + .onErrorMap(this::mapError); } private Throwable mapError(Throwable throwable) { @@ -122,8 +128,10 @@ class ReactiveCloudFoundrySecurityService { private Mono> fetchTokenKeys(String url) { RequestHeadersSpec uri = this.webClient.get().uri(url + "/token_keys"); - return uri.retrieve().bodyToMono(STRING_OBJECT_MAP).map(this::extractTokenKeys).onErrorMap( - ((ex) -> new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, ex.getMessage()))); + return uri.retrieve() + .bodyToMono(STRING_OBJECT_MAP) + .map(this::extractTokenKeys) + .onErrorMap(((ex) -> new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, ex.getMessage()))); } private Map extractTokenKeys(Map response) { @@ -140,10 +148,14 @@ class ReactiveCloudFoundrySecurityService { * @return the UAA url Mono */ Mono getUaaUrl() { - this.uaaUrl = this.webClient.get().uri(this.cloudControllerUrl + "/info").retrieve().bodyToMono(Map.class) - .map((response) -> (String) response.get("token_endpoint")).cache() - .onErrorMap((ex) -> new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, - "Unable to fetch token keys from UAA.")); + this.uaaUrl = this.webClient.get() + .uri(this.cloudControllerUrl + "/info") + .retrieve() + .bodyToMono(Map.class) + .map((response) -> (String) response.get("token_endpoint")) + .cache() + .onErrorMap((ex) -> new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, + "Unable to fetch token keys from UAA.")); return this.uaaUrl; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidator.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidator.java index 6c3df56d0d..3eedca083a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidator.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,10 @@ class ReactiveTokenValidator { } Mono validate(Token token) { - return validateAlgorithm(token).then(validateKeyIdAndSignature(token)).then(validateExpiry(token)) - .then(validateIssuer(token)).then(validateAudience(token)); + return validateAlgorithm(token).then(validateKeyIdAndSignature(token)) + .then(validateExpiry(token)) + .then(validateIssuer(token)) + .then(validateAudience(token)); } private Mono validateAlgorithm(Token token) { @@ -70,9 +72,9 @@ class ReactiveTokenValidator { private Mono validateKeyIdAndSignature(Token token) { return getTokenKey(token).filter((tokenKey) -> hasValidSignature(token, tokenKey)) - .switchIfEmpty(Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_SIGNATURE, - "RSA Signature did not match content"))) - .then(); + .switchIfEmpty(Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_SIGNATURE, + "RSA Signature did not match content"))) + .then(); } private Mono getTokenKey(Token token) { @@ -81,10 +83,12 @@ class ReactiveTokenValidator { if (cached != null) { return Mono.just(cached); } - return this.securityService.fetchTokenKeys().doOnSuccess(this::cacheTokenKeys) - .filter((tokenKeys) -> tokenKeys.containsKey(keyId)).map((tokenKeys) -> tokenKeys.get(keyId)) - .switchIfEmpty(Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_KEY_ID, - "Key Id present in token header does not match"))); + return this.securityService.fetchTokenKeys() + .doOnSuccess(this::cacheTokenKeys) + .filter((tokenKeys) -> tokenKeys.containsKey(keyId)) + .map((tokenKeys) -> tokenKeys.get(keyId)) + .switchIfEmpty(Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_KEY_ID, + "Key Id present in token header does not match"))); } private void cacheTokenKeys(Map tokenKeys) { @@ -122,11 +126,12 @@ class ReactiveTokenValidator { } private Mono validateIssuer(Token token) { - return this.securityService.getUaaUrl().map((uaaUrl) -> String.format("%s/oauth/token", uaaUrl)) - .filter((issuerUri) -> issuerUri.equals(token.getIssuer())) - .switchIfEmpty(Mono.error( - new CloudFoundryAuthorizationException(Reason.INVALID_ISSUER, "Token issuer does not match"))) - .then(); + return this.securityService.getUaaUrl() + .map((uaaUrl) -> String.format("%s/oauth/token", uaaUrl)) + .filter((issuerUri) -> issuerUri.equals(token.getIssuer())) + .switchIfEmpty(Mono + .error(new CloudFoundryAuthorizationException(Reason.INVALID_ISSUER, "Token issuer does not match"))) + .then(); } private Mono validateAudience(Token token) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfiguration.java index a9f3293776..7f2197ffab 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -101,9 +101,9 @@ public class CloudFoundryActuatorAutoConfiguration { public CloudFoundryInfoEndpointWebExtension cloudFoundryInfoEndpointWebExtension(GitProperties properties, ObjectProvider infoContributors) { List contributors = infoContributors.orderedStream() - .map((infoContributor) -> (infoContributor instanceof GitInfoContributor) - ? new GitInfoContributor(properties, InfoPropertiesInfoContributor.Mode.FULL) : infoContributor) - .collect(Collectors.toList()); + .map((infoContributor) -> (infoContributor instanceof GitInfoContributor) + ? new GitInfoContributor(properties, InfoPropertiesInfoContributor.Mode.FULL) : infoContributor) + .collect(Collectors.toList()); return new CloudFoundryInfoEndpointWebExtension(new InfoEndpoint(contributors)); } @@ -148,8 +148,8 @@ public class CloudFoundryActuatorAutoConfiguration { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin(CorsConfiguration.ALL); corsConfiguration.setAllowedMethods(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); - corsConfiguration.setAllowedHeaders( - Arrays.asList(HttpHeaders.AUTHORIZATION, "X-Cf-App-Instance", HttpHeaders.CONTENT_TYPE)); + corsConfiguration + .setAllowedHeaders(Arrays.asList(HttpHeaders.AUTHORIZATION, "X-Cf-App-Instance", HttpHeaders.CONTENT_TYPE)); return corsConfiguration; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryWebEndpointServletHandlerMapping.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryWebEndpointServletHandlerMapping.java index d4dc93e6bc..6596010892 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryWebEndpointServletHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryWebEndpointServletHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -88,7 +88,7 @@ class CloudFoundryWebEndpointServletHandlerMapping extends AbstractWebMvcEndpoin @ResponseBody public Map> links(HttpServletRequest request, HttpServletResponse response) { SecurityResponse securityResponse = CloudFoundryWebEndpointServletHandlerMapping.this.securityInterceptor - .preHandle(request, null); + .preHandle(request, null); if (!securityResponse.getStatus().equals(HttpStatus.OK)) { sendFailureResponse(response, securityResponse); } @@ -98,10 +98,11 @@ class CloudFoundryWebEndpointServletHandlerMapping extends AbstractWebMvcEndpoin return Collections.singletonMap("_links", filteredLinks); } Map links = CloudFoundryWebEndpointServletHandlerMapping.this.linksResolver - .resolveLinks(request.getRequestURL().toString()); - filteredLinks = links.entrySet().stream() - .filter((e) -> e.getKey().equals("self") || accessLevel.isAccessAllowed(e.getKey())) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + .resolveLinks(request.getRequestURL().toString()); + filteredLinks = links.entrySet() + .stream() + .filter((e) -> e.getKey().equals("self") || accessLevel.isAccessAllowed(e.getKey())) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return Collections.singletonMap("_links", filteredLinks); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnAvailableEndpointCondition.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnAvailableEndpointCondition.java index dafecbe57e..4478b0ed94 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnAvailableEndpointCondition.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnAvailableEndpointCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,7 +68,7 @@ class OnAvailableEndpointCondition extends SpringBootCondition { public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { Environment environment = context.getEnvironment(); MergedAnnotation conditionAnnotation = metadata.getAnnotations() - .get(ConditionalOnAvailableEndpoint.class); + .get(ConditionalOnAvailableEndpoint.class); Class target = getTarget(context, metadata, conditionAnnotation); MergedAnnotation endpointAnnotation = getEndpointAnnotation(target); return getMatchOutcome(environment, conditionAnnotation, endpointAnnotation); @@ -134,8 +134,8 @@ class OnAvailableEndpointCondition extends SpringBootCondition { } Boolean userDefinedDefault = isEnabledByDefault(environment); if (userDefinedDefault != null) { - return new ConditionOutcome(userDefinedDefault, message.because( - "no property " + key + " found so using user defined default from " + ENABLED_BY_DEFAULT_KEY)); + return new ConditionOutcome(userDefinedDefault, message + .because("no property " + key + " found so using user defined default from " + ENABLED_BY_DEFAULT_KEY)); } boolean endpointDefault = endpointAnnotation.getBoolean("enableByDefault"); return new ConditionOutcome(endpointDefault, diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilter.java index a1979ac1d3..e51ea7c03f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -174,6 +174,7 @@ public class IncludeExcludeEndpointFilter> implem /** * Default include patterns that can be used. + * * @deprecated since 2.6.0 for removal in 3.0.0 in favor of {@link EndpointExposure}. */ @Deprecated diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactory.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactory.java index eac4b9403c..23c18f400d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactory.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -89,7 +89,7 @@ class DefaultEndpointObjectNameFactory implements EndpointObjectNameFactory { } StringBuilder builder = new StringBuilder(); this.properties.getStaticNames() - .forEach((name, value) -> builder.append(",").append(name).append("=").append(value)); + .forEach((name, value) -> builder.append(",").append(name).append("=").append(value)); return builder.toString(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfiguration.java index bba0b4ae0a..e0c1f42f54 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -95,7 +95,9 @@ class JerseyWebEndpointManagementContextConfiguration { WebEndpointsSupplier webEndpointsSupplier, HealthEndpointGroups healthEndpointGroups) { Collection webEndpoints = webEndpointsSupplier.getEndpoints(); ExposableWebEndpoint health = webEndpoints.stream() - .filter((endpoint) -> endpoint.getEndpointId().equals(HEALTH_ENDPOINT_ID)).findFirst().get(); + .filter((endpoint) -> endpoint.getEndpointId().equals(HEALTH_ENDPOINT_ID)) + .findFirst() + .get(); return new JerseyAdditionalHealthEndpointPathsManagementResourcesRegistrar(health, healthEndpointGroups); } @@ -182,8 +184,10 @@ class JerseyWebEndpointManagementContextConfiguration { JerseyHealthEndpointAdditionalPathResourceFactory resourceFactory = new JerseyHealthEndpointAdditionalPathResourceFactory( WebServerNamespace.MANAGEMENT, this.groups); Collection endpointResources = resourceFactory - .createEndpointResources(mapping, Collections.singletonList(this.endpoint), null, null, false) - .stream().filter(Objects::nonNull).collect(Collectors.toList()); + .createEndpointResources(mapping, Collections.singletonList(this.endpoint), null, null, false) + .stream() + .filter(Objects::nonNull) + .collect(Collectors.toList()); register(endpointResources, config); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/reactive/WebFluxEndpointManagementContextConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/reactive/WebFluxEndpointManagementContextConfiguration.java index 0181f20717..95705e0eb9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/reactive/WebFluxEndpointManagementContextConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/reactive/WebFluxEndpointManagementContextConfiguration.java @@ -99,7 +99,9 @@ public class WebFluxEndpointManagementContextConfiguration { WebEndpointsSupplier webEndpointsSupplier, HealthEndpointGroups groups) { Collection webEndpoints = webEndpointsSupplier.getEndpoints(); ExposableWebEndpoint health = webEndpoints.stream() - .filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)).findFirst().get(); + .filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)) + .findFirst() + .get(); return new AdditionalHealthEndpointPathsWebFluxHandlerMapping(new EndpointMapping(""), health, groups.getAllWithAdditionalPath(WebServerNamespace.MANAGEMENT)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/servlet/WebMvcEndpointManagementContextConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/servlet/WebMvcEndpointManagementContextConfiguration.java index 27155ec8f8..e89ff1da91 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/servlet/WebMvcEndpointManagementContextConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/servlet/WebMvcEndpointManagementContextConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -102,7 +102,9 @@ public class WebMvcEndpointManagementContextConfiguration { WebEndpointsSupplier webEndpointsSupplier, HealthEndpointGroups groups) { Collection webEndpoints = webEndpointsSupplier.getEndpoints(); ExposableWebEndpoint health = webEndpoints.stream() - .filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)).findFirst().get(); + .filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)) + .findFirst() + .get(); return new AdditionalHealthEndpointPathsWebMvcHandlerMapping(health, groups.getAllWithAdditionalPath(WebServerNamespace.MANAGEMENT)); } 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 9f5082d7c3..4e54741e38 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -120,7 +120,7 @@ class HealthEndpointConfiguration { private Object applyPostProcessors(HealthEndpointGroups bean) { for (HealthEndpointGroupsPostProcessor postProcessor : this.postProcessors.orderedStream() - .toArray(HealthEndpointGroupsPostProcessor[]::new)) { + .toArray(HealthEndpointGroupsPostProcessor[]::new)) { bean = postProcessor.postProcessHealthEndpointGroups(bean); } return bean; diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointReactiveWebExtensionConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointReactiveWebExtensionConfiguration.java index 792c9d0f7e..6e80745fa7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointReactiveWebExtensionConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointReactiveWebExtensionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,7 +68,9 @@ class HealthEndpointReactiveWebExtensionConfiguration { WebEndpointsSupplier webEndpointsSupplier, HealthEndpointGroups groups) { Collection webEndpoints = webEndpointsSupplier.getEndpoints(); ExposableWebEndpoint health = webEndpoints.stream() - .filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)).findFirst().get(); + .filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)) + .findFirst() + .get(); return new AdditionalHealthEndpointPathsWebFluxHandlerMapping(new EndpointMapping(""), health, groups.getAllWithAdditionalPath(WebServerNamespace.SERVER)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointWebExtensionConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointWebExtensionConfiguration.java index 857b628295..33e91ed0ff 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointWebExtensionConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointWebExtensionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,8 +79,10 @@ class HealthEndpointWebExtensionConfiguration { private static ExposableWebEndpoint getHealthEndpoint(WebEndpointsSupplier webEndpointsSupplier) { Collection webEndpoints = webEndpointsSupplier.getEndpoints(); - return webEndpoints.stream().filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)) - .findFirst().get(); + return webEndpoints.stream() + .filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)) + .findFirst() + .get(); } @ConditionalOnBean(DispatcherServlet.class) @@ -161,8 +163,10 @@ class HealthEndpointWebExtensionConfiguration { JerseyHealthEndpointAdditionalPathResourceFactory resourceFactory = new JerseyHealthEndpointAdditionalPathResourceFactory( WebServerNamespace.SERVER, this.groups); Collection endpointResources = resourceFactory - .createEndpointResources(mapping, Collections.singletonList(this.endpoint), null, null, false) - .stream().filter(Objects::nonNull).collect(Collectors.toList()); + .createEndpointResources(mapping, Collections.singletonList(this.endpoint), null, null, false) + .stream() + .filter(Objects::nonNull) + .collect(Collectors.toList()); register(endpointResources, config); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/info/OnEnabledInfoContributorCondition.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/info/OnEnabledInfoContributorCondition.java index a36a2f9d65..f13af4a67b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/info/OnEnabledInfoContributorCondition.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/info/OnEnabledInfoContributorCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ class OnEnabledInfoContributorCondition extends OnEndpointElementCondition { InfoContributorFallback fallback = annotationAttributes.getEnum("fallback"); if (fallback == InfoContributorFallback.DISABLE) { return new ConditionOutcome(false, ConditionMessage.forCondition(ConditionalOnEnabledInfoContributor.class) - .because("management.info." + annotationAttributes.getString("value") + ".enabled is not true")); + .because("management.info." + annotationAttributes.getString("value") + ".enabled is not true")); } return super.getDefaultOutcome(context, annotationAttributes); } 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..bea4a4cb91 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -86,9 +86,10 @@ public class DataSourceHealthContributorAutoConfiguration implements Initializin public HealthContributor dbHealthContributor(Map dataSources, DataSourceHealthIndicatorProperties dataSourceHealthIndicatorProperties) { if (dataSourceHealthIndicatorProperties.isIgnoreRoutingDataSources()) { - Map filteredDatasources = dataSources.entrySet().stream() - .filter((e) -> !(e.getValue() instanceof AbstractRoutingDataSource)) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + Map filteredDatasources = dataSources.entrySet() + .stream() + .filter((e) -> !(e.getValue() instanceof AbstractRoutingDataSource)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return createContributor(filteredDatasources); } return createContributor(dataSources); @@ -128,9 +129,11 @@ public class DataSourceHealthContributorAutoConfiguration implements Initializin RoutingDataSourceHealthContributor(AbstractRoutingDataSource routingDataSource, Function contributorFunction) { - Map routedDataSources = routingDataSource.getResolvedDataSources().entrySet().stream() - .collect(Collectors.toMap((e) -> Objects.toString(e.getKey(), UNNAMED_DATASOURCE_KEY), - Map.Entry::getValue)); + Map routedDataSources = routingDataSource.getResolvedDataSources() + .entrySet() + .stream() + .collect(Collectors.toMap((e) -> Objects.toString(e.getKey(), UNNAMED_DATASOURCE_KEY), + Map.Entry::getValue)); this.delegate = CompositeHealthContributor.fromMap(routedDataSources, contributorFunction); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfiguration.java index af4296bb9e..a803aba296 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,8 +59,8 @@ public class LoggersEndpointAutoConfiguration { ConditionMessage.Builder message = ConditionMessage.forCondition("Logging System"); String loggingSystem = System.getProperty(LoggingSystem.SYSTEM_PROPERTY); if (LoggingSystem.NONE.equals(loggingSystem)) { - return ConditionOutcome.noMatch( - message.because("system property " + LoggingSystem.SYSTEM_PROPERTY + " is set to none")); + return ConditionOutcome + .noMatch(message.because("system property " + LoggingSystem.SYSTEM_PROPERTY + " is set to none")); } return ConditionOutcome.match(message.because("enabled")); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsAutoConfiguration.java index d2039e0466..9da1b3aef5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,14 +60,14 @@ public class Log4J2MetricsAutoConfiguration { try { if (Class.forName("org.apache.logging.log4j.core.LoggerContext").isInstance(loggerContext)) { return ConditionOutcome - .match("LoggerContext was an instance of org.apache.logging.log4j.core.LoggerContext"); + .match("LoggerContext was an instance of org.apache.logging.log4j.core.LoggerContext"); } } catch (Throwable ex) { // Continue with no match } return ConditionOutcome - .noMatch("Logger context was not an instance of org.apache.logging.log4j.core.LoggerContext"); + .noMatch("Logger context was not an instance of org.apache.logging.log4j.core.LoggerContext"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurer.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurer.java index fd062849a0..80bd483f08 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurer.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -75,7 +75,8 @@ class MeterRegistryConfigurer { @SuppressWarnings("unchecked") private void customize(MeterRegistry registry) { LambdaSafe.callbacks(MeterRegistryCustomizer.class, asOrderedList(this.customizers), registry) - .withLogger(MeterRegistryConfigurer.class).invoke((customizer) -> customizer.customize(registry)); + .withLogger(MeterRegistryConfigurer.class) + .invoke((customizer) -> customizer.customize(registry)); } private void addFilters(MeterRegistry registry) { 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..4cd0ed8634 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,7 +69,7 @@ class MeterRegistryPostProcessor implements BeanPostProcessor { private MeterRegistryConfigurer getConfigurer() { if (this.configurer == null) { boolean hasCompositeMeterRegistry = this.applicationContext - .getBeanNamesForType(CompositeMeterRegistry.class, false, false).length != 0; + .getBeanNamesForType(CompositeMeterRegistry.class, false, false).length != 0; this.configurer = new MeterRegistryConfigurer(this.meterRegistryCustomizers, this.meterFilters, this.meterBinders, this.metricsProperties.getObject().isUseGlobalRegistry(), hasCompositeMeterRegistry); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilter.java index 88e7d8dece..7b74d5d1fa 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,8 +61,10 @@ public class PropertiesMeterFilter implements MeterFilter { return new MeterFilter() { }; } - Tags commonTags = Tags.of(tags.entrySet().stream().map((entry) -> Tag.of(entry.getKey(), entry.getValue())) - .collect(Collectors.toList())); + Tags commonTags = Tags.of(tags.entrySet() + .stream() + .map((entry) -> Tag.of(entry.getKey(), entry.getValue())) + .collect(Collectors.toList())); return MeterFilter.commonTags(commonTags); } @@ -81,24 +83,29 @@ public class PropertiesMeterFilter implements MeterFilter { public DistributionStatisticConfig configure(Meter.Id id, DistributionStatisticConfig config) { Distribution distribution = this.properties.getDistribution(); return DistributionStatisticConfig.builder() - .percentilesHistogram(lookupWithFallbackToAll(distribution.getPercentilesHistogram(), id, null)) - .percentiles(lookupWithFallbackToAll(distribution.getPercentiles(), id, null)) - .serviceLevelObjectives( - convertServiceLevelObjectives(id.getType(), lookup(distribution.getSlo(), id, null))) - .minimumExpectedValue( - convertMeterValue(id.getType(), lookup(distribution.getMinimumExpectedValue(), id, null))) - .maximumExpectedValue( - convertMeterValue(id.getType(), lookup(distribution.getMaximumExpectedValue(), id, null))) - .expiry(lookupWithFallbackToAll(distribution.getExpiry(), id, null)) - .bufferLength(lookupWithFallbackToAll(distribution.getBufferLength(), id, null)).build().merge(config); + .percentilesHistogram(lookupWithFallbackToAll(distribution.getPercentilesHistogram(), id, null)) + .percentiles(lookupWithFallbackToAll(distribution.getPercentiles(), id, null)) + .serviceLevelObjectives( + convertServiceLevelObjectives(id.getType(), lookup(distribution.getSlo(), id, null))) + .minimumExpectedValue( + convertMeterValue(id.getType(), lookup(distribution.getMinimumExpectedValue(), id, null))) + .maximumExpectedValue( + convertMeterValue(id.getType(), lookup(distribution.getMaximumExpectedValue(), id, null))) + .expiry(lookupWithFallbackToAll(distribution.getExpiry(), id, null)) + .bufferLength(lookupWithFallbackToAll(distribution.getBufferLength(), id, null)) + .build() + .merge(config); } private double[] convertServiceLevelObjectives(Meter.Type meterType, ServiceLevelObjectiveBoundary[] slo) { if (slo == null) { return null; } - double[] converted = Arrays.stream(slo).map((candidate) -> candidate.getValue(meterType)) - .filter(Objects::nonNull).mapToDouble(Double::doubleValue).toArray(); + double[] converted = Arrays.stream(slo) + .map((candidate) -> candidate.getValue(meterType)) + .filter(Objects::nonNull) + .mapToDouble(Double::doubleValue) + .toArray(); return (converted.length != 0) ? converted : null; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsRegistrarConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsRegistrarConfiguration.java index 9c074c77da..be54d5baf7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsRegistrarConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsRegistrarConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,7 +68,7 @@ class CacheMetricsRegistrarConfiguration { private void bindCacheManagerToRegistry(String beanName, CacheManager cacheManager) { cacheManager.getCacheNames() - .forEach((cacheName) -> bindCacheToRegistry(beanName, cacheManager.getCache(cacheName))); + .forEach((cacheName) -> bindCacheToRegistry(beanName, cacheManager.getCache(cacheName))); } private void bindCacheToRegistry(String beanName, Cache cache) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfiguration.java index 52359430ec..45188b5cc5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,9 +64,11 @@ public class AppOpticsMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean public AppOpticsMeterRegistry appOpticsMeterRegistry(AppOpticsConfig config, Clock clock) { - return AppOpticsMeterRegistry.builder(config).clock(clock).httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) - .build(); + return AppOpticsMeterRegistry.builder(config) + .clock(clock) + .httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) + .build(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfiguration.java index 9d48d4cd57..463eba9422 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,9 +64,11 @@ public class DatadogMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean public DatadogMeterRegistry datadogMeterRegistry(DatadogConfig datadogConfig, Clock clock) { - return DatadogMeterRegistry.builder(datadogConfig).clock(clock).httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) - .build(); + return DatadogMeterRegistry.builder(datadogConfig) + .clock(clock) + .httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) + .build(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfiguration.java index 47a144ddde..60c57d2acc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,9 +64,11 @@ public class DynatraceMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean public DynatraceMeterRegistry dynatraceMeterRegistry(DynatraceConfig dynatraceConfig, Clock clock) { - return DynatraceMeterRegistry.builder(dynatraceConfig).clock(clock).httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) - .build(); + return DynatraceMeterRegistry.builder(dynatraceConfig) + .clock(clock) + .httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) + .build(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfiguration.java index 3363b4fa40..8040723791 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,9 +73,11 @@ public class ElasticMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean public ElasticMeterRegistry elasticMeterRegistry(ElasticConfig elasticConfig, Clock clock) { - return ElasticMeterRegistry.builder(elasticConfig).clock(clock).httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) - .build(); + return ElasticMeterRegistry.builder(elasticConfig) + .clock(clock) + .httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) + .build(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfiguration.java index a208ee7378..afa4f9ebde 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,9 +64,11 @@ public class HumioMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean public HumioMeterRegistry humioMeterRegistry(HumioConfig humioConfig, Clock clock) { - return HumioMeterRegistry.builder(humioConfig).clock(clock).httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) - .build(); + return HumioMeterRegistry.builder(humioConfig) + .clock(clock) + .httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) + .build(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfiguration.java index daec199473..3615f0d143 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,9 +64,11 @@ public class InfluxMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean public InfluxMeterRegistry influxMeterRegistry(InfluxConfig influxConfig, Clock clock) { - return InfluxMeterRegistry.builder(influxConfig).clock(clock).httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) - .build(); + return InfluxMeterRegistry.builder(influxConfig) + .clock(clock) + .httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) + .build(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfiguration.java index 9378a6dc50..8e079fb9a4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,9 +64,11 @@ public class KairosMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean public KairosMeterRegistry kairosMeterRegistry(KairosConfig kairosConfig, Clock clock) { - return KairosMeterRegistry.builder(kairosConfig).clock(clock).httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) - .build(); + return KairosMeterRegistry.builder(kairosConfig) + .clock(clock) + .httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) + .build(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfiguration.java index 694eedfacf..e65f922883 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,8 +81,10 @@ public class NewRelicMetricsExportAutoConfiguration { @ConditionalOnMissingBean public NewRelicMeterRegistry newRelicMeterRegistry(NewRelicConfig newRelicConfig, Clock clock, NewRelicClientProvider newRelicClientProvider) { - return NewRelicMeterRegistry.builder(newRelicConfig).clock(clock).clientProvider(newRelicClientProvider) - .build(); + return NewRelicMeterRegistry.builder(newRelicConfig) + .clock(clock) + .clientProvider(newRelicClientProvider) + .build(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfiguration.java index 8c8d365cc3..62f9c778aa 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -153,7 +153,7 @@ public class PrometheusMetricsExportAutoConfiguration { } catch (MalformedURLException ex) { logger.warn(LogMessage - .format("Invalid PushGateway base url '%s': update your configuration to a valid URL", url)); + .format("Invalid PushGateway base url '%s': update your configuration to a valid URL", url)); return new PushGateway(url); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfiguration.java index 8816f91ce5..cd29accec3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -88,7 +88,7 @@ public class DataSourcePoolMetricsAutoConfiguration { @Override public void bindTo(MeterRegistry registry) { List metadataProvidersList = this.metadataProviders.stream() - .collect(Collectors.toList()); + .collect(Collectors.toList()); this.dataSources.forEach((name, dataSource) -> bindDataSourceToRegistry(name, dataSource, metadataProvidersList, registry)); } @@ -97,7 +97,7 @@ public class DataSourcePoolMetricsAutoConfiguration { Collection metadataProviders, MeterRegistry registry) { String dataSourceName = getDataSourceName(beanName); new DataSourcePoolMetrics(dataSource, metadataProviders, dataSourceName, Collections.emptyList()) - .bindTo(registry); + .bindTo(registry); } /** diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/mongo/MongoMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/mongo/MongoMetricsAutoConfiguration.java index 1e448b46f0..e900d07674 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/mongo/MongoMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/mongo/MongoMetricsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -98,8 +98,8 @@ public class MongoMetricsAutoConfiguration { MongoClientSettingsBuilderCustomizer mongoMetricsConnectionPoolListenerClientSettingsBuilderCustomizer( MongoMetricsConnectionPoolListener mongoMetricsConnectionPoolListener) { return (clientSettingsBuilder) -> clientSettingsBuilder - .applyToConnectionPoolSettings((connectionPoolSettingsBuilder) -> connectionPoolSettingsBuilder - .addConnectionPoolListener(mongoMetricsConnectionPoolListener)); + .applyToConnectionPoolSettings((connectionPoolSettingsBuilder) -> connectionPoolSettingsBuilder + .addConnectionPoolListener(mongoMetricsConnectionPoolListener)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfiguration.java index 5398f30b0c..ff0c6292e1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,7 +77,8 @@ public class HibernateMetricsAutoConfiguration implements SmartInitializingSingl String entityManagerFactoryName = getEntityManagerFactoryName(beanName); try { new HibernateMetrics(entityManagerFactory.unwrap(SessionFactory.class), entityManagerFactoryName, - Collections.emptyList()).bindTo(registry); + Collections.emptyList()) + .bindTo(registry); } catch (PersistenceException ex) { // Continue diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/HttpClientMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/HttpClientMetricsAutoConfiguration.java index 230e100438..5ae0aeff5f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/HttpClientMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/HttpClientMetricsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ public class HttpClientMetricsAutoConfiguration { public MeterFilter metricsHttpClientUriTagFilter(MetricsProperties properties) { String metricName = properties.getWeb().getClient().getRequest().getMetricName(); MeterFilter denyFilter = new OnlyOnceLoggingDenyMeterFilter(() -> String - .format("Reached the maximum number of URI tags for '%s'. Are you using 'uriVariables'?", metricName)); + .format("Reached the maximum number of URI tags for '%s'. Are you using 'uriVariables'?", metricName)); return MeterFilter.maximumAllowableTags(metricName, "uri", properties.getWeb().getClient().getMaxUriTags(), denyFilter); } 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 50dc4a97d8..8a6d7d04d6 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 @@ -232,8 +232,9 @@ public final class EndpointRequest { } private List getDelegateMatchers(Set paths) { - return paths.stream().map((path) -> new PathPatternParserServerWebExchangeMatcher(path + "/**")) - .collect(Collectors.toList()); + return paths.stream() + .map((path) -> new PathPatternParserServerWebExchangeMatcher(path + "/**")) + .collect(Collectors.toList()); } @Override @@ -243,8 +244,10 @@ public final class EndpointRequest { } private String toString(List endpoints, String emptyValue) { - return (!endpoints.isEmpty()) ? endpoints.stream().map(this::getEndpointId).map(Object::toString) - .collect(Collectors.joining(", ", "[", "]")) : emptyValue; + return (!endpoints.isEmpty()) ? endpoints.stream() + .map(this::getEndpointId) + .map(Object::toString) + .collect(Collectors.joining(", ", "[", "]")) : emptyValue; } private EndpointId getEndpointId(Object 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 5cf798ea84..b914a32115 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 @@ -250,8 +250,9 @@ public final class EndpointRequest { private List getDelegateMatchers(RequestMatcherFactory requestMatcherFactory, RequestMatcherProvider matcherProvider, Set paths) { - return paths.stream().map((path) -> requestMatcherFactory.antPath(matcherProvider, path, "/**")) - .collect(Collectors.toList()); + return paths.stream() + .map((path) -> requestMatcherFactory.antPath(matcherProvider, path, "/**")) + .collect(Collectors.toList()); } @Override @@ -261,8 +262,10 @@ public final class EndpointRequest { } private String toString(List endpoints, String emptyValue) { - return (!endpoints.isEmpty()) ? endpoints.stream().map(this::getEndpointId).map(Object::toString) - .collect(Collectors.joining(", ", "[", "]")) : emptyValue; + return (!endpoints.isEmpty()) ? endpoints.stream() + .map(this::getEndpointId) + .map(Object::toString) + .collect(Collectors.joining(", ", "[", "]")) : emptyValue; } private EndpointId getEndpointId(Object source) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/startup/StartupEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/startup/StartupEndpointAutoConfiguration.java index 5f91740a9e..4871ee6d9f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/startup/StartupEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/startup/StartupEndpointAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,8 +62,8 @@ public class StartupEndpointAutoConfiguration { ConditionMessage.Builder message = ConditionMessage.forCondition("ApplicationStartup"); ApplicationStartup applicationStartup = context.getBeanFactory().getApplicationStartup(); if (applicationStartup instanceof BufferingApplicationStartup) { - return ConditionOutcome.match( - message.because("configured applicationStartup is of type BufferingApplicationStartup.")); + return ConditionOutcome + .match(message.because("configured applicationStartup is of type BufferingApplicationStartup.")); } return ConditionOutcome.noMatch(message.because("configured applicationStartup is of type " + applicationStartup.getClass() + ", expected BufferingApplicationStartup.")); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactory.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactory.java index 117d2d549a..66620d9b3b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactory.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ class ReactiveManagementContextFactory implements ManagementContextFactory { Class... configClasses) { Environment parentEnvironment = parent.getEnvironment(); ConfigurableEnvironment childEnvironment = ApplicationContextFactory.DEFAULT - .createEnvironment(WebApplicationType.REACTIVE); + .createEnvironment(WebApplicationType.REACTIVE); if (parentEnvironment instanceof ConfigurableEnvironment) { childEnvironment.setConversionService(((ConfigurableEnvironment) parentEnvironment).getConversionService()); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/LocalManagementPort.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/LocalManagementPort.java index dfceb07a1d..822d3db82f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/LocalManagementPort.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/LocalManagementPort.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,6 +28,7 @@ import org.springframework.beans.factory.annotation.Value; * Annotation at the field or method/constructor parameter level that injects the HTTP * management port that got allocated at runtime. Provides a convenient alternative for * @Value("${local.management.port}"). + * * @deprecated since 2.7.0 for removal in 3.0.0 in favor of * {@code org.springframework.boot.test.web.server.LocalManagementPort} * @author Stephane Nicoll diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfiguration.java index 7e4592eac3..feb3629eea 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -137,9 +137,8 @@ public class ManagementContextAutoConfiguration { public void onApplicationEvent(WebServerInitializedEvent event) { if (event.getApplicationContext().equals(this.applicationContext)) { ConfigurableWebServerApplicationContext managementContext = this.managementContextFactory - .createManagementContext(this.applicationContext, - EnableChildManagementContextConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + .createManagementContext(this.applicationContext, EnableChildManagementContextConfiguration.class, + PropertyPlaceholderAutoConfiguration.class); if (isLazyInitialization()) { managementContext.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor()); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelector.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelector.java index cc10be2f03..219ee654d4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelector.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelector.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,7 +55,8 @@ class ManagementContextConfigurationImportSelector implements DeferredImportSele @Override public String[] selectImports(AnnotationMetadata metadata) { ManagementContextType contextType = (ManagementContextType) metadata - .getAnnotationAttributes(EnableManagementContext.class.getName()).get("value"); + .getAnnotationAttributes(EnableManagementContext.class.getName()) + .get("value"); // Find all management context configuration classes, filtering duplicates List configurations = getConfigurations(); OrderComparator.sort(configurations); @@ -121,7 +122,7 @@ class ManagementContextConfigurationImportSelector implements DeferredImportSele private ManagementContextType readContextType(AnnotationMetadata annotationMetadata) { Map annotationAttributes = annotationMetadata - .getAnnotationAttributes(ManagementContextConfiguration.class.getName()); + .getAnnotationAttributes(ManagementContextConfiguration.class.getName()); return (annotationAttributes != null) ? (ManagementContextType) annotationAttributes.get("value") : ManagementContextType.ANY; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementWebServerFactoryCustomizer.java index 4b0e3be415..98c1eec900 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementWebServerFactoryCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,7 +64,7 @@ public abstract class ManagementWebServerFactoryCustomizer> customizers = Arrays.stream(this.customizerClasses).map(this::getCustomizer) - .filter(Objects::nonNull).collect(Collectors.toList()); + List> customizers = Arrays.stream(this.customizerClasses) + .map(this::getCustomizer) + .filter(Objects::nonNull) + .collect(Collectors.toList()); invokeCustomizers(factory, customizers); } @@ -95,7 +97,7 @@ public abstract class ManagementWebServerFactoryCustomizer> customizers) { LambdaSafe.callbacks(WebServerFactoryCustomizer.class, customizers, factory) - .invoke((customizer) -> customizer.customize(factory)); + .invoke((customizer) -> customizer.customize(factory)); } protected void customize(T factory, ManagementServerProperties managementServerProperties, diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/OnManagementPortCondition.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/OnManagementPortCondition.java index 077a6b9ee6..4cdee48ddc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/OnManagementPortCondition.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/OnManagementPortCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,10 +49,10 @@ class OnManagementPortCondition extends SpringBootCondition { ManagementPortType actualType = ManagementPortType.get(context.getEnvironment()); if (actualType == requiredType) { return ConditionOutcome - .match(message.because("actual port type (" + actualType + ") matched required type")); + .match(message.because("actual port type (" + actualType + ") matched required type")); } return ConditionOutcome.noMatch(message - .because("actual port type (" + actualType + ") did not match required type (" + requiredType + ")")); + .because("actual port type (" + actualType + ") did not match required type (" + requiredType + ")")); } private boolean isWebApplicationContext(ConditionContext context) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementChildContextConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementChildContextConfiguration.java index d2a6002aa3..1bb08cbac7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementChildContextConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementChildContextConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -112,8 +112,8 @@ class ServletManagementChildContextConfiguration { @Bean @ConditionalOnBean(name = "securityFilterChainRegistration", search = SearchStrategy.ANCESTORS) DelegatingFilterProxyRegistrationBean securityFilterChainRegistration(HierarchicalBeanFactory beanFactory) { - return beanFactory.getParentBeanFactory().getBean("securityFilterChainRegistration", - DelegatingFilterProxyRegistrationBean.class); + return beanFactory.getParentBeanFactory() + .getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementContextFactory.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementContextFactory.java index 0f676b6669..1e438ca6c0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementContextFactory.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementContextFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ class ServletManagementContextFactory implements ManagementContextFactory { Class... configClasses) { Environment parentEnvironment = parent.getEnvironment(); ConfigurableEnvironment childEnvironment = ApplicationContextFactory.DEFAULT - .createEnvironment(WebApplicationType.SERVLET); + .createEnvironment(WebApplicationType.SERVLET); if (parentEnvironment instanceof ConfigurableEnvironment) { childEnvironment.setConversionService(((ConfigurableEnvironment) parentEnvironment).getConversionService()); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthContributorAutoConfigurationTests.java index e642c1015f..fc77d4c095 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,8 @@ import static org.assertj.core.api.Assertions.assertThat; class RabbitHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class, - RabbitHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class, + RabbitHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { @@ -45,7 +45,7 @@ class RabbitHealthContributorAutoConfigurationTests { @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.rabbit.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(RabbitHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(RabbitHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfigurationTests.java index 471e2dd0bb..7b010f4ba5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ import static org.assertj.core.api.Assertions.assertThat; class AuditAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AuditAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(AuditAutoConfiguration.class)); @Test void autoConfigurationIsDisabledByDefault() { @@ -66,34 +66,34 @@ class AuditAutoConfigurationTests { @Test void ownAuthenticationAuditListener() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) - .withUserConfiguration(CustomAuthenticationAuditListenerConfiguration.class) - .run((context) -> assertThat(context.getBean(AbstractAuthenticationAuditListener.class)) - .isInstanceOf(TestAuthenticationAuditListener.class)); + .withUserConfiguration(CustomAuthenticationAuditListenerConfiguration.class) + .run((context) -> assertThat(context.getBean(AbstractAuthenticationAuditListener.class)) + .isInstanceOf(TestAuthenticationAuditListener.class)); } @Test void ownAuthorizationAuditListener() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) - .withUserConfiguration(CustomAuthorizationAuditListenerConfiguration.class) - .run((context) -> assertThat(context.getBean(AbstractAuthorizationAuditListener.class)) - .isInstanceOf(TestAuthorizationAuditListener.class)); + .withUserConfiguration(CustomAuthorizationAuditListenerConfiguration.class) + .run((context) -> assertThat(context.getBean(AbstractAuthorizationAuditListener.class)) + .isInstanceOf(TestAuthorizationAuditListener.class)); } @Test void ownAuditListener() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) - .withUserConfiguration(CustomAuditListenerConfiguration.class) - .run((context) -> assertThat(context.getBean(AbstractAuditListener.class)) - .isInstanceOf(TestAuditListener.class)); + .withUserConfiguration(CustomAuditListenerConfiguration.class) + .run((context) -> assertThat(context.getBean(AbstractAuditListener.class)) + .isInstanceOf(TestAuditListener.class)); } @Test void backsOffWhenDisabled() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) - .withPropertyValues("management.auditevents.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(AuditListener.class) - .doesNotHaveBean(AuthenticationAuditListener.class) - .doesNotHaveBean(AuthorizationAuditListener.class)); + .withPropertyValues("management.auditevents.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(AuditListener.class) + .doesNotHaveBean(AuthenticationAuditListener.class) + .doesNotHaveBean(AuthorizationAuditListener.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfigurationTests.java index cefd0f6e10..8e1e14712a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,14 +42,14 @@ class AuditEventsEndpointAutoConfigurationTests { @Test void runWhenRepositoryBeanAvailableShouldHaveEndpointBean() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=auditevents") - .run((context) -> assertThat(context).hasSingleBean(AuditEventsEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=auditevents") + .run((context) -> assertThat(context).hasSingleBean(AuditEventsEndpoint.class)); } @Test void endpointBacksOffWhenRepositoryNotAvailable() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=auditevents") - .run((context) -> assertThat(context).doesNotHaveBean(AuditEventsEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(AuditEventsEndpoint.class)); } @Test @@ -60,9 +60,9 @@ class AuditEventsEndpointAutoConfigurationTests { @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpoint() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) - .withPropertyValues("management.endpoint.auditevents.enabled:false") - .withPropertyValues("management.endpoints.web.exposure.include=*") - .run((context) -> assertThat(context).doesNotHaveBean(AuditEventsEndpoint.class)); + .withPropertyValues("management.endpoint.auditevents.enabled:false") + .withPropertyValues("management.endpoints.web.exposure.include=*") + .run((context) -> assertThat(context).doesNotHaveBean(AuditEventsEndpoint.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityHealthContributorAutoConfigurationTests.java index dce124c765..8b65242246 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,30 +35,30 @@ import static org.assertj.core.api.Assertions.assertThat; class AvailabilityHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ApplicationAvailabilityAutoConfiguration.class, - AvailabilityHealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ApplicationAvailabilityAutoConfiguration.class, + AvailabilityHealthContributorAutoConfiguration.class)); @Test void probesWhenNotKubernetesAddsNoBeans() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) - .doesNotHaveBean(LivenessStateHealthIndicator.class) - .doesNotHaveBean(ReadinessStateHealthIndicator.class)); + .doesNotHaveBean(LivenessStateHealthIndicator.class) + .doesNotHaveBean(ReadinessStateHealthIndicator.class)); } @Test void livenessIndicatorWhenPropertyEnabledAddsBeans() { this.contextRunner.withPropertyValues("management.health.livenessState.enabled=true") - .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) - .hasSingleBean(LivenessStateHealthIndicator.class) - .doesNotHaveBean(ReadinessStateHealthIndicator.class)); + .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) + .hasSingleBean(LivenessStateHealthIndicator.class) + .doesNotHaveBean(ReadinessStateHealthIndicator.class)); } @Test void readinessIndicatorWhenPropertyEnabledAddsBeans() { this.contextRunner.withPropertyValues("management.health.readinessState.enabled=true") - .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) - .hasSingleBean(ReadinessStateHealthIndicator.class) - .doesNotHaveBean(LivenessStateHealthIndicator.class)); + .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) + .hasSingleBean(ReadinessStateHealthIndicator.class) + .doesNotHaveBean(LivenessStateHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesAutoConfigurationTests.java index 7e422cc579..32400ecc3f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,44 +35,48 @@ import static org.assertj.core.api.Assertions.assertThat; class AvailabilityProbesAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ApplicationAvailabilityAutoConfiguration.class, - AvailabilityHealthContributorAutoConfiguration.class, AvailabilityProbesAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ApplicationAvailabilityAutoConfiguration.class, + AvailabilityHealthContributorAutoConfiguration.class, AvailabilityProbesAutoConfiguration.class)); @Test void probesWhenNotKubernetesAddsNoBeans() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) - .doesNotHaveBean(LivenessStateHealthIndicator.class) - .doesNotHaveBean(ReadinessStateHealthIndicator.class) - .doesNotHaveBean(AvailabilityProbesHealthEndpointGroupsPostProcessor.class)); + .doesNotHaveBean(LivenessStateHealthIndicator.class) + .doesNotHaveBean(ReadinessStateHealthIndicator.class) + .doesNotHaveBean(AvailabilityProbesHealthEndpointGroupsPostProcessor.class)); } @Test void probesWhenKubernetesAddsBeans() { this.contextRunner.withPropertyValues("spring.main.cloud-platform=kubernetes") - .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) - .hasSingleBean(LivenessStateHealthIndicator.class).hasBean("livenessStateHealthIndicator") - .hasSingleBean(ReadinessStateHealthIndicator.class).hasBean("readinessStateHealthIndicator") - .hasSingleBean(AvailabilityProbesHealthEndpointGroupsPostProcessor.class)); + .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) + .hasSingleBean(LivenessStateHealthIndicator.class) + .hasBean("livenessStateHealthIndicator") + .hasSingleBean(ReadinessStateHealthIndicator.class) + .hasBean("readinessStateHealthIndicator") + .hasSingleBean(AvailabilityProbesHealthEndpointGroupsPostProcessor.class)); } @Test void probesWhenPropertyEnabledAddsBeans() { this.contextRunner.withPropertyValues("management.endpoint.health.probes.enabled=true") - .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) - .hasSingleBean(LivenessStateHealthIndicator.class).hasBean("livenessStateHealthIndicator") - .hasSingleBean(ReadinessStateHealthIndicator.class).hasBean("readinessStateHealthIndicator") - .hasSingleBean(AvailabilityProbesHealthEndpointGroupsPostProcessor.class)); + .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) + .hasSingleBean(LivenessStateHealthIndicator.class) + .hasBean("livenessStateHealthIndicator") + .hasSingleBean(ReadinessStateHealthIndicator.class) + .hasBean("readinessStateHealthIndicator") + .hasSingleBean(AvailabilityProbesHealthEndpointGroupsPostProcessor.class)); } @Test void probesWhenKubernetesAndPropertyDisabledAddsNotBeans() { this.contextRunner - .withPropertyValues("spring.main.cloud-platform=kubernetes", - "management.endpoint.health.probes.enabled=false") - .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) - .doesNotHaveBean(LivenessStateHealthIndicator.class) - .doesNotHaveBean(ReadinessStateHealthIndicator.class) - .doesNotHaveBean(AvailabilityProbesHealthEndpointGroupsPostProcessor.class)); + .withPropertyValues("spring.main.cloud-platform=kubernetes", + "management.endpoint.health.probes.enabled=false") + .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) + .doesNotHaveBean(LivenessStateHealthIndicator.class) + .doesNotHaveBean(ReadinessStateHealthIndicator.class) + .doesNotHaveBean(AvailabilityProbesHealthEndpointGroupsPostProcessor.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsPostProcessorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsPostProcessorTests.java index 8c53e4a0f0..5fa64163e4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsPostProcessorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,7 @@ class AvailabilityProbesHealthEndpointGroupsPostProcessorTests { names.add("liveness"); given(groups.getNames()).willReturn(names); assertThat(this.postProcessor.postProcessHealthEndpointGroups(groups)) - .isInstanceOf(AvailabilityProbesHealthEndpointGroups.class); + .isInstanceOf(AvailabilityProbesHealthEndpointGroups.class); } @Test @@ -60,7 +60,7 @@ class AvailabilityProbesHealthEndpointGroupsPostProcessorTests { names.add("readiness"); given(groups.getNames()).willReturn(names); assertThat(this.postProcessor.postProcessHealthEndpointGroups(groups)) - .isInstanceOf(AvailabilityProbesHealthEndpointGroups.class); + .isInstanceOf(AvailabilityProbesHealthEndpointGroups.class); } @Test @@ -72,7 +72,7 @@ class AvailabilityProbesHealthEndpointGroupsPostProcessorTests { names.add("boot"); given(groups.getNames()).willReturn(names); assertThat(this.postProcessor.postProcessHealthEndpointGroups(groups)) - .isInstanceOf(AvailabilityProbesHealthEndpointGroups.class); + .isInstanceOf(AvailabilityProbesHealthEndpointGroups.class); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsTests.java index 78e711125d..ae5dfc5384 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ class AvailabilityProbesHealthEndpointGroupsTests { @Test void createWhenGroupsIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new AvailabilityProbesHealthEndpointGroups(null, false)) - .withMessage("Groups must not be null"); + .withMessage("Groups must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfigurationTests.java index 3f1186b275..e1918e4505 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,12 +32,12 @@ import static org.assertj.core.api.Assertions.assertThat; class BeansEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(BeansEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(BeansEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=beans") - .run((context) -> assertThat(context).hasSingleBean(BeansEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(BeansEndpoint.class)); } @Test @@ -48,8 +48,8 @@ class BeansEndpointAutoConfigurationTests { @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.beans.enabled:false") - .withPropertyValues("management.endpoints.web.exposure.include=*") - .run((context) -> assertThat(context).doesNotHaveBean(BeansEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=*") + .run((context) -> assertThat(context).doesNotHaveBean(BeansEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfigurationTests.java index 4c02aae4e2..77766f4c3b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,42 +36,42 @@ import static org.mockito.Mockito.mock; class CachesEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CachesEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(CachesEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withBean(CacheManager.class, () -> mock(CacheManager.class)) - .withPropertyValues("management.endpoints.web.exposure.include=caches") - .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=caches") + .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class)); } @Test void runWithoutCacheManagerShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=caches") - .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class)); } @Test void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withBean(CacheManager.class, () -> mock(CacheManager.class)) - .run((context) -> assertThat(context).doesNotHaveBean(CachesEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CachesEndpoint.class)); } @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.caches.enabled:false") - .withPropertyValues("management.endpoints.web.exposure.include=*") - .withBean(CacheManager.class, () -> mock(CacheManager.class)) - .run((context) -> assertThat(context).doesNotHaveBean(CachesEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=*") + .withBean(CacheManager.class, () -> mock(CacheManager.class)) + .run((context) -> assertThat(context).doesNotHaveBean(CachesEndpoint.class)); } @Test void runWhenOnlyExposedOverJmxShouldHaveEndpointBeanWithoutWebExtension() { this.contextRunner.withBean(CacheManager.class, () -> mock(CacheManager.class)) - .withPropertyValues("management.endpoints.web.exposure.include=info", "spring.jmx.enabled=true", - "management.endpoints.jmx.exposure.include=caches") - .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class) - .doesNotHaveBean(CachesEndpointWebExtension.class)); + .withPropertyValues("management.endpoints.web.exposure.include=info", "spring.jmx.enabled=true", + "management.endpoints.jmx.exposure.include=caches") + .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class) + .doesNotHaveBean(CachesEndpointWebExtension.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthContributorAutoConfigurationTests.java index fb61aead66..a76c786630 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,35 +38,35 @@ import static org.mockito.Mockito.mock; class CassandraHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CassandraHealthContributorAutoConfiguration.class, - HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(CassandraHealthContributorAutoConfiguration.class, + HealthContributorAutoConfiguration.class)); @Test void runWithoutCqlSessionOrCassandraOperationsShouldNotCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean("cassandraHealthContributor") - .doesNotHaveBean(CassandraDriverHealthIndicator.class)); + .doesNotHaveBean(CassandraDriverHealthIndicator.class)); } @Test void runWithCqlSessionOnlyShouldCreateDriverIndicator() { this.contextRunner.withBean(CqlSession.class, () -> mock(CqlSession.class)) - .run((context) -> assertThat(context).hasSingleBean(CassandraDriverHealthIndicator.class)); + .run((context) -> assertThat(context).hasSingleBean(CassandraDriverHealthIndicator.class)); } @Test void runWithCqlSessionAndSpringDataAbsentShouldCreateDriverIndicator() { this.contextRunner.withBean(CqlSession.class, () -> mock(CqlSession.class)) - .withClassLoader(new FilteredClassLoader("org.springframework.data")) - .run((context) -> assertThat(context).hasSingleBean(CassandraDriverHealthIndicator.class)); + .withClassLoader(new FilteredClassLoader("org.springframework.data")) + .run((context) -> assertThat(context).hasSingleBean(CassandraDriverHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withBean(CqlSession.class, () -> mock(CqlSession.class)) - .withBean(CassandraOperations.class, () -> mock(CassandraOperations.class)) - .withPropertyValues("management.health.cassandra.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean("cassandraHealthContributor") - .doesNotHaveBean(CassandraDriverHealthIndicator.class)); + .withBean(CassandraOperations.class, () -> mock(CassandraOperations.class)) + .withPropertyValues("management.health.cassandra.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean("cassandraHealthContributor") + .doesNotHaveBean(CassandraDriverHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraReactiveHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraReactiveHealthContributorAutoConfigurationTests.java index e2485c0789..0f85369b4b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraReactiveHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraReactiveHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,45 +40,46 @@ import static org.mockito.Mockito.mock; class CassandraReactiveHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CassandraReactiveHealthContributorAutoConfiguration.class, - CassandraHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(CassandraReactiveHealthContributorAutoConfiguration.class, + CassandraHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runWithoutCqlSessionOrReactiveCassandraOperationsShouldNotCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean("cassandraHealthContributor") - .doesNotHaveBean(CassandraDriverReactiveHealthIndicator.class)); + .doesNotHaveBean(CassandraDriverReactiveHealthIndicator.class)); } @Test void runWithCqlSessionOnlyShouldCreateDriverIndicator() { - this.contextRunner.withBean(CqlSession.class, () -> mock(CqlSession.class)).run((context) -> assertThat(context) - .hasBean("cassandraHealthContributor").hasSingleBean(CassandraDriverReactiveHealthIndicator.class)); + this.contextRunner.withBean(CqlSession.class, () -> mock(CqlSession.class)) + .run((context) -> assertThat(context).hasBean("cassandraHealthContributor") + .hasSingleBean(CassandraDriverReactiveHealthIndicator.class)); } @Test void runWithCqlSessionAndReactiveCassandraOperationsShouldCreateDriverIndicator() { this.contextRunner.withBean(CqlSession.class, () -> mock(CqlSession.class)) - .withBean(ReactiveCassandraOperations.class, () -> mock(ReactiveCassandraOperations.class)) - .withBean(CassandraOperations.class, () -> mock(CassandraOperations.class)) - .run((context) -> assertThat(context).hasBean("cassandraHealthContributor") - .hasSingleBean(CassandraDriverReactiveHealthIndicator.class) - .doesNotHaveBean(CassandraDriverHealthIndicator.class)); + .withBean(ReactiveCassandraOperations.class, () -> mock(ReactiveCassandraOperations.class)) + .withBean(CassandraOperations.class, () -> mock(CassandraOperations.class)) + .run((context) -> assertThat(context).hasBean("cassandraHealthContributor") + .hasSingleBean(CassandraDriverReactiveHealthIndicator.class) + .doesNotHaveBean(CassandraDriverHealthIndicator.class)); } @Test void runWithCqlSessionAndSpringDataAbsentShouldCreateDriverIndicator() { this.contextRunner.withBean(CqlSession.class, () -> mock(CqlSession.class)) - .withClassLoader(new FilteredClassLoader("org.springframework.data")) - .run((context) -> assertThat(context).hasBean("cassandraHealthContributor") - .hasSingleBean(CassandraDriverReactiveHealthIndicator.class)); + .withClassLoader(new FilteredClassLoader("org.springframework.data")) + .run((context) -> assertThat(context).hasBean("cassandraHealthContributor") + .hasSingleBean(CassandraDriverReactiveHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withBean(CqlSession.class, () -> mock(CqlSession.class)) - .withBean(ReactiveCassandraOperations.class, () -> mock(ReactiveCassandraOperations.class)) - .withPropertyValues("management.health.cassandra.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean("cassandraHealthContributor")); + .withBean(ReactiveCassandraOperations.class, () -> mock(ReactiveCassandraOperations.class)) + .withPropertyValues("management.health.cassandra.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean("cassandraHealthContributor")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java index 7ac36ae23e..800ec2246b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,7 +58,7 @@ class CloudFoundryAuthorizationExceptionTests { @Test void statusCodeForUnsupportedSignatureAlgorithmReasonShouldBe401() { assertThat(createException(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM).getStatusCode()) - .isEqualTo(HttpStatus.UNAUTHORIZED); + .isEqualTo(HttpStatus.UNAUTHORIZED); } @Test @@ -74,7 +74,7 @@ class CloudFoundryAuthorizationExceptionTests { @Test void statusCodeForServiceUnavailableReasonShouldBe503() { assertThat(createException(Reason.SERVICE_UNAVAILABLE).getStatusCode()) - .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); + .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); } private CloudFoundryAuthorizationException createException(Reason reason) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscovererTests.java index cf3a9494ce..0311e14a4a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscovererTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,8 +62,8 @@ class CloudFoundryWebEndpointDiscovererTests { if (endpoint.getEndpointId().equals(EndpointId.of("health"))) { WebOperation operation = findMainReadOperation(endpoint); assertThat(operation - .invoke(new InvocationContext(mock(SecurityContext.class), Collections.emptyMap()))) - .isEqualTo("cf"); + .invoke(new InvocationContext(mock(SecurityContext.class), Collections.emptyMap()))) + .isEqualTo("cf"); } } }); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java index 45e9e2f362..ec764f7d65 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ class TokenTests { @Test void invalidJwtShouldThrowException() { assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(() -> new Token("invalid-token")) - .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -44,9 +44,9 @@ class TokenTests { String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "invalid-claims"; assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> new Token(Base64Utils.encodeToString(header.getBytes()) + "." - + Base64Utils.encodeToString(claims.getBytes()))) - .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); + .isThrownBy(() -> new Token(Base64Utils.encodeToString(header.getBytes()) + "." + + Base64Utils.encodeToString(claims.getBytes()))) + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -54,9 +54,9 @@ class TokenTests { String header = "invalid-header"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> new Token(Base64Utils.encodeToString(header.getBytes()) + "." - + Base64Utils.encodeToString(claims.getBytes()))) - .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); + .isThrownBy(() -> new Token(Base64Utils.encodeToString(header.getBytes()) + "." + + Base64Utils.encodeToString(claims.getBytes()))) + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -64,7 +64,7 @@ class TokenTests { String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0b3B0YWwu" + "Y29tIiwiZXhwIjoxNDI2NDIwODAwLCJhd2Vzb21lIjp0cnVlfQ."; assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(() -> new Token(token)) - .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -89,7 +89,7 @@ class TokenTests { String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; Token token = createToken(header, claims); assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(token::getSignatureAlgorithm) - .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -98,7 +98,7 @@ class TokenTests { String claims = "{\"exp\": 2147483647}"; Token token = createToken(header, claims); assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(token::getIssuer) - .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -107,7 +107,7 @@ class TokenTests { String claims = "{\"exp\": 2147483647}"; Token token = createToken(header, claims); assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(token::getKeyId) - .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -116,7 +116,7 @@ class TokenTests { String claims = "{\"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; Token token = createToken(header, claims); assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(token::getExpiry) - .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } private Token createToken(String header, String claims) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtensionTests.java index 79e977a7aa..e4eeaedbd9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtensionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,23 +50,23 @@ import static org.assertj.core.api.Assertions.assertThat; class CloudFoundryReactiveHealthEndpointWebExtensionTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withPropertyValues("VCAP_APPLICATION={}") - .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, - ReactiveUserDetailsServiceAutoConfiguration.class, WebFluxAutoConfiguration.class, - JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - ReactiveCloudFoundryActuatorAutoConfigurationTests.WebClientCustomizerConfig.class, - WebClientAutoConfiguration.class, ManagementContextAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - HealthContributorAutoConfiguration.class, HealthEndpointAutoConfiguration.class, - ReactiveCloudFoundryActuatorAutoConfiguration.class)) - .withUserConfiguration(TestHealthIndicator.class); + .withPropertyValues("VCAP_APPLICATION={}") + .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, + ReactiveUserDetailsServiceAutoConfiguration.class, WebFluxAutoConfiguration.class, + JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, + ReactiveCloudFoundryActuatorAutoConfigurationTests.WebClientCustomizerConfig.class, + WebClientAutoConfiguration.class, ManagementContextAutoConfiguration.class, + EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + HealthContributorAutoConfiguration.class, HealthEndpointAutoConfiguration.class, + ReactiveCloudFoundryActuatorAutoConfiguration.class)) + .withUserConfiguration(TestHealthIndicator.class); @Test void healthComponentsAlwaysPresent() { this.contextRunner.run((context) -> { CloudFoundryReactiveHealthEndpointWebExtension extension = context - .getBean(CloudFoundryReactiveHealthEndpointWebExtension.class); + .getBean(CloudFoundryReactiveHealthEndpointWebExtension.class); HealthComponent body = extension.health(ApiVersion.V3).block(Duration.ofSeconds(30)).getBody(); HealthComponent health = ((CompositeHealth) body).getComponents().entrySet().iterator().next().getValue(); assertThat(((Health) health).getDetails()).containsEntry("spring", "boot"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java index 7b1d3ad033..b5f08cfd63 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -78,50 +78,87 @@ class CloudFoundryWebFluxEndpointIntegrationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class, - HttpHandlerAutoConfiguration.class, ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(TestEndpointConfiguration.class).withPropertyValues("server.port=0"); + .withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, + ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(TestEndpointConfiguration.class) + .withPropertyValues("server.port=0"); @Test void operationWithSecurityInterceptorForbidden() { given(tokenValidator.validate(any())).willReturn(Mono.empty()); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.RESTRICTED)); - this.contextRunner.run(withWebTestClient((client) -> client.get().uri("/cfApplication/test") - .accept(MediaType.APPLICATION_JSON).header("Authorization", "bearer " + mockAccessToken()).exchange() - .expectStatus().isEqualTo(HttpStatus.FORBIDDEN))); + this.contextRunner.run(withWebTestClient((client) -> client.get() + .uri("/cfApplication/test") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.FORBIDDEN))); } @Test void operationWithSecurityInterceptorSuccess() { given(tokenValidator.validate(any())).willReturn(Mono.empty()); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.FULL)); - this.contextRunner.run(withWebTestClient((client) -> client.get().uri("/cfApplication/test") - .accept(MediaType.APPLICATION_JSON).header("Authorization", "bearer " + mockAccessToken()).exchange() - .expectStatus().isEqualTo(HttpStatus.OK))); + this.contextRunner.run(withWebTestClient((client) -> client.get() + .uri("/cfApplication/test") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.OK))); } @Test void responseToOptionsRequestIncludesCorsHeaders() { - this.contextRunner.run(withWebTestClient((client) -> client.options().uri("/cfApplication/test") - .accept(MediaType.APPLICATION_JSON).header("Access-Control-Request-Method", "POST") - .header("Origin", "https://example.com").exchange().expectStatus().isOk().expectHeader() - .valueEquals("Access-Control-Allow-Origin", "https://example.com").expectHeader() - .valueEquals("Access-Control-Allow-Methods", "GET,POST"))); + this.contextRunner.run(withWebTestClient((client) -> client.options() + .uri("/cfApplication/test") + .accept(MediaType.APPLICATION_JSON) + .header("Access-Control-Request-Method", "POST") + .header("Origin", "https://example.com") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueEquals("Access-Control-Allow-Origin", "https://example.com") + .expectHeader() + .valueEquals("Access-Control-Allow-Methods", "GET,POST"))); } @Test void linksToOtherEndpointsWithFullAccess() { given(tokenValidator.validate(any())).willReturn(Mono.empty()); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.FULL)); - this.contextRunner - .run(withWebTestClient((client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus().isOk() - .expectBody().jsonPath("_links.length()").isEqualTo(5).jsonPath("_links.self.href").isNotEmpty() - .jsonPath("_links.self.templated").isEqualTo(false).jsonPath("_links.info.href").isNotEmpty() - .jsonPath("_links.info.templated").isEqualTo(false).jsonPath("_links.env.href").isNotEmpty() - .jsonPath("_links.env.templated").isEqualTo(false).jsonPath("_links.test.href").isNotEmpty() - .jsonPath("_links.test.templated").isEqualTo(false).jsonPath("_links.test-part.href") - .isNotEmpty().jsonPath("_links.test-part.templated").isEqualTo(true))); + this.contextRunner.run(withWebTestClient((client) -> client.get() + .uri("/cfApplication") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("_links.length()") + .isEqualTo(5) + .jsonPath("_links.self.href") + .isNotEmpty() + .jsonPath("_links.self.templated") + .isEqualTo(false) + .jsonPath("_links.info.href") + .isNotEmpty() + .jsonPath("_links.info.templated") + .isEqualTo(false) + .jsonPath("_links.env.href") + .isNotEmpty() + .jsonPath("_links.env.templated") + .isEqualTo(false) + .jsonPath("_links.test.href") + .isNotEmpty() + .jsonPath("_links.test.templated") + .isEqualTo(false) + .jsonPath("_links.test-part.href") + .isNotEmpty() + .jsonPath("_links.test-part.templated") + .isEqualTo(true))); } @Test @@ -129,31 +166,55 @@ class CloudFoundryWebFluxEndpointIntegrationTests { CloudFoundryAuthorizationException exception = new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "invalid-token"); willThrow(exception).given(tokenValidator).validate(any()); - this.contextRunner.run(withWebTestClient((client) -> client.get().uri("/cfApplication") - .accept(MediaType.APPLICATION_JSON).header("Authorization", "bearer " + mockAccessToken()).exchange() - .expectStatus().isUnauthorized())); + this.contextRunner.run(withWebTestClient((client) -> client.get() + .uri("/cfApplication") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isUnauthorized())); } @Test void linksToOtherEndpointsWithRestrictedAccess() { given(tokenValidator.validate(any())).willReturn(Mono.empty()); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.RESTRICTED)); - this.contextRunner - .run(withWebTestClient((client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus().isOk() - .expectBody().jsonPath("_links.length()").isEqualTo(2).jsonPath("_links.self.href").isNotEmpty() - .jsonPath("_links.self.templated").isEqualTo(false).jsonPath("_links.info.href").isNotEmpty() - .jsonPath("_links.info.templated").isEqualTo(false).jsonPath("_links.env").doesNotExist() - .jsonPath("_links.test").doesNotExist().jsonPath("_links.test-part").doesNotExist())); + this.contextRunner.run(withWebTestClient((client) -> client.get() + .uri("/cfApplication") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("_links.length()") + .isEqualTo(2) + .jsonPath("_links.self.href") + .isNotEmpty() + .jsonPath("_links.self.templated") + .isEqualTo(false) + .jsonPath("_links.info.href") + .isNotEmpty() + .jsonPath("_links.info.templated") + .isEqualTo(false) + .jsonPath("_links.env") + .doesNotExist() + .jsonPath("_links.test") + .doesNotExist() + .jsonPath("_links.test-part") + .doesNotExist())); } private ContextConsumer withWebTestClient( Consumer clientConsumer) { return (context) -> { int port = ((AnnotationConfigReactiveWebServerApplicationContext) context.getSourceApplicationContext()) - .getWebServer().getPort(); - clientConsumer.accept(WebTestClient.bindToServer().baseUrl("http://localhost:" + port) - .responseTimeout(Duration.ofMinutes(5)).build()); + .getWebServer() + .getPort(); + clientConsumer.accept(WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port) + .responseTimeout(Duration.ofMinutes(5)) + .build()); }; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java index fadaeb8fee..79dda6f1e9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,15 +85,15 @@ class ReactiveCloudFoundryActuatorAutoConfigurationTests { private static final String V3_JSON = ApiVersion.V3.getProducedMimeType().toString(); private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, - ReactiveUserDetailsServiceAutoConfiguration.class, WebFluxAutoConfiguration.class, - JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, WebClientCustomizerConfig.class, - WebClientAutoConfiguration.class, ManagementContextAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - HealthContributorAutoConfiguration.class, HealthEndpointAutoConfiguration.class, - InfoContributorAutoConfiguration.class, InfoEndpointAutoConfiguration.class, - ProjectInfoAutoConfiguration.class, ReactiveCloudFoundryActuatorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, + ReactiveUserDetailsServiceAutoConfiguration.class, WebFluxAutoConfiguration.class, + JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, WebClientCustomizerConfig.class, + WebClientAutoConfiguration.class, ManagementContextAutoConfiguration.class, + EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + HealthContributorAutoConfiguration.class, HealthEndpointAutoConfiguration.class, + InfoContributorAutoConfiguration.class, InfoEndpointAutoConfiguration.class, + ProjectInfoAutoConfiguration.class, ReactiveCloudFoundryActuatorAutoConfiguration.class)); @AfterEach void close() { @@ -102,150 +102,163 @@ class ReactiveCloudFoundryActuatorAutoConfigurationTests { @Test void cloudFoundryPlatformActive() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); - EndpointMapping endpointMapping = (EndpointMapping) ReflectionTestUtils.getField(handlerMapping, - "endpointMapping"); - assertThat(endpointMapping.getPath()).isEqualTo("/cloudfoundryapplication"); - CorsConfiguration corsConfiguration = (CorsConfiguration) ReflectionTestUtils - .getField(handlerMapping, "corsConfiguration"); - assertThat(corsConfiguration.getAllowedOrigins()).contains("*"); - assertThat(corsConfiguration.getAllowedMethods()) - .containsAll(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); - assertThat(corsConfiguration.getAllowedHeaders()) - .containsAll(Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type")); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + EndpointMapping endpointMapping = (EndpointMapping) ReflectionTestUtils.getField(handlerMapping, + "endpointMapping"); + assertThat(endpointMapping.getPath()).isEqualTo("/cloudfoundryapplication"); + CorsConfiguration corsConfiguration = (CorsConfiguration) ReflectionTestUtils.getField(handlerMapping, + "corsConfiguration"); + assertThat(corsConfiguration.getAllowedOrigins()).contains("*"); + assertThat(corsConfiguration.getAllowedMethods()) + .containsAll(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); + assertThat(corsConfiguration.getAllowedHeaders()) + .containsAll(Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type")); + }); } @Test void cloudfoundryapplicationProducesActuatorMediaType() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { - WebTestClient webTestClient = WebTestClient.bindToApplicationContext(context).build(); - webTestClient.get().uri("/cloudfoundryapplication").header("Content-Type", - V2_JSON + ";charset=UTF-8"); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + WebTestClient webTestClient = WebTestClient.bindToApplicationContext(context).build(); + webTestClient.get().uri("/cloudfoundryapplication").header("Content-Type", V2_JSON + ";charset=UTF-8"); + }); } @Test void cloudFoundryPlatformActiveSetsApplicationId() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); - String applicationId = (String) ReflectionTestUtils.getField(interceptor, "applicationId"); - assertThat(applicationId).isEqualTo("my-app-id"); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + String applicationId = (String) ReflectionTestUtils.getField(interceptor, "applicationId"); + assertThat(applicationId).isEqualTo("my-app-id"); + }); } @Test void cloudFoundryPlatformActiveSetsCloudControllerUrl() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, - "cloudFoundrySecurityService"); - String cloudControllerUrl = (String) ReflectionTestUtils.getField(interceptorSecurityService, - "cloudControllerUrl"); - assertThat(cloudControllerUrl).isEqualTo("https://my-cloud-controller.com"); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, + "cloudFoundrySecurityService"); + String cloudControllerUrl = (String) ReflectionTestUtils.getField(interceptorSecurityService, + "cloudControllerUrl"); + assertThat(cloudControllerUrl).isEqualTo("https://my-cloud-controller.com"); + }); } @Test void cloudFoundryPlatformActiveAndCloudControllerUrlNotPresent() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") - .run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = context.getBean( - "cloudFoundryWebFluxEndpointHandlerMapping", - CloudFoundryWebFluxEndpointHandlerMapping.class); - Object securityInterceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils.getField(securityInterceptor, - "cloudFoundrySecurityService"); - assertThat(interceptorSecurityService).isNull(); - }); + .run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = context.getBean( + "cloudFoundryWebFluxEndpointHandlerMapping", CloudFoundryWebFluxEndpointHandlerMapping.class); + Object securityInterceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(securityInterceptor, + "cloudFoundrySecurityService"); + assertThat(interceptorSecurityService).isNull(); + }); } @Test @SuppressWarnings("unchecked") void cloudFoundryPathsIgnoredBySpringSecurity() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { - WebFilterChainProxy chainProxy = context.getBean(WebFilterChainProxy.class); - List filters = (List) ReflectionTestUtils - .getField(chainProxy, "filters"); - Boolean cfRequestMatches = filters.get(0) - .matches(MockServerWebExchange - .from(MockServerHttpRequest.get("/cloudfoundryapplication/my-path").build())) - .block(Duration.ofSeconds(30)); - Boolean otherRequestMatches = filters.get(0) - .matches(MockServerWebExchange.from(MockServerHttpRequest.get("/some-other-path").build())) - .block(Duration.ofSeconds(30)); - assertThat(cfRequestMatches).isTrue(); - assertThat(otherRequestMatches).isFalse(); - otherRequestMatches = filters.get(1) - .matches(MockServerWebExchange.from(MockServerHttpRequest.get("/some-other-path").build())) - .block(Duration.ofSeconds(30)); - assertThat(otherRequestMatches).isTrue(); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + WebFilterChainProxy chainProxy = context.getBean(WebFilterChainProxy.class); + List filters = (List) ReflectionTestUtils + .getField(chainProxy, "filters"); + Boolean cfRequestMatches = filters.get(0) + .matches(MockServerWebExchange + .from(MockServerHttpRequest.get("/cloudfoundryapplication/my-path").build())) + .block(Duration.ofSeconds(30)); + Boolean otherRequestMatches = filters.get(0) + .matches(MockServerWebExchange.from(MockServerHttpRequest.get("/some-other-path").build())) + .block(Duration.ofSeconds(30)); + assertThat(cfRequestMatches).isTrue(); + assertThat(otherRequestMatches).isFalse(); + otherRequestMatches = filters.get(1) + .matches(MockServerWebExchange.from(MockServerHttpRequest.get("/some-other-path").build())) + .block(Duration.ofSeconds(30)); + assertThat(otherRequestMatches).isTrue(); + }); } @Test void cloudFoundryPlatformInactive() { - this.contextRunner.run( - (context) -> assertThat(context.containsBean("cloudFoundryWebFluxEndpointHandlerMapping")).isFalse()); + this.contextRunner + .run((context) -> assertThat(context.containsBean("cloudFoundryWebFluxEndpointHandlerMapping")).isFalse()); } @Test void cloudFoundryManagementEndpointsDisabled() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION=---", "management.cloudfoundry.enabled:false").run( - (context) -> assertThat(context.containsBean("cloudFoundryWebFluxEndpointHandlerMapping")).isFalse()); + this.contextRunner.withPropertyValues("VCAP_APPLICATION=---", "management.cloudfoundry.enabled:false") + .run((context) -> assertThat(context.containsBean("cloudFoundryWebFluxEndpointHandlerMapping")).isFalse()); } @Test void allEndpointsAvailableUnderCloudFoundryWithoutEnablingWebIncludes() { - this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); - Collection endpoints = handlerMapping.getEndpoints(); - List endpointIds = endpoints.stream().map(ExposableWebEndpoint::getEndpointId) - .collect(Collectors.toList()); - assertThat(endpointIds).contains(EndpointId.of("test")); - }); + this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new) + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Collection endpoints = handlerMapping.getEndpoints(); + List endpointIds = endpoints.stream() + .map(ExposableWebEndpoint::getEndpointId) + .collect(Collectors.toList()); + assertThat(endpointIds).contains(EndpointId.of("test")); + }); } @Test void endpointPathCustomizationIsNotApplied() { - this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); - Collection endpoints = handlerMapping.getEndpoints(); - ExposableWebEndpoint endpoint = endpoints.stream() - .filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())).findFirst() - .get(); - assertThat(endpoint.getOperations()).hasSize(1); - WebOperation operation = endpoint.getOperations().iterator().next(); - assertThat(operation.getRequestPredicate().getPath()).isEqualTo("test"); - }); + this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new) + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Collection endpoints = handlerMapping.getEndpoints(); + ExposableWebEndpoint endpoint = endpoints.stream() + .filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())) + .findFirst() + .get(); + assertThat(endpoint.getOperations()).hasSize(1); + WebOperation operation = endpoint.getOperations().iterator().next(); + assertThat(operation.getRequestPredicate().getPath()).isEqualTo("test"); + }); } @Test void healthEndpointInvokerShouldBeCloudFoundryWebExtension() { this.contextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class)) - .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { - Collection endpoints = getHandlerMapping(context).getEndpoints(); - ExposableWebEndpoint endpoint = endpoints.iterator().next(); - assertThat(endpoint.getOperations()).hasSize(2); - WebOperation webOperation = findOperationWithRequestPath(endpoint, "health"); - assertThat(webOperation).extracting("invoker").extracting("target") - .isInstanceOf(CloudFoundryReactiveHealthEndpointWebExtension.class); - }); + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + Collection endpoints = getHandlerMapping(context).getEndpoints(); + ExposableWebEndpoint endpoint = endpoints.iterator().next(); + assertThat(endpoint.getOperations()).hasSize(2); + WebOperation webOperation = findOperationWithRequestPath(endpoint, "health"); + assertThat(webOperation).extracting("invoker") + .extracting("target") + .isInstanceOf(CloudFoundryReactiveHealthEndpointWebExtension.class); + }); } @Test @@ -253,7 +266,7 @@ class ReactiveCloudFoundryActuatorAutoConfigurationTests { void gitFullDetailsAlwaysPresent() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---").run((context) -> { CloudFoundryInfoEndpointWebExtension extension = context - .getBean(CloudFoundryInfoEndpointWebExtension.class); + .getBean(CloudFoundryInfoEndpointWebExtension.class); Map git = (Map) extension.info().get("git"); Map commit = (Map) git.get("commit"); assertThat(commit).hasSize(4); @@ -263,38 +276,42 @@ class ReactiveCloudFoundryActuatorAutoConfigurationTests { @Test void skipSslValidation() { this.contextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class)) - .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com", - "management.cloudfoundry.skip-ssl-validation:true") - .run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, - "cloudFoundrySecurityService"); - WebClient webClient = (WebClient) ReflectionTestUtils.getField(interceptorSecurityService, - "webClient"); - webClient.get().uri("https://self-signed.badssl.com/").retrieve().toBodilessEntity() - .block(Duration.ofSeconds(30)); - }); + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com", + "management.cloudfoundry.skip-ssl-validation:true") + .run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, + "cloudFoundrySecurityService"); + WebClient webClient = (WebClient) ReflectionTestUtils.getField(interceptorSecurityService, "webClient"); + webClient.get() + .uri("https://self-signed.badssl.com/") + .retrieve() + .toBodilessEntity() + .block(Duration.ofSeconds(30)); + }); } @Test void sslValidationNotSkippedByDefault() { this.contextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class)) - .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, - "cloudFoundrySecurityService"); - WebClient webClient = (WebClient) ReflectionTestUtils.getField(interceptorSecurityService, - "webClient"); - assertThatExceptionOfType(RuntimeException.class) - .isThrownBy(() -> webClient.get().uri("https://self-signed.badssl.com/").retrieve() - .toBodilessEntity().block(Duration.ofSeconds(30))) - .withCauseInstanceOf(SSLException.class); - }); + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, + "cloudFoundrySecurityService"); + WebClient webClient = (WebClient) ReflectionTestUtils.getField(interceptorSecurityService, "webClient"); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> webClient.get() + .uri("https://self-signed.badssl.com/") + .retrieve() + .toBodilessEntity() + .block(Duration.ofSeconds(30))) + .withCauseInstanceOf(SSLException.class); + }); } private CloudFoundryWebFluxEndpointHandlerMapping getHandlerMapping(ApplicationContext context) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityInterceptorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityInterceptorTests.java index 5e88fd55cb..46e53f65eb 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityInterceptorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,64 +60,68 @@ class ReactiveCloudFoundrySecurityInterceptorTests { @Test void preHandleWhenRequestIsPreFlightShouldBeOk() { - MockServerWebExchange request = MockServerWebExchange - .from(MockServerHttpRequest.options("/a").header(HttpHeaders.ORIGIN, "https://example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").build()); + MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest.options("/a") + .header(HttpHeaders.ORIGIN, "https://example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .build()); StepVerifier.create(this.interceptor.preHandle(request, "/a")) - .consumeNextWith((response) -> assertThat(response.getStatus()).isEqualTo(HttpStatus.OK)) - .verifyComplete(); + .consumeNextWith((response) -> assertThat(response.getStatus()).isEqualTo(HttpStatus.OK)) + .verifyComplete(); } @Test void preHandleWhenTokenIsMissingShouldReturnMissingAuthorization() { MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest.get("/a").build()); - StepVerifier.create(this.interceptor.preHandle(request, "/a")).consumeNextWith( - (response) -> assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus())) - .verifyComplete(); + StepVerifier.create(this.interceptor.preHandle(request, "/a")) + .consumeNextWith( + (response) -> assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus())) + .verifyComplete(); } @Test void preHandleWhenTokenIsNotBearerShouldReturnMissingAuthorization() { MockServerWebExchange request = MockServerWebExchange - .from(MockServerHttpRequest.get("/a").header(HttpHeaders.AUTHORIZATION, mockAccessToken()).build()); - StepVerifier.create(this.interceptor.preHandle(request, "/a")).consumeNextWith( - (response) -> assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus())) - .verifyComplete(); + .from(MockServerHttpRequest.get("/a").header(HttpHeaders.AUTHORIZATION, mockAccessToken()).build()); + StepVerifier.create(this.interceptor.preHandle(request, "/a")) + .consumeNextWith( + (response) -> assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus())) + .verifyComplete(); } @Test void preHandleWhenApplicationIdIsNullShouldReturnError() { this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, this.securityService, null); MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest.get("/a") - .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()).build()); + .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()) + .build()); StepVerifier.create(this.interceptor.preHandle(request, "/a")) - .consumeErrorWith((ex) -> assertThat(((CloudFoundryAuthorizationException) ex).getReason()) - .isEqualTo(Reason.SERVICE_UNAVAILABLE)) - .verify(); + .consumeErrorWith((ex) -> assertThat(((CloudFoundryAuthorizationException) ex).getReason()) + .isEqualTo(Reason.SERVICE_UNAVAILABLE)) + .verify(); } @Test void preHandleWhenCloudFoundrySecurityServiceIsNullShouldReturnError() { this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, null, "my-app-id"); MockServerWebExchange request = MockServerWebExchange - .from(MockServerHttpRequest.get("/a").header(HttpHeaders.AUTHORIZATION, mockAccessToken()).build()); + .from(MockServerHttpRequest.get("/a").header(HttpHeaders.AUTHORIZATION, mockAccessToken()).build()); StepVerifier.create(this.interceptor.preHandle(request, "/a")) - .consumeErrorWith((ex) -> assertThat(((CloudFoundryAuthorizationException) ex).getReason()) - .isEqualTo(Reason.SERVICE_UNAVAILABLE)) - .verify(); + .consumeErrorWith((ex) -> assertThat(((CloudFoundryAuthorizationException) ex).getReason()) + .isEqualTo(Reason.SERVICE_UNAVAILABLE)) + .verify(); } @Test void preHandleWhenAccessIsNotAllowedShouldReturnAccessDenied() { given(this.securityService.getAccessLevel(mockAccessToken(), "my-app-id")) - .willReturn(Mono.just(AccessLevel.RESTRICTED)); + .willReturn(Mono.just(AccessLevel.RESTRICTED)); given(this.tokenValidator.validate(any())).willReturn(Mono.empty()); MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest.get("/a") - .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()).build()); + .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()) + .build()); StepVerifier.create(this.interceptor.preHandle(request, "/a")) - .consumeNextWith( - (response) -> assertThat(response.getStatus()).isEqualTo(Reason.ACCESS_DENIED.getStatus())) - .verifyComplete(); + .consumeNextWith((response) -> assertThat(response.getStatus()).isEqualTo(Reason.ACCESS_DENIED.getStatus())) + .verifyComplete(); } @Test @@ -126,7 +130,8 @@ class ReactiveCloudFoundrySecurityInterceptorTests { given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(Mono.just(AccessLevel.FULL)); given(this.tokenValidator.validate(any())).willReturn(Mono.empty()); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/a") - .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()).build()); + .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()) + .build()); StepVerifier.create(this.interceptor.preHandle(exchange, "/a")).consumeNextWith((response) -> { assertThat(response.getStatus()).isEqualTo(HttpStatus.OK); assertThat((AccessLevel) exchange.getAttribute("cloudFoundryAccessLevel")).isEqualTo(AccessLevel.FULL); @@ -137,14 +142,15 @@ class ReactiveCloudFoundrySecurityInterceptorTests { void preHandleSuccessfulWithRestrictedAccess() { String accessToken = mockAccessToken(); given(this.securityService.getAccessLevel(accessToken, "my-app-id")) - .willReturn(Mono.just(AccessLevel.RESTRICTED)); + .willReturn(Mono.just(AccessLevel.RESTRICTED)); given(this.tokenValidator.validate(any())).willReturn(Mono.empty()); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/info") - .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()).build()); + .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()) + .build()); StepVerifier.create(this.interceptor.preHandle(exchange, "info")).consumeNextWith((response) -> { assertThat(response.getStatus()).isEqualTo(HttpStatus.OK); assertThat((AccessLevel) exchange.getAttribute("cloudFoundryAccessLevel")) - .isEqualTo(AccessLevel.RESTRICTED); + .isEqualTo(AccessLevel.RESTRICTED); }).verifyComplete(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityServiceTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityServiceTests.java index f082733ea3..4f69ad64df 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityServiceTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,8 +70,9 @@ class ReactiveCloudFoundrySecurityServiceTests { String responseBody = "{\"read_sensitive_data\": true,\"read_basic_data\": true}"; prepareResponse((response) -> response.setBody(responseBody).setHeader("Content-Type", "application/json")); StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) - .consumeNextWith((accessLevel) -> assertThat(accessLevel).isEqualTo(AccessLevel.FULL)).expectComplete() - .verify(); + .consumeNextWith((accessLevel) -> assertThat(accessLevel).isEqualTo(AccessLevel.FULL)) + .expectComplete() + .verify(); expectRequest((request) -> { assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token"); assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS); @@ -83,8 +84,9 @@ class ReactiveCloudFoundrySecurityServiceTests { String responseBody = "{\"read_sensitive_data\": false,\"read_basic_data\": true}"; prepareResponse((response) -> response.setBody(responseBody).setHeader("Content-Type", "application/json")); StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) - .consumeNextWith((accessLevel) -> assertThat(accessLevel).isEqualTo(AccessLevel.RESTRICTED)) - .expectComplete().verify(); + .consumeNextWith((accessLevel) -> assertThat(accessLevel).isEqualTo(AccessLevel.RESTRICTED)) + .expectComplete() + .verify(); expectRequest((request) -> { assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token"); assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS); @@ -95,11 +97,12 @@ class ReactiveCloudFoundrySecurityServiceTests { void getAccessLevelWhenTokenIsNotValidShouldThrowException() throws Exception { prepareResponse((response) -> response.setResponseCode(401)); StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) - .consumeErrorWith((throwable) -> { - assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) - .isEqualTo(Reason.INVALID_TOKEN); - }).verify(); + .consumeErrorWith((throwable) -> { + assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) + .isEqualTo(Reason.INVALID_TOKEN); + }) + .verify(); expectRequest((request) -> { assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token"); assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS); @@ -110,11 +113,12 @@ class ReactiveCloudFoundrySecurityServiceTests { void getAccessLevelWhenForbiddenShouldThrowException() throws Exception { prepareResponse((response) -> response.setResponseCode(403)); StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) - .consumeErrorWith((throwable) -> { - assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) - .isEqualTo(Reason.ACCESS_DENIED); - }).verify(); + .consumeErrorWith((throwable) -> { + assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) + .isEqualTo(Reason.ACCESS_DENIED); + }) + .verify(); expectRequest((request) -> { assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token"); assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS); @@ -125,11 +129,12 @@ class ReactiveCloudFoundrySecurityServiceTests { void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() throws Exception { prepareResponse((response) -> response.setResponseCode(500)); StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) - .consumeErrorWith((throwable) -> { - assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) - .isEqualTo(Reason.SERVICE_UNAVAILABLE); - }).verify(); + .consumeErrorWith((throwable) -> { + assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) + .isEqualTo(Reason.SERVICE_UNAVAILABLE); + }) + .verify(); expectRequest((request) -> { assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token"); assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS); @@ -157,8 +162,9 @@ class ReactiveCloudFoundrySecurityServiceTests { response.setHeader("Content-Type", "application/json"); }); StepVerifier.create(this.securityService.fetchTokenKeys()) - .consumeNextWith((tokenKeys) -> assertThat(tokenKeys.get("test-key")).isEqualTo(tokenKeyValue)) - .expectComplete().verify(); + .consumeNextWith((tokenKeys) -> assertThat(tokenKeys.get("test-key")).isEqualTo(tokenKeyValue)) + .expectComplete() + .verify(); expectRequest((request) -> assertThat(request.getPath()).isEqualTo("/my-cloud-controller.com/info")); expectRequest((request) -> assertThat(request.getPath()).isEqualTo("/my-uaa.com/token_keys")); } @@ -175,7 +181,9 @@ class ReactiveCloudFoundrySecurityServiceTests { response.setHeader("Content-Type", "application/json"); }); StepVerifier.create(this.securityService.fetchTokenKeys()) - .consumeNextWith((tokenKeys) -> assertThat(tokenKeys).hasSize(0)).expectComplete().verify(); + .consumeNextWith((tokenKeys) -> assertThat(tokenKeys).hasSize(0)) + .expectComplete() + .verify(); expectRequest((request) -> assertThat(request.getPath()).isEqualTo("/my-cloud-controller.com/info")); expectRequest((request) -> assertThat(request.getPath()).isEqualTo("/my-uaa.com/token_keys")); } @@ -188,10 +196,9 @@ class ReactiveCloudFoundrySecurityServiceTests { }); prepareResponse((response) -> response.setResponseCode(500)); StepVerifier.create(this.securityService.fetchTokenKeys()) - .consumeErrorWith( - (throwable) -> assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) - .isEqualTo(Reason.SERVICE_UNAVAILABLE)) - .verify(); + .consumeErrorWith((throwable) -> assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) + .isEqualTo(Reason.SERVICE_UNAVAILABLE)) + .verify(); expectRequest((request) -> assertThat(request.getPath()).isEqualTo("/my-cloud-controller.com/info")); expectRequest((request) -> assertThat(request.getPath()).isEqualTo("/my-uaa.com/token_keys")); } @@ -203,7 +210,9 @@ class ReactiveCloudFoundrySecurityServiceTests { response.setHeader("Content-Type", "application/json"); }); StepVerifier.create(this.securityService.getUaaUrl()) - .consumeNextWith((uaaUrl) -> assertThat(uaaUrl).isEqualTo(UAA_URL)).expectComplete().verify(); + .consumeNextWith((uaaUrl) -> assertThat(uaaUrl).isEqualTo(UAA_URL)) + .expectComplete() + .verify(); expectRequest((request) -> assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER + "/info")); expectRequestCount(1); } @@ -214,7 +223,7 @@ class ReactiveCloudFoundrySecurityServiceTests { StepVerifier.create(this.securityService.getUaaUrl()).consumeErrorWith((throwable) -> { assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) - .isEqualTo(Reason.SERVICE_UNAVAILABLE); + .isEqualTo(Reason.SERVICE_UNAVAILABLE); }).verify(); expectRequest((request) -> assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER + "/info")); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidatorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidatorTests.java index b2ca744728..7dcaadc6d7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidatorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -101,11 +101,12 @@ class ReactiveTokenValidatorTests { String header = "{\"alg\": \"RS256\", \"kid\": \"invalid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_KEY_ID); - }).verify(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .consumeErrorWith((ex) -> { + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_KEY_ID); + }) + .verify(); assertThat(this.tokenValidator).hasFieldOrPropertyWithValue("cachedTokenKeys", VALID_KEYS); fetchTokenKeys.assertWasSubscribed(); } @@ -119,8 +120,8 @@ class ReactiveTokenValidatorTests { String header = "{\"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .verifyComplete(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .verifyComplete(); assertThat(this.tokenValidator).hasFieldOrPropertyWithValue("cachedTokenKeys", VALID_KEYS); fetchTokenKeys.assertWasSubscribed(); } @@ -133,8 +134,8 @@ class ReactiveTokenValidatorTests { String header = "{\"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .verifyComplete(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .verifyComplete(); assertThat(this.tokenValidator).hasFieldOrPropertyWithValue("cachedTokenKeys", VALID_KEYS); fetchTokenKeys.assertWasSubscribed(); } @@ -147,11 +148,12 @@ class ReactiveTokenValidatorTests { String header = "{\"alg\": \"RS256\", \"kid\": \"invalid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_KEY_ID); - }).verify(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .consumeErrorWith((ex) -> { + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_KEY_ID); + }) + .verify(); assertThat(this.tokenValidator).hasFieldOrPropertyWithValue("cachedTokenKeys", VALID_KEYS); fetchTokenKeys.assertWasSubscribed(); } @@ -164,8 +166,8 @@ class ReactiveTokenValidatorTests { String header = "{\"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .verifyComplete(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .verifyComplete(); fetchTokenKeys.assertWasNotSubscribed(); } @@ -177,12 +179,12 @@ class ReactiveTokenValidatorTests { String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) ex).getReason()) - .isEqualTo(Reason.INVALID_SIGNATURE); - }).verify(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .consumeErrorWith((ex) -> { + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_SIGNATURE); + }) + .verify(); } @Test @@ -192,12 +194,13 @@ class ReactiveTokenValidatorTests { String header = "{ \"alg\": \"HS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) ex).getReason()) - .isEqualTo(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM); - }).verify(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .consumeErrorWith((ex) -> { + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) ex).getReason()) + .isEqualTo(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM); + }) + .verify(); } @Test @@ -207,11 +210,12 @@ class ReactiveTokenValidatorTests { String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"jti\": \"0236399c350c47f3ae77e67a75e75e7d\", \"exp\": 1477509977, \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.TOKEN_EXPIRED); - }).verify(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .consumeErrorWith((ex) -> { + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.TOKEN_EXPIRED); + }) + .verify(); } @Test @@ -221,11 +225,12 @@ class ReactiveTokenValidatorTests { String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\", \"scope\": [\"actuator.read\"]}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"foo.bar\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_ISSUER); - }).verify(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .consumeErrorWith((ex) -> { + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_ISSUER); + }) + .verify(); } @Test @@ -235,12 +240,12 @@ class ReactiveTokenValidatorTests { String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"foo.bar\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) ex).getReason()) - .isEqualTo(Reason.INVALID_AUDIENCE); - }).verify(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .consumeErrorWith((ex) -> { + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_AUDIENCE); + }) + .verify(); } private String getSignedToken(byte[] header, byte[] claims) throws Exception { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfigurationTests.java index 04f261b6cd..5314b4e6b8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,172 +70,183 @@ class CloudFoundryActuatorAutoConfigurationTests { private static final String V3_JSON = ApiVersion.V3.getProducedMimeType().toString(); private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, - JacksonAutoConfiguration.class, DispatcherServletAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - RestTemplateAutoConfiguration.class, ManagementContextAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, + JacksonAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + RestTemplateAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ServletManagementContextAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)); @Test void cloudFoundryPlatformActive() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); - EndpointMapping endpointMapping = (EndpointMapping) ReflectionTestUtils.getField(handlerMapping, - "endpointMapping"); - assertThat(endpointMapping.getPath()).isEqualTo("/cloudfoundryapplication"); - CorsConfiguration corsConfiguration = (CorsConfiguration) ReflectionTestUtils - .getField(handlerMapping, "corsConfiguration"); - assertThat(corsConfiguration.getAllowedOrigins()).contains("*"); - assertThat(corsConfiguration.getAllowedMethods()) - .containsAll(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); - assertThat(corsConfiguration.getAllowedHeaders()) - .containsAll(Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type")); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + EndpointMapping endpointMapping = (EndpointMapping) ReflectionTestUtils.getField(handlerMapping, + "endpointMapping"); + assertThat(endpointMapping.getPath()).isEqualTo("/cloudfoundryapplication"); + CorsConfiguration corsConfiguration = (CorsConfiguration) ReflectionTestUtils.getField(handlerMapping, + "corsConfiguration"); + assertThat(corsConfiguration.getAllowedOrigins()).contains("*"); + assertThat(corsConfiguration.getAllowedMethods()) + .containsAll(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); + assertThat(corsConfiguration.getAllowedHeaders()) + .containsAll(Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type")); + }); } @Test void cloudfoundryapplicationProducesActuatorMediaType() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); - mockMvc.perform(get("/cloudfoundryapplication")) - .andExpect(header().string("Content-Type", V3_JSON)); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); + mockMvc.perform(get("/cloudfoundryapplication")).andExpect(header().string("Content-Type", V3_JSON)); + }); } @Test void cloudFoundryPlatformActiveSetsApplicationId() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); - String applicationId = (String) ReflectionTestUtils.getField(interceptor, "applicationId"); - assertThat(applicationId).isEqualTo("my-app-id"); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + String applicationId = (String) ReflectionTestUtils.getField(interceptor, "applicationId"); + assertThat(applicationId).isEqualTo("my-app-id"); + }); } @Test void cloudFoundryPlatformActiveSetsCloudControllerUrl() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, - "cloudFoundrySecurityService"); - String cloudControllerUrl = (String) ReflectionTestUtils.getField(interceptorSecurityService, - "cloudControllerUrl"); - assertThat(cloudControllerUrl).isEqualTo("https://my-cloud-controller.com"); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, + "cloudFoundrySecurityService"); + String cloudControllerUrl = (String) ReflectionTestUtils.getField(interceptorSecurityService, + "cloudControllerUrl"); + assertThat(cloudControllerUrl).isEqualTo("https://my-cloud-controller.com"); + }); } @Test void skipSslValidation() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com", - "management.cloudfoundry.skip-ssl-validation:true").run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, - "cloudFoundrySecurityService"); - RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(interceptorSecurityService, - "restTemplate"); - assertThat(restTemplate.getRequestFactory()) - .isInstanceOf(SkipSslVerificationHttpRequestFactory.class); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com", + "management.cloudfoundry.skip-ssl-validation:true") + .run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, + "cloudFoundrySecurityService"); + RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(interceptorSecurityService, + "restTemplate"); + assertThat(restTemplate.getRequestFactory()).isInstanceOf(SkipSslVerificationHttpRequestFactory.class); + }); } @Test void cloudFoundryPlatformActiveAndCloudControllerUrlNotPresent() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") - .run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); - Object securityInterceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils.getField(securityInterceptor, - "cloudFoundrySecurityService"); - assertThat(interceptorSecurityService).isNull(); - }); + .run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + Object securityInterceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(securityInterceptor, + "cloudFoundrySecurityService"); + assertThat(interceptorSecurityService).isNull(); + }); } @Test void cloudFoundryPathsIgnoredBySpringSecurity() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") - .run((context) -> { - FilterChainProxy securityFilterChain = (FilterChainProxy) context - .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); - SecurityFilterChain chain = securityFilterChain.getFilterChains().get(0); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setServletPath("/cloudfoundryapplication/my-path"); - assertThat(chain.getFilters()).isEmpty(); - assertThat(chain.matches(request)).isTrue(); - request.setServletPath("/some-other-path"); - assertThat(chain.matches(request)).isFalse(); - }); + .run((context) -> { + FilterChainProxy securityFilterChain = (FilterChainProxy) context + .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); + SecurityFilterChain chain = securityFilterChain.getFilterChains().get(0); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setServletPath("/cloudfoundryapplication/my-path"); + assertThat(chain.getFilters()).isEmpty(); + assertThat(chain.matches(request)).isTrue(); + request.setServletPath("/some-other-path"); + assertThat(chain.matches(request)).isFalse(); + }); } @Test void cloudFoundryPlatformInactive() { this.contextRunner.withPropertyValues() - .run((context) -> assertThat(context.containsBean("cloudFoundryWebEndpointServletHandlerMapping")) - .isFalse()); + .run((context) -> assertThat(context.containsBean("cloudFoundryWebEndpointServletHandlerMapping")) + .isFalse()); } @Test void cloudFoundryManagementEndpointsDisabled() { this.contextRunner.withPropertyValues("VCAP_APPLICATION=---", "management.cloudfoundry.enabled:false") - .run((context) -> assertThat(context.containsBean("cloudFoundryEndpointHandlerMapping")).isFalse()); + .run((context) -> assertThat(context.containsBean("cloudFoundryEndpointHandlerMapping")).isFalse()); } @Test void allEndpointsAvailableUnderCloudFoundryWithoutExposeAllOnWeb() { - this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); - Collection endpoints = handlerMapping.getEndpoints(); - assertThat(endpoints.stream() - .filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())).findFirst()) - .isNotEmpty(); - }); + this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new) + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + Collection endpoints = handlerMapping.getEndpoints(); + assertThat(endpoints.stream() + .filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())) + .findFirst()).isNotEmpty(); + }); } @Test void endpointPathCustomizationIsNotApplied() { this.contextRunner - .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com", - "management.endpoints.web.path-mapping.test=custom") - .withBean(TestEndpoint.class, TestEndpoint::new).run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); - Collection endpoints = handlerMapping.getEndpoints(); - ExposableWebEndpoint endpoint = endpoints.stream() - .filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())).findFirst() - .get(); - Collection operations = endpoint.getOperations(); - assertThat(operations).hasSize(1); - assertThat(operations.iterator().next().getRequestPredicate().getPath()).isEqualTo("test"); - }); + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com", + "management.endpoints.web.path-mapping.test=custom") + .withBean(TestEndpoint.class, TestEndpoint::new) + .run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + Collection endpoints = handlerMapping.getEndpoints(); + ExposableWebEndpoint endpoint = endpoints.stream() + .filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())) + .findFirst() + .get(); + Collection operations = endpoint.getOperations(); + assertThat(operations).hasSize(1); + assertThat(operations.iterator().next().getRequestPredicate().getPath()).isEqualTo("test"); + }); } @Test void healthEndpointInvokerShouldBeCloudFoundryWebExtension() { this.contextRunner - .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") - .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class)) - .run((context) -> { - Collection endpoints = context - .getBean("cloudFoundryWebEndpointServletHandlerMapping", - CloudFoundryWebEndpointServletHandlerMapping.class) - .getEndpoints(); - ExposableWebEndpoint endpoint = endpoints.iterator().next(); - assertThat(endpoint.getOperations()).hasSize(2); - WebOperation webOperation = findOperationWithRequestPath(endpoint, "health"); - assertThat(webOperation).extracting("invoker.target") - .isInstanceOf(CloudFoundryHealthEndpointWebExtension.class); - }); + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, + HealthEndpointAutoConfiguration.class)) + .run((context) -> { + Collection endpoints = context + .getBean("cloudFoundryWebEndpointServletHandlerMapping", + CloudFoundryWebEndpointServletHandlerMapping.class) + .getEndpoints(); + ExposableWebEndpoint endpoint = endpoints.iterator().next(); + assertThat(endpoint.getOperations()).hasSize(2); + WebOperation webOperation = findOperationWithRequestPath(endpoint, "health"); + assertThat(webOperation).extracting("invoker.target") + .isInstanceOf(CloudFoundryHealthEndpointWebExtension.class); + }); } private CloudFoundryWebEndpointServletHandlerMapping getHandlerMapping(ApplicationContext context) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryHealthEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryHealthEndpointWebExtensionTests.java index 024c7b107f..f113a01ccf 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryHealthEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryHealthEndpointWebExtensionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,21 +49,21 @@ import static org.assertj.core.api.Assertions.assertThat; class CloudFoundryHealthEndpointWebExtensionTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withPropertyValues("VCAP_APPLICATION={}") - .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, - JacksonAutoConfiguration.class, DispatcherServletAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - RestTemplateAutoConfiguration.class, ManagementContextAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, HealthContributorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)) - .withUserConfiguration(TestHealthIndicator.class); + .withPropertyValues("VCAP_APPLICATION={}") + .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, + JacksonAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + RestTemplateAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ServletManagementContextAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, HealthContributorAutoConfiguration.class, + HealthEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)) + .withUserConfiguration(TestHealthIndicator.class); @Test void healthComponentsAlwaysPresent() { this.contextRunner.run((context) -> { CloudFoundryHealthEndpointWebExtension extension = context - .getBean(CloudFoundryHealthEndpointWebExtension.class); + .getBean(CloudFoundryHealthEndpointWebExtension.class); HealthComponent body = extension.health(ApiVersion.V3).getBody(); HealthComponent health = ((CompositeHealth) body).getComponents().entrySet().iterator().next().getValue(); assertThat(((Health) health).getDetails()).containsEntry("spring", "boot"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryInfoEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryInfoEndpointWebExtensionTests.java index 042e7988c6..e8cebbf1dd 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryInfoEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryInfoEndpointWebExtensionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,22 +48,22 @@ import static org.assertj.core.api.Assertions.assertThat; class CloudFoundryInfoEndpointWebExtensionTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withPropertyValues("VCAP_APPLICATION={}") - .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, - JacksonAutoConfiguration.class, DispatcherServletAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - RestTemplateAutoConfiguration.class, ManagementContextAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, ProjectInfoAutoConfiguration.class, - InfoContributorAutoConfiguration.class, InfoEndpointAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)); + .withPropertyValues("VCAP_APPLICATION={}") + .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, + JacksonAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + RestTemplateAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ServletManagementContextAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, ProjectInfoAutoConfiguration.class, + InfoContributorAutoConfiguration.class, InfoEndpointAutoConfiguration.class, + HealthEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)); @Test @SuppressWarnings("unchecked") void gitFullDetailsAlwaysPresent() { this.contextRunner.run((context) -> { CloudFoundryInfoEndpointWebExtension extension = context - .getBean(CloudFoundryInfoEndpointWebExtension.class); + .getBean(CloudFoundryInfoEndpointWebExtension.class); Map git = (Map) extension.info().get("git"); Map commit = (Map) git.get("commit"); assertThat(commit).hasSize(4); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryMvcWebEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryMvcWebEndpointIntegrationTests.java index a7affad6a0..60aef8eabc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryMvcWebEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryMvcWebEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,42 +74,79 @@ class CloudFoundryMvcWebEndpointIntegrationTests { void operationWithSecurityInterceptorForbidden() { given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.RESTRICTED); load(TestEndpointConfiguration.class, - (client) -> client.get().uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus() - .isEqualTo(HttpStatus.FORBIDDEN)); + (client) -> client.get() + .uri("/cfApplication/test") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.FORBIDDEN)); } @Test void operationWithSecurityInterceptorSuccess() { given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.FULL); load(TestEndpointConfiguration.class, - (client) -> client.get().uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus() - .isEqualTo(HttpStatus.OK)); + (client) -> client.get() + .uri("/cfApplication/test") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.OK)); } @Test void responseToOptionsRequestIncludesCorsHeaders() { load(TestEndpointConfiguration.class, - (client) -> client.options().uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) - .header("Access-Control-Request-Method", "POST").header("Origin", "https://example.com") - .exchange().expectStatus().isOk().expectHeader() - .valueEquals("Access-Control-Allow-Origin", "https://example.com").expectHeader() - .valueEquals("Access-Control-Allow-Methods", "GET,POST")); + (client) -> client.options() + .uri("/cfApplication/test") + .accept(MediaType.APPLICATION_JSON) + .header("Access-Control-Request-Method", "POST") + .header("Origin", "https://example.com") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueEquals("Access-Control-Allow-Origin", "https://example.com") + .expectHeader() + .valueEquals("Access-Control-Allow-Methods", "GET,POST")); } @Test void linksToOtherEndpointsWithFullAccess() { given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.FULL); load(TestEndpointConfiguration.class, - (client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus().isOk() - .expectBody().jsonPath("_links.length()").isEqualTo(5).jsonPath("_links.self.href").isNotEmpty() - .jsonPath("_links.self.templated").isEqualTo(false).jsonPath("_links.info.href").isNotEmpty() - .jsonPath("_links.info.templated").isEqualTo(false).jsonPath("_links.env.href").isNotEmpty() - .jsonPath("_links.env.templated").isEqualTo(false).jsonPath("_links.test.href").isNotEmpty() - .jsonPath("_links.test.templated").isEqualTo(false).jsonPath("_links.test-part.href") - .isNotEmpty().jsonPath("_links.test-part.templated").isEqualTo(true)); + (client) -> client.get() + .uri("/cfApplication") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("_links.length()") + .isEqualTo(5) + .jsonPath("_links.self.href") + .isNotEmpty() + .jsonPath("_links.self.templated") + .isEqualTo(false) + .jsonPath("_links.info.href") + .isNotEmpty() + .jsonPath("_links.info.templated") + .isEqualTo(false) + .jsonPath("_links.env.href") + .isNotEmpty() + .jsonPath("_links.env.templated") + .isEqualTo(false) + .jsonPath("_links.test.href") + .isNotEmpty() + .jsonPath("_links.test.templated") + .isEqualTo(false) + .jsonPath("_links.test-part.href") + .isNotEmpty() + .jsonPath("_links.test-part.templated") + .isEqualTo(true)); } @Test @@ -118,21 +155,43 @@ class CloudFoundryMvcWebEndpointIntegrationTests { "invalid-token"); willThrow(exception).given(tokenValidator).validate(any()); load(TestEndpointConfiguration.class, - (client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus() - .isUnauthorized()); + (client) -> client.get() + .uri("/cfApplication") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isUnauthorized()); } @Test void linksToOtherEndpointsWithRestrictedAccess() { given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.RESTRICTED); load(TestEndpointConfiguration.class, - (client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus().isOk() - .expectBody().jsonPath("_links.length()").isEqualTo(2).jsonPath("_links.self.href").isNotEmpty() - .jsonPath("_links.self.templated").isEqualTo(false).jsonPath("_links.info.href").isNotEmpty() - .jsonPath("_links.info.templated").isEqualTo(false).jsonPath("_links.env").doesNotExist() - .jsonPath("_links.test").doesNotExist().jsonPath("_links.test-part").doesNotExist()); + (client) -> client.get() + .uri("/cfApplication") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("_links.length()") + .isEqualTo(2) + .jsonPath("_links.self.href") + .isNotEmpty() + .jsonPath("_links.self.templated") + .isEqualTo(false) + .jsonPath("_links.info.href") + .isNotEmpty() + .jsonPath("_links.info.templated") + .isEqualTo(false) + .jsonPath("_links.env") + .doesNotExist() + .jsonPath("_links.test") + .doesNotExist() + .jsonPath("_links.test-part") + .doesNotExist()); } private AnnotationConfigServletWebServerApplicationContext createApplicationContext(Class... config) { @@ -147,8 +206,11 @@ class CloudFoundryMvcWebEndpointIntegrationTests { BiConsumer consumer = (context, client) -> clientConsumer.accept(client); try (AnnotationConfigServletWebServerApplicationContext context = createApplicationContext(configuration, CloudFoundryMvcConfiguration.class)) { - consumer.accept(context, WebTestClient.bindToServer().baseUrl("http://localhost:" + getPort(context)) - .responseTimeout(Duration.ofMinutes(5)).build()); + consumer.accept(context, + WebTestClient.bindToServer() + .baseUrl("http://localhost:" + getPort(context)) + .responseTimeout(Duration.ofMinutes(5)) + .build()); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java index de4953e216..f9e5d42810 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,8 +87,8 @@ class CloudFoundrySecurityServiceTests { void getAccessLevelWhenSpaceDeveloperShouldReturnFull() { String responseBody = "{\"read_sensitive_data\": true,\"read_basic_data\": true}"; this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) - .andExpect(header("Authorization", "bearer my-access-token")) - .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); + .andExpect(header("Authorization", "bearer my-access-token")) + .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); AccessLevel accessLevel = this.securityService.getAccessLevel("my-access-token", "my-app-id"); this.server.verify(); assertThat(accessLevel).isEqualTo(AccessLevel.FULL); @@ -98,8 +98,8 @@ class CloudFoundrySecurityServiceTests { void getAccessLevelWhenNotSpaceDeveloperShouldReturnRestricted() { String responseBody = "{\"read_sensitive_data\": false,\"read_basic_data\": true}"; this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) - .andExpect(header("Authorization", "bearer my-access-token")) - .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); + .andExpect(header("Authorization", "bearer my-access-token")) + .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); AccessLevel accessLevel = this.securityService.getAccessLevel("my-access-token", "my-app-id"); this.server.verify(); assertThat(accessLevel).isEqualTo(AccessLevel.RESTRICTED); @@ -108,35 +108,37 @@ class CloudFoundrySecurityServiceTests { @Test void getAccessLevelWhenTokenIsNotValidShouldThrowException() { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) - .andExpect(header("Authorization", "bearer my-access-token")).andRespond(withUnauthorizedRequest()); + .andExpect(header("Authorization", "bearer my-access-token")) + .andRespond(withUnauthorizedRequest()); assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) - .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); + .isThrownBy(() -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test void getAccessLevelWhenForbiddenShouldThrowException() { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) - .andExpect(header("Authorization", "bearer my-access-token")) - .andRespond(withStatus(HttpStatus.FORBIDDEN)); + .andExpect(header("Authorization", "bearer my-access-token")) + .andRespond(withStatus(HttpStatus.FORBIDDEN)); assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) - .satisfies(reasonRequirement(Reason.ACCESS_DENIED)); + .isThrownBy(() -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) + .satisfies(reasonRequirement(Reason.ACCESS_DENIED)); } @Test void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) - .andExpect(header("Authorization", "bearer my-access-token")).andRespond(withServerError()); + .andExpect(header("Authorization", "bearer my-access-token")) + .andRespond(withServerError()); assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) - .satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE)); + .isThrownBy(() -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) + .satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE)); } @Test void fetchTokenKeysWhenSuccessfulShouldReturnListOfKeysFromUAA() { this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) - .andRespond(withSuccess("{\"token_endpoint\":\"https://my-uaa.com\"}", MediaType.APPLICATION_JSON)); + .andRespond(withSuccess("{\"token_endpoint\":\"https://my-uaa.com\"}", MediaType.APPLICATION_JSON)); String tokenKeyValue = "-----BEGIN PUBLIC KEY-----\n" + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0m59l2u9iDnMbrXHfqkO\n" + "rn2dVQ3vfBJqcDuFUK03d+1PZGbVlNCqnkpIJ8syFppW8ljnWweP7+LiWpRoz0I7\n" @@ -148,7 +150,7 @@ class CloudFoundrySecurityServiceTests { String responseBody = "{\"keys\" : [ {\"kid\":\"test-key\",\"value\" : \"" + tokenKeyValue.replace("\n", "\\n") + "\"} ]}"; this.server.expect(requestTo(UAA_URL + "/token_keys")) - .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); + .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); Map tokenKeys = this.securityService.fetchTokenKeys(); this.server.verify(); assertThat(tokenKeys.get("test-key")).isEqualTo(tokenKeyValue); @@ -157,10 +159,10 @@ class CloudFoundrySecurityServiceTests { @Test void fetchTokenKeysWhenNoKeysReturnedFromUAA() { this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) - .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); + .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); String responseBody = "{\"keys\": []}"; this.server.expect(requestTo(UAA_URL + "/token_keys")) - .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); + .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); Map tokenKeys = this.securityService.fetchTokenKeys(); this.server.verify(); assertThat(tokenKeys).hasSize(0); @@ -169,17 +171,17 @@ class CloudFoundrySecurityServiceTests { @Test void fetchTokenKeysWhenUnsuccessfulShouldThrowException() { this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) - .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); + .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); this.server.expect(requestTo(UAA_URL + "/token_keys")).andRespond(withServerError()); assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> this.securityService.fetchTokenKeys()) - .satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE)); + .isThrownBy(() -> this.securityService.fetchTokenKeys()) + .satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE)); } @Test void getUaaUrlShouldCallCloudControllerInfoOnlyOnce() { this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) - .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); + .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); String uaaUrl = this.securityService.getUaaUrl(); this.server.verify(); assertThat(uaaUrl).isEqualTo(UAA_URL); @@ -192,8 +194,8 @@ class CloudFoundrySecurityServiceTests { void getUaaUrlWhenCloudControllerUrlIsNotReachableShouldThrowException() { this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")).andRespond(withServerError()); assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> this.securityService.getUaaUrl()) - .satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE)); + .isThrownBy(() -> this.securityService.getUaaUrl()) + .satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE)); } private Consumer reasonRequirement(Reason reason) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java index 7bd6619f4e..6d7f0cf019 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,8 +57,8 @@ class SkipSslVerificationHttpRequestFactoryTests { ResponseEntity responseEntity = restTemplate.getForEntity(httpsUrl, String.class); assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThatExceptionOfType(ResourceAccessException.class) - .isThrownBy(() -> otherRestTemplate.getForEntity(httpsUrl, String.class)) - .withCauseInstanceOf(SSLHandshakeException.class); + .isThrownBy(() -> otherRestTemplate.getForEntity(httpsUrl, String.class)) + .withCauseInstanceOf(SSLHandshakeException.class); } private String getHttpsUrl() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java index cf469ce897..2b50c2454f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -96,9 +96,10 @@ class TokenValidatorTests { given(this.securityService.fetchTokenKeys()).willReturn(INVALID_KEYS); String header = "{\"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( - () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .satisfies(reasonRequirement(Reason.INVALID_KEY_ID)); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy( + () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .satisfies(reasonRequirement(Reason.INVALID_KEY_ID)); } @Test @@ -138,18 +139,20 @@ class TokenValidatorTests { Collections.singletonMap("valid-key", INVALID_KEY)); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( - () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .satisfies(reasonRequirement(Reason.INVALID_SIGNATURE)); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy( + () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .satisfies(reasonRequirement(Reason.INVALID_SIGNATURE)); } @Test void validateTokenWhenTokenAlgorithmIsNotRS256ShouldThrowException() { String header = "{ \"alg\": \"HS256\", \"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( - () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .satisfies(reasonRequirement(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM)); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy( + () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .satisfies(reasonRequirement(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM)); } @Test @@ -158,9 +161,10 @@ class TokenValidatorTests { given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"jti\": \"0236399c350c47f3ae77e67a75e75e7d\", \"exp\": 1477509977, \"scope\": [\"actuator.read\"]}"; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( - () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .satisfies(reasonRequirement(Reason.TOKEN_EXPIRED)); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy( + () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .satisfies(reasonRequirement(Reason.TOKEN_EXPIRED)); } @Test @@ -169,9 +173,10 @@ class TokenValidatorTests { given(this.securityService.getUaaUrl()).willReturn("https://other-uaa.com"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\", \"scope\": [\"actuator.read\"]}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( - () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .satisfies(reasonRequirement(Reason.INVALID_ISSUER)); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy( + () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .satisfies(reasonRequirement(Reason.INVALID_ISSUER)); } @Test @@ -180,9 +185,10 @@ class TokenValidatorTests { given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"foo.bar\"]}"; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( - () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .satisfies(reasonRequirement(Reason.INVALID_AUDIENCE)); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy( + () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .satisfies(reasonRequirement(Reason.INVALID_AUDIENCE)); } private String getSignedToken(byte[] header, byte[] claims) throws Exception { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfigurationTests.java index df2e9fdc62..0685e50cac 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,12 +31,12 @@ import static org.assertj.core.api.Assertions.assertThat; class ConditionsReportEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ConditionsReportEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ConditionsReportEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=conditions") - .run((context) -> assertThat(context).hasSingleBean(ConditionsReportEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(ConditionsReportEndpoint.class)); } @Test @@ -47,7 +47,7 @@ class ConditionsReportEndpointAutoConfigurationTests { @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.conditions.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(ConditionsReportEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ConditionsReportEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointTests.java index 1002d79fec..f8d13da594 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,9 @@ class ConditionsReportEndpointTests { void invoke() { new ApplicationContextRunner().withUserConfiguration(Config.class).run((context) -> { ContextConditionEvaluation report = context.getBean(ConditionsReportEndpoint.class) - .applicationConditionEvaluation().getContexts().get(context.getId()); + .applicationConditionEvaluation() + .getContexts() + .get(context.getId()); assertThat(report.getPositiveMatches()).isEmpty(); assertThat(report.getNegativeMatches()).containsKey("a"); assertThat(report.getUnconditionalClasses()).contains("b"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfigurationTests.java index 2c6d14f4aa..1652a72dc8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,31 +36,32 @@ import static org.assertj.core.api.Assertions.assertThat; class ShutdownEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ShutdownEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ShutdownEndpointAutoConfiguration.class)); @Test @SuppressWarnings("unchecked") void runShouldHaveEndpointBeanThatIsNotDisposable() { this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:true") - .withPropertyValues("management.endpoints.web.exposure.include=shutdown").run((context) -> { - assertThat(context).hasSingleBean(ShutdownEndpoint.class); - ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - Map disposableBeans = (Map) ReflectionTestUtils - .getField(beanFactory, "disposableBeans"); - assertThat(disposableBeans).isEmpty(); - }); + .withPropertyValues("management.endpoints.web.exposure.include=shutdown") + .run((context) -> { + assertThat(context).hasSingleBean(ShutdownEndpoint.class); + ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); + Map disposableBeans = (Map) ReflectionTestUtils.getField(beanFactory, + "disposableBeans"); + assertThat(disposableBeans).isEmpty(); + }); } @Test void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:true") - .run((context) -> assertThat(context).doesNotHaveBean(ShutdownEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ShutdownEndpoint.class)); } @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(ShutdownEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ShutdownEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/properties/ConfigurationPropertiesReportEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/properties/ConfigurationPropertiesReportEndpointAutoConfigurationTests.java index 035abffdea..9f3c8984b3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/properties/ConfigurationPropertiesReportEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/properties/ConfigurationPropertiesReportEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,49 +44,48 @@ import static org.assertj.core.api.Assertions.assertThat; class ConfigurationPropertiesReportEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ConfigurationPropertiesReportEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ConfigurationPropertiesReportEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withUserConfiguration(Config.class) - .withPropertyValues("management.endpoints.web.exposure.include=configprops") - .run(validateTestProperties("******", "654321")); + .withPropertyValues("management.endpoints.web.exposure.include=configprops") + .run(validateTestProperties("******", "654321")); } @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.configprops.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(ConfigurationPropertiesReportEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ConfigurationPropertiesReportEndpoint.class)); } @Test void keysToSanitizeCanBeConfiguredViaTheEnvironment() { this.contextRunner.withUserConfiguration(Config.class) - .withPropertyValues("management.endpoint.configprops.keys-to-sanitize: .*pass.*, property") - .withPropertyValues("management.endpoints.web.exposure.include=configprops") - .run(validateTestProperties("******", "******")); + .withPropertyValues("management.endpoint.configprops.keys-to-sanitize: .*pass.*, property") + .withPropertyValues("management.endpoints.web.exposure.include=configprops") + .run(validateTestProperties("******", "******")); } @Test void additionalKeysToSanitizeCanBeConfiguredViaTheEnvironment() { this.contextRunner.withUserConfiguration(Config.class) - .withPropertyValues("management.endpoint.configprops.additional-keys-to-sanitize: property") - .withPropertyValues("management.endpoints.web.exposure.include=configprops") - .run(validateTestProperties("******", "******")); + .withPropertyValues("management.endpoint.configprops.additional-keys-to-sanitize: property") + .withPropertyValues("management.endpoints.web.exposure.include=configprops") + .run(validateTestProperties("******", "******")); } @Test void customSanitizingFunctionsAreAppliedInOrder() { this.contextRunner.withUserConfiguration(Config.class, SanitizingFunctionConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=configprops", - "test.my-test-property=abc") - .run(validateTestProperties("$$$111$$$", "$$$222$$$")); + .withPropertyValues("management.endpoints.web.exposure.include=configprops", "test.my-test-property=abc") + .run(validateTestProperties("$$$111$$$", "$$$222$$$")); } @Test void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(ConfigurationPropertiesReportEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ConfigurationPropertiesReportEndpoint.class)); } private ContextConsumer validateTestProperties(String dbPassword, @@ -94,10 +93,13 @@ class ConfigurationPropertiesReportEndpointAutoConfigurationTests { return (context) -> { assertThat(context).hasSingleBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ApplicationConfigurationProperties properties = endpoint.configurationProperties(); - Map nestedProperties = properties.getContexts().get(context.getId()).getBeans() - .get("testProperties").getProperties(); + Map nestedProperties = properties.getContexts() + .get(context.getId()) + .getBeans() + .get("testProperties") + .getProperties(); assertThat(nestedProperties).isNotNull(); assertThat(nestedProperties.get("dbPassword")).isEqualTo(dbPassword); assertThat(nestedProperties.get("myTestProperty")).isEqualTo(myTestProperty); @@ -107,10 +109,10 @@ class ConfigurationPropertiesReportEndpointAutoConfigurationTests { @Test void runWhenOnlyExposedOverJmxShouldHaveEndpointBeanWithoutWebExtension() { this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=info", "spring.jmx.enabled=true", - "management.endpoints.jmx.exposure.include=configprops") - .run((context) -> assertThat(context).hasSingleBean(ConfigurationPropertiesReportEndpoint.class) - .doesNotHaveBean(ConfigurationPropertiesReportEndpointWebExtension.class)); + .withPropertyValues("management.endpoints.web.exposure.include=info", "spring.jmx.enabled=true", + "management.endpoints.jmx.exposure.include=configprops") + .run((context) -> assertThat(context).hasSingleBean(ConfigurationPropertiesReportEndpoint.class) + .doesNotHaveBean(ConfigurationPropertiesReportEndpointWebExtension.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseHealthContributorAutoConfigurationTests.java index 4d8860877e..6e171325da 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,19 +37,20 @@ import static org.mockito.Mockito.mock; class CouchbaseHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withBean(Cluster.class, () -> mock(Cluster.class)).withConfiguration(AutoConfigurations - .of(CouchbaseHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withBean(Cluster.class, () -> mock(Cluster.class)) + .withConfiguration(AutoConfigurations.of(CouchbaseHealthContributorAutoConfiguration.class, + HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CouchbaseHealthIndicator.class) - .doesNotHaveBean(CouchbaseReactiveHealthIndicator.class)); + .doesNotHaveBean(CouchbaseReactiveHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.couchbase.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(CouchbaseHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CouchbaseHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthContributorAutoConfigurationTests.java index d4474a9bd6..a99dfa423d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,28 +36,29 @@ import static org.mockito.Mockito.mock; class CouchbaseReactiveHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withBean(Cluster.class, () -> mock(Cluster.class)) - .withConfiguration(AutoConfigurations.of(CouchbaseReactiveHealthContributorAutoConfiguration.class, - HealthContributorAutoConfiguration.class)); + .withBean(Cluster.class, () -> mock(Cluster.class)) + .withConfiguration(AutoConfigurations.of(CouchbaseReactiveHealthContributorAutoConfiguration.class, + HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CouchbaseReactiveHealthIndicator.class) - .hasBean("couchbaseHealthContributor")); + .hasBean("couchbaseHealthContributor")); } @Test void runWithRegularIndicatorShouldOnlyCreateReactiveIndicator() { this.contextRunner.withConfiguration(AutoConfigurations.of(CouchbaseHealthContributorAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(CouchbaseReactiveHealthIndicator.class) - .hasBean("couchbaseHealthContributor").doesNotHaveBean(CouchbaseHealthIndicator.class)); + .run((context) -> assertThat(context).hasSingleBean(CouchbaseReactiveHealthIndicator.class) + .hasBean("couchbaseHealthContributor") + .doesNotHaveBean(CouchbaseHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.couchbase.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(CouchbaseReactiveHealthIndicator.class) - .doesNotHaveBean("couchbaseHealthContributor")); + .run((context) -> assertThat(context).doesNotHaveBean(CouchbaseReactiveHealthIndicator.class) + .doesNotHaveBean("couchbaseHealthContributor")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchRestHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchRestHealthContributorAutoConfigurationTests.java index 5c1f4d9aa4..fd5c025b05 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchRestHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchRestHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,45 +40,45 @@ import static org.assertj.core.api.Assertions.assertThat; class ElasticSearchRestHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class, - ElasticSearchRestHealthContributorAutoConfiguration.class, - HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class, + ElasticSearchRestHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(ElasticsearchRestClientHealthIndicator.class).hasBean("elasticsearchHealthContributor")); + this.contextRunner + .run((context) -> assertThat(context).hasSingleBean(ElasticsearchRestClientHealthIndicator.class) + .hasBean("elasticsearchHealthContributor")); } @Test @SuppressWarnings("deprecation") void runWithoutRestHighLevelClientAndWithoutRestClientShouldNotCreateIndicator() { this.contextRunner - .withClassLoader( - new FilteredClassLoader(org.elasticsearch.client.RestHighLevelClient.class, RestClient.class)) - .run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchRestClientHealthIndicator.class) - .doesNotHaveBean("elasticsearchHealthContributor")); + .withClassLoader( + new FilteredClassLoader(org.elasticsearch.client.RestHighLevelClient.class, RestClient.class)) + .run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchRestClientHealthIndicator.class) + .doesNotHaveBean("elasticsearchHealthContributor")); } @Test void runWithoutRestHighLevelClientAndWithRestClientShouldCreateIndicator() { this.contextRunner.withUserConfiguration(CustomRestClientConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ElasticsearchRestClientHealthIndicator.class) - .hasBean("elasticsearchHealthContributor")); + .run((context) -> assertThat(context).hasSingleBean(ElasticsearchRestClientHealthIndicator.class) + .hasBean("elasticsearchHealthContributor")); } @Test void runWithRestHighLevelClientAndWithRestClientShouldCreateIndicator() { this.contextRunner.withUserConfiguration(CustomRestHighClientConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ElasticsearchRestClientHealthIndicator.class) - .hasBean("elasticsearchHealthContributor")); + .run((context) -> assertThat(context).hasSingleBean(ElasticsearchRestClientHealthIndicator.class) + .hasBean("elasticsearchHealthContributor")); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.elasticsearch.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchRestClientHealthIndicator.class) - .doesNotHaveBean("elasticsearchHealthContributor")); + .run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchRestClientHealthIndicator.class) + .doesNotHaveBean("elasticsearchHealthContributor")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchReactiveHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchReactiveHealthContributorAutoConfigurationTests.java index 7cf3bce2fc..4be2941ef4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchReactiveHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchReactiveHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,32 +37,32 @@ import static org.assertj.core.api.Assertions.assertThat; class ElasticsearchReactiveHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticsearchDataAutoConfiguration.class, - ReactiveElasticsearchRestClientAutoConfiguration.class, - ElasticsearchRestClientAutoConfiguration.class, - ElasticSearchReactiveHealthContributorAutoConfiguration.class, - HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ElasticsearchDataAutoConfiguration.class, + ReactiveElasticsearchRestClientAutoConfiguration.class, ElasticsearchRestClientAutoConfiguration.class, + ElasticSearchReactiveHealthContributorAutoConfiguration.class, + HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(ElasticsearchReactiveHealthIndicator.class).hasBean("elasticsearchHealthContributor")); + this.contextRunner + .run((context) -> assertThat(context).hasSingleBean(ElasticsearchReactiveHealthIndicator.class) + .hasBean("elasticsearchHealthContributor")); } @Test void runWithRegularIndicatorShouldOnlyCreateReactiveIndicator() { this.contextRunner - .withConfiguration(AutoConfigurations.of(ElasticSearchRestHealthContributorAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(ElasticsearchReactiveHealthIndicator.class) - .hasBean("elasticsearchHealthContributor") - .doesNotHaveBean(ElasticsearchRestClientHealthIndicator.class)); + .withConfiguration(AutoConfigurations.of(ElasticSearchRestHealthContributorAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(ElasticsearchReactiveHealthIndicator.class) + .hasBean("elasticsearchHealthContributor") + .doesNotHaveBean(ElasticsearchRestClientHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.elasticsearch.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchReactiveHealthIndicator.class) - .doesNotHaveBean("elasticsearchHealthContributor")); + .run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchReactiveHealthIndicator.class) + .doesNotHaveBean("elasticsearchHealthContributor")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfigurationTests.java index f4262b605a..4d1e4c6a4a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfigurationTests.java @@ -47,7 +47,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class EndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(EndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(EndpointAutoConfiguration.class)); @Test void mapShouldUseConfigurationConverter() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java index a0c61d295f..c19c434dae 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,172 +37,219 @@ import static org.assertj.core.api.Assertions.assertThat; class ConditionalOnAvailableEndpointTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(AllEndpointsConfiguration.class); + .withUserConfiguration(AllEndpointsConfiguration.class); @Test void outcomeShouldMatchDefaults() { - this.contextRunner.run((context) -> assertThat(context).hasBean("health").doesNotHaveBean("spring") - .doesNotHaveBean("test").doesNotHaveBean("shutdown")); + this.contextRunner.run((context) -> assertThat(context).hasBean("health") + .doesNotHaveBean("spring") + .doesNotHaveBean("test") + .doesNotHaveBean("shutdown")); } @Test void outcomeWithEnabledByDefaultSetToFalseShouldNotMatchAnything() { this.contextRunner.withPropertyValues("management.endpoints.enabled-by-default=false") - .run((context) -> assertThat(context).doesNotHaveBean("info").doesNotHaveBean("health") - .doesNotHaveBean("spring").doesNotHaveBean("test").doesNotHaveBean("shutdown")); + .run((context) -> assertThat(context).doesNotHaveBean("info") + .doesNotHaveBean("health") + .doesNotHaveBean("spring") + .doesNotHaveBean("test") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeAllWebShouldMatchEnabledEndpoints() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=*") - .run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("test") - .hasBean("spring").doesNotHaveBean("shutdown")); + .run((context) -> assertThat(context).hasBean("info") + .hasBean("health") + .hasBean("test") + .hasBean("spring") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeAllWebAndDisablingEndpointShouldMatchEnabledEndpoints() { this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=*", - "management.endpoint.test.enabled=false", "management.endpoint.health.enabled=false") - .run((context) -> assertThat(context).hasBean("info").doesNotHaveBean("health").doesNotHaveBean("test") - .hasBean("spring").doesNotHaveBean("shutdown")); + .withPropertyValues("management.endpoints.web.exposure.include=*", "management.endpoint.test.enabled=false", + "management.endpoint.health.enabled=false") + .run((context) -> assertThat(context).hasBean("info") + .doesNotHaveBean("health") + .doesNotHaveBean("test") + .hasBean("spring") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeAllWebAndEnablingEndpointDisabledByDefaultShouldMatchAll() { this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=*", - "management.endpoint.shutdown.enabled=true") - .run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("test") - .hasBean("spring").hasBean("shutdown")); + .withPropertyValues("management.endpoints.web.exposure.include=*", + "management.endpoint.shutdown.enabled=true") + .run((context) -> assertThat(context).hasBean("info") + .hasBean("health") + .hasBean("test") + .hasBean("spring") + .hasBean("shutdown")); } @Test void outcomeWhenIncludeAllJmxButJmxDisabledShouldMatchDefaults() { this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.include=*") - .run((context) -> assertThat(context).hasBean("health").doesNotHaveBean("spring") - .doesNotHaveBean("test").doesNotHaveBean("shutdown")); + .run((context) -> assertThat(context).hasBean("health") + .doesNotHaveBean("spring") + .doesNotHaveBean("test") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeAllJmxAndJmxEnabledShouldMatchEnabledEndpoints() { this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.include=*", "spring.jmx.enabled=true") - .run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("test") - .hasBean("spring").doesNotHaveBean("shutdown")); + .run((context) -> assertThat(context).hasBean("info") + .hasBean("health") + .hasBean("test") + .hasBean("spring") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeAllJmxAndJmxEnabledAndEnablingEndpointDisabledByDefaultShouldMatchAll() { this.contextRunner - .withPropertyValues("management.endpoints.jmx.exposure.include=*", "spring.jmx.enabled=true", - "management.endpoint.shutdown.enabled=true") - .run((context) -> assertThat(context).hasBean("health").hasBean("test").hasBean("spring") - .hasBean("shutdown")); + .withPropertyValues("management.endpoints.jmx.exposure.include=*", "spring.jmx.enabled=true", + "management.endpoint.shutdown.enabled=true") + .run((context) -> assertThat(context).hasBean("health") + .hasBean("test") + .hasBean("spring") + .hasBean("shutdown")); } @Test void outcomeWhenIncludeAllWebAndExcludeMatchesShouldNotMatch() { this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=*", - "management.endpoints.web.exposure.exclude=spring,info") - .run((context) -> assertThat(context).hasBean("health").hasBean("test").doesNotHaveBean("info") - .doesNotHaveBean("spring").doesNotHaveBean("shutdown")); + .withPropertyValues("management.endpoints.web.exposure.include=*", + "management.endpoints.web.exposure.exclude=spring,info") + .run((context) -> assertThat(context).hasBean("health") + .hasBean("test") + .doesNotHaveBean("info") + .doesNotHaveBean("spring") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeMatchesAndExcludeMatchesShouldNotMatch() { this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=info,health,spring,test", - "management.endpoints.web.exposure.exclude=spring,info") - .run((context) -> assertThat(context).hasBean("health").hasBean("test").doesNotHaveBean("info") - .doesNotHaveBean("spring").doesNotHaveBean("shutdown")); + .withPropertyValues("management.endpoints.web.exposure.include=info,health,spring,test", + "management.endpoints.web.exposure.exclude=spring,info") + .run((context) -> assertThat(context).hasBean("health") + .hasBean("test") + .doesNotHaveBean("info") + .doesNotHaveBean("spring") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeMatchesShouldMatchEnabledEndpoints() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=spring") - .run((context) -> assertThat(context).hasBean("spring").doesNotHaveBean("health") - .doesNotHaveBean("info").doesNotHaveBean("test").doesNotHaveBean("shutdown")); + .run((context) -> assertThat(context).hasBean("spring") + .doesNotHaveBean("health") + .doesNotHaveBean("info") + .doesNotHaveBean("test") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeMatchOnDisabledEndpointShouldNotMatch() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=shutdown") - .run((context) -> assertThat(context).doesNotHaveBean("spring").doesNotHaveBean("health") - .doesNotHaveBean("info").doesNotHaveBean("test").doesNotHaveBean("shutdown")); + .run((context) -> assertThat(context).doesNotHaveBean("spring") + .doesNotHaveBean("health") + .doesNotHaveBean("info") + .doesNotHaveBean("test") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeMatchOnEnabledEndpointShouldNotMatch() { this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=shutdown", - "management.endpoint.shutdown.enabled=true") - .run((context) -> assertThat(context).doesNotHaveBean("spring").doesNotHaveBean("health") - .doesNotHaveBean("info").doesNotHaveBean("test").hasBean("shutdown")); + .withPropertyValues("management.endpoints.web.exposure.include=shutdown", + "management.endpoint.shutdown.enabled=true") + .run((context) -> assertThat(context).doesNotHaveBean("spring") + .doesNotHaveBean("health") + .doesNotHaveBean("info") + .doesNotHaveBean("test") + .hasBean("shutdown")); } @Test void outcomeWhenIncludeMatchesWithCaseShouldMatch() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=sPRing") - .run((context) -> assertThat(context).hasBean("spring").doesNotHaveBean("health") - .doesNotHaveBean("info").doesNotHaveBean("test").doesNotHaveBean("shutdown")); + .run((context) -> assertThat(context).hasBean("spring") + .doesNotHaveBean("health") + .doesNotHaveBean("info") + .doesNotHaveBean("test") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeMatchesAndExcludeAllShouldNotMatch() { this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=info,health,spring,test", - "management.endpoints.web.exposure.exclude=*") - .run((context) -> assertThat(context).doesNotHaveBean("health").doesNotHaveBean("info") - .doesNotHaveBean("spring").doesNotHaveBean("test").doesNotHaveBean("shutdown")); + .withPropertyValues("management.endpoints.web.exposure.include=info,health,spring,test", + "management.endpoints.web.exposure.exclude=*") + .run((context) -> assertThat(context).doesNotHaveBean("health") + .doesNotHaveBean("info") + .doesNotHaveBean("spring") + .doesNotHaveBean("test") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeMatchesShouldMatchWithExtensionsAndComponents() { this.contextRunner.withUserConfiguration(ComponentEnabledIfEndpointIsExposedConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=spring") - .run((context) -> assertThat(context).hasBean("spring").hasBean("springComponent") - .hasBean("springExtension").doesNotHaveBean("info").doesNotHaveBean("health") - .doesNotHaveBean("test").doesNotHaveBean("shutdown")); + .withPropertyValues("management.endpoints.web.exposure.include=spring") + .run((context) -> assertThat(context).hasBean("spring") + .hasBean("springComponent") + .hasBean("springExtension") + .doesNotHaveBean("info") + .doesNotHaveBean("health") + .doesNotHaveBean("test") + .doesNotHaveBean("shutdown")); } @Test void outcomeWithNoEndpointReferenceShouldFail() { this.contextRunner.withUserConfiguration(ComponentWithNoEndpointReferenceConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=*").run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure().getCause().getMessage()) - .contains("No endpoint is specified and the return type of the @Bean method " - + "is neither an @Endpoint, nor an @EndpointExtension"); - }); + .withPropertyValues("management.endpoints.web.exposure.include=*") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure().getCause().getMessage()) + .contains("No endpoint is specified and the return type of the @Bean method " + + "is neither an @Endpoint, nor an @EndpointExtension"); + }); } @Test void outcomeOnCloudFoundryShouldMatchAll() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---").run( - (context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("spring").hasBean("test")); + this.contextRunner.withPropertyValues("VCAP_APPLICATION:---") + .run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("spring").hasBean("test")); } @Test // gh-21044 void outcomeWhenIncludeAllShouldMatchDashedEndpoint() { this.contextRunner.withUserConfiguration(DashedEndpointConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=*") - .run((context) -> assertThat(context).hasSingleBean(DashedEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=*") + .run((context) -> assertThat(context).hasSingleBean(DashedEndpoint.class)); } @Test // gh-21044 void outcomeWhenIncludeDashedShouldMatchDashedEndpoint() { this.contextRunner.withUserConfiguration(DashedEndpointConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=test-dashed") - .run((context) -> assertThat(context).hasSingleBean(DashedEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=test-dashed") + .run((context) -> assertThat(context).hasSingleBean(DashedEndpoint.class)); } @Test void outcomeWhenEndpointNotExposedOnSpecifiedTechnology() { this.contextRunner.withUserConfiguration(ExposureEndpointConfiguration.class) - .withPropertyValues("spring.jmx.enabled=true", "management.endpoints.jmx.exposure.include=test", - "management.endpoints.web.exposure.exclude=test") - .run((context) -> assertThat(context).doesNotHaveBean("unexposed")); + .withPropertyValues("spring.jmx.enabled=true", "management.endpoints.jmx.exposure.include=test", + "management.endpoints.web.exposure.exclude=test") + .run((context) -> assertThat(context).doesNotHaveBean("unexposed")); } @Endpoint(id = "health") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilterTests.java index aefe8aae5a..75737180e4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,31 +44,29 @@ class IncludeExcludeEndpointFilterTests { @Test void createWhenEndpointTypeIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new IncludeExcludeEndpointFilter<>(null, new MockEnvironment(), "foo")) - .withMessageContaining("EndpointType must not be null"); + .isThrownBy(() -> new IncludeExcludeEndpointFilter<>(null, new MockEnvironment(), "foo")) + .withMessageContaining("EndpointType must not be null"); } @Test void createWhenEnvironmentIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new IncludeExcludeEndpointFilter<>(ExposableEndpoint.class, null, "foo")) - .withMessageContaining("Environment must not be null"); + .isThrownBy(() -> new IncludeExcludeEndpointFilter<>(ExposableEndpoint.class, null, "foo")) + .withMessageContaining("Environment must not be null"); } @Test void createWhenPrefixIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> new IncludeExcludeEndpointFilter<>(ExposableEndpoint.class, new MockEnvironment(), null)) - .withMessageContaining("Prefix must not be empty"); + .isThrownBy(() -> new IncludeExcludeEndpointFilter<>(ExposableEndpoint.class, new MockEnvironment(), null)) + .withMessageContaining("Prefix must not be empty"); } @Test void createWhenPrefixIsEmptyShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> new IncludeExcludeEndpointFilter<>(ExposableEndpoint.class, new MockEnvironment(), "")) - .withMessageContaining("Prefix must not be empty"); + .isThrownBy(() -> new IncludeExcludeEndpointFilter<>(ExposableEndpoint.class, new MockEnvironment(), "")) + .withMessageContaining("Prefix must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java index 45c1804058..d6684db8a3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -94,17 +94,18 @@ class DefaultEndpointObjectNameFactoryTests { void generateObjectNameWithDuplicate() throws MalformedObjectNameException { this.contextId = "testContext"; given(this.mBeanServer.queryNames(new ObjectName("org.springframework.boot:type=Endpoint,name=Test,*"), null)) - .willReturn(Collections.singleton(new ObjectName("org.springframework.boot:type=Endpoint,name=Test"))); + .willReturn(Collections.singleton(new ObjectName("org.springframework.boot:type=Endpoint,name=Test"))); ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test"))); assertThat(objectName.toString()) - .isEqualTo("org.springframework.boot:type=Endpoint,name=Test,context=testContext"); + .isEqualTo("org.springframework.boot:type=Endpoint,name=Test,context=testContext"); } private ObjectName generateObjectName(ExposableJmxEndpoint endpoint) { try { return new DefaultEndpointObjectNameFactory(this.properties, this.jmxProperties, this.mBeanServer, - this.contextId).getObjectName(endpoint); + this.contextId) + .getObjectName(endpoint); } catch (MalformedObjectNameException ex) { throw new AssertionError("Invalid object name", ex); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/JmxEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/JmxEndpointAutoConfigurationTests.java index 7c077dd36e..ce4fd3dad2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/JmxEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/JmxEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,45 +58,49 @@ class JmxEndpointAutoConfigurationTests { }; private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(EndpointAutoConfiguration.class, JmxAutoConfiguration.class, - JmxEndpointAutoConfiguration.class)) - .withUserConfiguration(TestEndpoint.class); + .withConfiguration(AutoConfigurations.of(EndpointAutoConfiguration.class, JmxAutoConfiguration.class, + JmxEndpointAutoConfiguration.class)) + .withUserConfiguration(TestEndpoint.class); private final MBeanServer mBeanServer = mock(MBeanServer.class); @Test void jmxEndpointWithoutJmxSupportNotAutoConfigured() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(MBeanServer.class) - .doesNotHaveBean(JmxEndpointDiscoverer.class).doesNotHaveBean(JmxEndpointExporter.class)); + .doesNotHaveBean(JmxEndpointDiscoverer.class) + .doesNotHaveBean(JmxEndpointExporter.class)); } @Test void jmxEndpointWithJmxSupportAutoConfigured() { - this.contextRunner.withPropertyValues("spring.jmx.enabled=true").with(mockMBeanServer()) - .run((context) -> assertThat(context).hasSingleBean(JmxEndpointDiscoverer.class) - .hasSingleBean(JmxEndpointExporter.class)); + this.contextRunner.withPropertyValues("spring.jmx.enabled=true") + .with(mockMBeanServer()) + .run((context) -> assertThat(context).hasSingleBean(JmxEndpointDiscoverer.class) + .hasSingleBean(JmxEndpointExporter.class)); } @Test void jmxEndpointWithCustomEndpointObjectNameFactory() { EndpointObjectNameFactory factory = mock(EndpointObjectNameFactory.class); - this.contextRunner.withPropertyValues("spring.jmx.enabled=true").with(mockMBeanServer()) - .withBean(EndpointObjectNameFactory.class, () -> factory).run((context) -> { - ArgumentCaptor argumentCaptor = ArgumentCaptor - .forClass(ExposableJmxEndpoint.class); - then(factory).should().getObjectName(argumentCaptor.capture()); - ExposableJmxEndpoint jmxEndpoint = argumentCaptor.getValue(); - assertThat(jmxEndpoint.getEndpointId().toLowerCaseString()).isEqualTo("test"); - }); + this.contextRunner.withPropertyValues("spring.jmx.enabled=true") + .with(mockMBeanServer()) + .withBean(EndpointObjectNameFactory.class, () -> factory) + .run((context) -> { + ArgumentCaptor argumentCaptor = ArgumentCaptor + .forClass(ExposableJmxEndpoint.class); + then(factory).should().getObjectName(argumentCaptor.capture()); + ExposableJmxEndpoint jmxEndpoint = argumentCaptor.getValue(); + assertThat(jmxEndpoint.getEndpointId().toLowerCaseString()).isEqualTo("test"); + }); } @Test void jmxEndpointWithContextHierarchyGeneratesUniqueNamesForEachEndpoint() throws Exception { given(this.mBeanServer.queryNames(any(), any())) - .willReturn(new HashSet<>(Arrays.asList(new ObjectName("test:test=test")))); + .willReturn(new HashSet<>(Arrays.asList(new ObjectName("test:test=test")))); ArgumentCaptor objectName = ArgumentCaptor.forClass(ObjectName.class); ApplicationContextRunner jmxEnabledContextRunner = this.contextRunner - .withPropertyValues("spring.jmx.enabled=true"); + .withPropertyValues("spring.jmx.enabled=true"); jmxEnabledContextRunner.with(mockMBeanServer()).run((parent) -> { jmxEnabledContextRunner.withParent(parent).run(NO_OPERATION); jmxEnabledContextRunner.withParent(parent).run(NO_OPERATION); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapperTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapperTests.java index 32b7541323..577c7fbb2d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapperTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,14 +43,14 @@ class MappingWebEndpointPathMapperTests { MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper( Collections.singletonMap("test", "custom")); assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("test"))) - .isEqualTo("custom"); + .isEqualTo("custom"); } @Test void mixedCaseDefaultConfiguration() { MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper(Collections.emptyMap()); assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("testEndpoint"))) - .isEqualTo("testEndpoint"); + .isEqualTo("testEndpoint"); } @Test @@ -58,7 +58,7 @@ class MappingWebEndpointPathMapperTests { MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper( Collections.singletonMap("test-endpoint", "custom")); assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("testEndpoint"))) - .isEqualTo("custom"); + .isEqualTo("custom"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfigurationTests.java index 8c914672c0..0df0cf10d0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ServletEndpointManagementContextConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withUserConfiguration(TestConfig.class); + .withUserConfiguration(TestConfig.class); @Test void contextShouldContainServletEndpointRegistrar() { @@ -70,7 +70,7 @@ class ServletEndpointManagementContextConfigurationTests { @Test void contextWhenNoServletBasedShouldNotContainServletEndpointRegistrar() { new ApplicationContextRunner().withUserConfiguration(TestConfig.class) - .run((context) -> assertThat(context).doesNotHaveBean(ServletEndpointRegistrar.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ServletEndpointRegistrar.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfigurationTests.java index 38a7042054..b32f165909 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,7 +59,7 @@ class WebEndpointAutoConfigurationTests { WebEndpointAutoConfiguration.class); private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(CONFIGURATIONS); + .withConfiguration(CONFIGURATIONS); @Test void webApplicationConfiguresEndpointMediaTypes() { @@ -72,28 +72,29 @@ class WebEndpointAutoConfigurationTests { @Test void webApplicationConfiguresPathMapper() { this.contextRunner.withPropertyValues("management.endpoints.web.path-mapping.health=healthcheck") - .run((context) -> { - assertThat(context).hasSingleBean(PathMapper.class); - String pathMapping = context.getBean(PathMapper.class).getRootPath(EndpointId.of("health")); - assertThat(pathMapping).isEqualTo("healthcheck"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(PathMapper.class); + String pathMapping = context.getBean(PathMapper.class).getRootPath(EndpointId.of("health")); + assertThat(pathMapping).isEqualTo("healthcheck"); + }); } @Test void webApplicationSupportCustomPathMatcher() { this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=*", - "management.endpoints.web.path-mapping.testanotherone=foo") - .withUserConfiguration(TestPathMatcher.class, TestOneEndpoint.class, TestAnotherOneEndpoint.class, - TestTwoEndpoint.class) - .run((context) -> { - WebEndpointDiscoverer discoverer = context.getBean(WebEndpointDiscoverer.class); - Collection endpoints = discoverer.getEndpoints(); - ExposableWebEndpoint[] webEndpoints = endpoints.toArray(new ExposableWebEndpoint[0]); - List paths = Arrays.stream(webEndpoints).map(PathMappedEndpoint::getRootPath) - .collect(Collectors.toList()); - assertThat(paths).containsOnly("1/testone", "foo", "testtwo"); - }); + .withPropertyValues("management.endpoints.web.exposure.include=*", + "management.endpoints.web.path-mapping.testanotherone=foo") + .withUserConfiguration(TestPathMatcher.class, TestOneEndpoint.class, TestAnotherOneEndpoint.class, + TestTwoEndpoint.class) + .run((context) -> { + WebEndpointDiscoverer discoverer = context.getBean(WebEndpointDiscoverer.class); + Collection endpoints = discoverer.getEndpoints(); + ExposableWebEndpoint[] webEndpoints = endpoints.toArray(new ExposableWebEndpoint[0]); + List paths = Arrays.stream(webEndpoints) + .map(PathMappedEndpoint::getRootPath) + .collect(Collectors.toList()); + assertThat(paths).containsOnly("1/testone", "foo", "testtwo"); + }); } @Test @@ -106,9 +107,8 @@ class WebEndpointAutoConfigurationTests { @Test void webApplicationConfiguresExposeExcludePropertyEndpointFilter() { - this.contextRunner - .run((context) -> assertThat(context).getBeans(IncludeExcludeEndpointFilter.class).containsKeys( - "webExposeExcludePropertyEndpointFilter", "controllerExposeExcludePropertyEndpointFilter")); + this.contextRunner.run((context) -> assertThat(context).getBeans(IncludeExcludeEndpointFilter.class) + .containsKeys("webExposeExcludePropertyEndpointFilter", "controllerExposeExcludePropertyEndpointFilter")); } @Test @@ -119,7 +119,7 @@ class WebEndpointAutoConfigurationTests { @Test void contextWhenNotServletShouldNotConfigureServletEndpointDiscoverer() { new ApplicationContextRunner().withConfiguration(CONFIGURATIONS) - .run((context) -> assertThat(context).doesNotHaveBean(ServletEndpointDiscoverer.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ServletEndpointDiscoverer.class)); } @Component diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java index d1d55d2901..34061845b9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ class WebEndpointPropertiesTests { void basePathMustStartWithSlash() { WebEndpointProperties properties = new WebEndpointProperties(); assertThatIllegalArgumentException().isThrownBy(() -> properties.setBasePath("admin")) - .withMessageContaining("Base path must start with '/' or be empty"); + .withMessageContaining("Base path must start with '/' or be empty"); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AbstractEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AbstractEndpointDocumentationTests.java index 8ab7f40e92..3d68a26866 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AbstractEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AbstractEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,7 +61,8 @@ public abstract class AbstractEndpointDocumentationTests { protected static String describeEnumValues(Class> enumType) { return StringUtils.collectionToDelimitedString(Stream.of(enumType.getEnumConstants()) - .map((constant) -> "`" + constant.name() + "`").collect(Collectors.toList()), ", "); + .map((constant) -> "`" + constant.name() + "`") + .collect(Collectors.toList()), ", "); } protected OperationPreprocessor limit(String... keys) { @@ -99,21 +100,27 @@ public abstract class AbstractEndpointDocumentationTests { protected FieldDescriptor parentIdField() { return fieldWithPath("contexts.*.parentId").description("Id of the parent application context, if any.") - .optional().type(JsonFieldType.STRING); + .optional() + .type(JsonFieldType.STRING); } @SuppressWarnings("unchecked") private Map select(Map candidates, Predicate filter) { Map selected = new HashMap<>(); - candidates.entrySet().stream().filter((candidate) -> filter.test((T) candidate)).limit(3) - .forEach((entry) -> selected.put(entry.getKey(), entry.getValue())); + candidates.entrySet() + .stream() + .filter((candidate) -> filter.test((T) candidate)) + .limit(3) + .forEach((entry) -> selected.put(entry.getKey(), entry.getValue())); return selected; } @SuppressWarnings("unchecked") private List select(List candidates, Predicate filter) { - return candidates.stream().filter((candidate) -> filter.test((T) candidate)).limit(3) - .collect(Collectors.toList()); + return candidates.stream() + .filter((candidate) -> filter.test((T) candidate)) + .limit(3) + .collect(Collectors.toList()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AuditEventsEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AuditEventsEndpointDocumentationTests.java index d5c18d1735..ef50064371 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AuditEventsEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AuditEventsEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,13 +56,15 @@ class AuditEventsEndpointDocumentationTests extends MockMvcEndpointDocumentation void allAuditEvents() throws Exception { String queryTimestamp = "2017-11-07T09:37Z"; given(this.repository.find(any(), any(), any())) - .willReturn(Arrays.asList(new AuditEvent("alice", "logout", Collections.emptyMap()))); - this.mockMvc.perform(get("/actuator/auditevents").param("after", queryTimestamp)).andExpect(status().isOk()) - .andDo(document("auditevents/all", responseFields( - fieldWithPath("events").description("An array of audit events."), - fieldWithPath("events.[].timestamp").description("The timestamp of when the event occurred."), - fieldWithPath("events.[].principal").description("The principal that triggered the event."), - fieldWithPath("events.[].type").description("The type of the event.")))); + .willReturn(Arrays.asList(new AuditEvent("alice", "logout", Collections.emptyMap()))); + this.mockMvc.perform(get("/actuator/auditevents").param("after", queryTimestamp)) + .andExpect(status().isOk()) + .andDo(document("auditevents/all", + responseFields(fieldWithPath("events").description("An array of audit events."), + fieldWithPath("events.[].timestamp") + .description("The timestamp of when the event occurred."), + fieldWithPath("events.[].principal").description("The principal that triggered the event."), + fieldWithPath("events.[].type").description("The type of the event.")))); } @Test @@ -70,19 +72,20 @@ class AuditEventsEndpointDocumentationTests extends MockMvcEndpointDocumentation OffsetDateTime now = OffsetDateTime.now(); String queryTimestamp = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(now); given(this.repository.find("alice", now.toInstant(), "logout")) - .willReturn(Arrays.asList(new AuditEvent("alice", "logout", Collections.emptyMap()))); + .willReturn(Arrays.asList(new AuditEvent("alice", "logout", Collections.emptyMap()))); this.mockMvc - .perform(get("/actuator/auditevents") - .param("principal", "alice").param("after", queryTimestamp).param("type", "logout")) - .andExpect(status().isOk()) - .andDo(document("auditevents/filtered", - requestParameters( - parameterWithName("after").description( - "Restricts the events to those that occurred after the given time. Optional."), - parameterWithName("principal").description( - "Restricts the events to those with the given principal. Optional."), - parameterWithName("type") - .description("Restricts the events to those with the given type. Optional.")))); + .perform(get("/actuator/auditevents").param("principal", "alice") + .param("after", queryTimestamp) + .param("type", "logout")) + .andExpect(status().isOk()) + .andDo(document("auditevents/filtered", + requestParameters( + parameterWithName("after").description( + "Restricts the events to those that occurred after the given time. Optional."), + parameterWithName("principal") + .description("Restricts the events to those with the given principal. Optional."), + parameterWithName("type") + .description("Restricts the events to those with the given type. Optional.")))); then(this.repository).should().find("alice", now.toInstant(), "logout"); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/BeansEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/BeansEndpointDocumentationTests.java index 41a4ae8563..282eb162f1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/BeansEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/BeansEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,18 +53,20 @@ class BeansEndpointDocumentationTests extends MockMvcEndpointDocumentationTests List beanFields = Arrays.asList(fieldWithPath("aliases").description("Names of any aliases."), fieldWithPath("scope").description("Scope of the bean."), fieldWithPath("type").description("Fully qualified type of the bean."), - fieldWithPath("resource").description("Resource in which the bean was defined, if any.").optional() - .type(JsonFieldType.STRING), + fieldWithPath("resource").description("Resource in which the bean was defined, if any.") + .optional() + .type(JsonFieldType.STRING), fieldWithPath("dependencies").description("Names of any dependencies.")); ResponseFieldsSnippet responseFields = responseFields( fieldWithPath("contexts").description("Application contexts keyed by id."), parentIdField(), fieldWithPath("contexts.*.beans").description("Beans in the application context keyed by name.")) - .andWithPrefix("contexts.*.beans.*.", beanFields); - this.mockMvc.perform(get("/actuator/beans")).andExpect(status().isOk()) - .andDo(document("beans", - preprocessResponse( - limit(this::isIndependentBean, "contexts", getApplicationContext().getId(), "beans")), - responseFields)); + .andWithPrefix("contexts.*.beans.*.", beanFields); + this.mockMvc.perform(get("/actuator/beans")) + .andExpect(status().isOk()) + .andDo(document("beans", + preprocessResponse( + limit(this::isIndependentBean, "contexts", getApplicationContext().getId(), "beans")), + responseFields)); } private boolean isIndependentBean(Entry> bean) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/CachesEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/CachesEndpointDocumentationTests.java index 9b9e0a408c..a072cc733e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/CachesEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/CachesEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,38 +56,42 @@ class CachesEndpointDocumentationTests extends MockMvcEndpointDocumentationTests fieldWithPath("target").description("Fully qualified name of the native cache.")); private static final List requestParameters = Collections - .singletonList(parameterWithName("cacheManager").description( - "Name of the cacheManager to qualify the cache. May be omitted if the cache name is unique.") - .optional()); + .singletonList(parameterWithName("cacheManager") + .description("Name of the cacheManager to qualify the cache. May be omitted if the cache name is unique.") + .optional()); @Test void allCaches() throws Exception { - this.mockMvc.perform(get("/actuator/caches")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("caches/all", - responseFields(fieldWithPath("cacheManagers").description("Cache managers keyed by id."), - fieldWithPath("cacheManagers.*.caches") - .description("Caches in the application context keyed by name.")) - .andWithPrefix("cacheManagers.*.caches.*.", fieldWithPath("target") - .description("Fully qualified name of the native cache.")))); + this.mockMvc.perform(get("/actuator/caches")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("caches/all", + responseFields(fieldWithPath("cacheManagers").description("Cache managers keyed by id."), + fieldWithPath("cacheManagers.*.caches") + .description("Caches in the application context keyed by name.")) + .andWithPrefix("cacheManagers.*.caches.*.", + fieldWithPath("target").description("Fully qualified name of the native cache.")))); } @Test void namedCache() throws Exception { - this.mockMvc.perform(get("/actuator/caches/cities")).andExpect(status().isOk()).andDo(MockMvcRestDocumentation - .document("caches/named", requestParameters(requestParameters), responseFields(levelFields))); + this.mockMvc.perform(get("/actuator/caches/cities")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("caches/named", requestParameters(requestParameters), + responseFields(levelFields))); } @Test void evictAllCaches() throws Exception { - this.mockMvc.perform(delete("/actuator/caches")).andExpect(status().isNoContent()) - .andDo(MockMvcRestDocumentation.document("caches/evict-all")); + this.mockMvc.perform(delete("/actuator/caches")) + .andExpect(status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("caches/evict-all")); } @Test void evictNamedCache() throws Exception { this.mockMvc.perform(delete("/actuator/caches/countries?cacheManager=anotherCacheManager")) - .andExpect(status().isNoContent()) - .andDo(MockMvcRestDocumentation.document("caches/evict-named", requestParameters(requestParameters))); + .andExpect(status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("caches/evict-named", requestParameters(requestParameters))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConditionsReportEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConditionsReportEndpointDocumentationTests.java index 40c2e1194d..3e36dff8ad 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConditionsReportEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConditionsReportEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,7 +60,8 @@ class ConditionsReportEndpointDocumentationTests extends MockMvcEndpointDocument @BeforeEach void setup(RestDocumentationContextProvider restDocumentation) { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.applicationContext) - .apply(MockMvcRestDocumentation.documentationConfiguration(restDocumentation).uris()).build(); + .apply(MockMvcRestDocumentation.documentationConfiguration(restDocumentation).uris()) + .build(); } @Test @@ -76,19 +77,22 @@ class ConditionsReportEndpointDocumentationTests extends MockMvcEndpointDocument fieldWithPath(".*.notMatched.[].message").description("Details of why the condition was not matched."), fieldWithPath(".*.matched").description("Conditions that were matched."), fieldWithPath(".*.matched.[].condition").description("Name of the condition.") - .type(JsonFieldType.STRING).optional(), + .type(JsonFieldType.STRING) + .optional(), fieldWithPath(".*.matched.[].message").description("Details of why the condition was matched.") - .type(JsonFieldType.STRING).optional()); + .type(JsonFieldType.STRING) + .optional()); FieldDescriptor unconditionalClassesField = fieldWithPath("contexts.*.unconditionalClasses") - .description("Names of unconditional auto-configuration classes if any."); - this.mockMvc.perform(get("/actuator/conditions")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("conditions", - preprocessResponse(limit("contexts", getApplicationContext().getId(), "positiveMatches"), - limit("contexts", getApplicationContext().getId(), "negativeMatches")), - responseFields(fieldWithPath("contexts").description("Application contexts keyed by id.")) - .andWithPrefix("contexts.*.positiveMatches", positiveMatchFields) - .andWithPrefix("contexts.*.negativeMatches", negativeMatchFields) - .and(unconditionalClassesField, parentIdField()))); + .description("Names of unconditional auto-configuration classes if any."); + this.mockMvc.perform(get("/actuator/conditions")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("conditions", + preprocessResponse(limit("contexts", getApplicationContext().getId(), "positiveMatches"), + limit("contexts", getApplicationContext().getId(), "negativeMatches")), + responseFields(fieldWithPath("contexts").description("Application contexts keyed by id.")) + .andWithPrefix("contexts.*.positiveMatches", positiveMatchFields) + .andWithPrefix("contexts.*.negativeMatches", negativeMatchFields) + .and(unconditionalClassesField, parentIdField()))); } @Configuration(proxyBeanMethods = false) @@ -98,9 +102,9 @@ class ConditionsReportEndpointDocumentationTests extends MockMvcEndpointDocument @Bean ConditionsReportEndpoint autoConfigurationReportEndpoint(ConfigurableApplicationContext context) { ConditionEvaluationReport conditionEvaluationReport = ConditionEvaluationReport - .get(context.getBeanFactory()); + .get(context.getBeanFactory()); conditionEvaluationReport - .recordEvaluationCandidates(Arrays.asList(PropertyPlaceholderAutoConfiguration.class.getName())); + .recordEvaluationCandidates(Arrays.asList(PropertyPlaceholderAutoConfiguration.class.getName())); return new ConditionsReportEndpoint(context); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConfigurationPropertiesReportEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConfigurationPropertiesReportEndpointDocumentationTests.java index e1e5be8b10..e8a5842498 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConfigurationPropertiesReportEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConfigurationPropertiesReportEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,36 +42,38 @@ class ConfigurationPropertiesReportEndpointDocumentationTests extends MockMvcEnd @Test void configProps() throws Exception { - this.mockMvc.perform(get("/actuator/configprops")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("configprops/all", - preprocessResponse(limit("contexts", getApplicationContext().getId(), "beans")), - responseFields(fieldWithPath("contexts").description("Application contexts keyed by id."), - fieldWithPath("contexts.*.beans.*") - .description("`@ConfigurationProperties` beans keyed by bean name."), - fieldWithPath("contexts.*.beans.*.prefix") - .description("Prefix applied to the names of the bean's properties."), - subsectionWithPath("contexts.*.beans.*.properties") - .description("Properties of the bean as name-value pairs."), - subsectionWithPath("contexts.*.beans.*.inputs").description( - "Origin and value of the configuration property used when binding to this bean."), - parentIdField()))); + this.mockMvc.perform(get("/actuator/configprops")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("configprops/all", + preprocessResponse(limit("contexts", getApplicationContext().getId(), "beans")), + responseFields(fieldWithPath("contexts").description("Application contexts keyed by id."), + fieldWithPath("contexts.*.beans.*") + .description("`@ConfigurationProperties` beans keyed by bean name."), + fieldWithPath("contexts.*.beans.*.prefix") + .description("Prefix applied to the names of the bean's properties."), + subsectionWithPath("contexts.*.beans.*.properties") + .description("Properties of the bean as name-value pairs."), + subsectionWithPath("contexts.*.beans.*.inputs").description( + "Origin and value of the configuration property used when binding to this bean."), + parentIdField()))); } @Test void configPropsFilterByPrefix() throws Exception { - this.mockMvc.perform(get("/actuator/configprops/spring.jackson")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("configprops/prefixed", - preprocessResponse(limit("contexts", getApplicationContext().getId(), "beans")), - responseFields(fieldWithPath("contexts").description("Application contexts keyed by id."), - fieldWithPath("contexts.*.beans.*") - .description("`@ConfigurationProperties` beans keyed by bean name."), - fieldWithPath("contexts.*.beans.*.prefix") - .description("Prefix applied to the names of the bean's properties."), - subsectionWithPath("contexts.*.beans.*.properties") - .description("Properties of the bean as name-value pairs."), - subsectionWithPath("contexts.*.beans.*.inputs").description( - "Origin and value of the configuration property used when binding to this bean."), - parentIdField()))); + this.mockMvc.perform(get("/actuator/configprops/spring.jackson")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("configprops/prefixed", + preprocessResponse(limit("contexts", getApplicationContext().getId(), "beans")), + responseFields(fieldWithPath("contexts").description("Application contexts keyed by id."), + fieldWithPath("contexts.*.beans.*") + .description("`@ConfigurationProperties` beans keyed by bean name."), + fieldWithPath("contexts.*.beans.*.prefix") + .description("Prefix applied to the names of the bean's properties."), + subsectionWithPath("contexts.*.beans.*.properties") + .description("Properties of the bean as name-value pairs."), + subsectionWithPath("contexts.*.beans.*.inputs").description( + "Origin and value of the configuration property used when binding to this bean."), + parentIdField()))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/EnvironmentEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/EnvironmentEndpointDocumentationTests.java index e3e6cffffe..72a6aae3b7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/EnvironmentEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/EnvironmentEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,46 +60,53 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. class EnvironmentEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { private static final FieldDescriptor activeProfiles = fieldWithPath("activeProfiles") - .description("Names of the active profiles, if any."); + .description("Names of the active profiles, if any."); private static final FieldDescriptor propertySources = fieldWithPath("propertySources") - .description("Property sources in order of precedence."); + .description("Property sources in order of precedence."); private static final FieldDescriptor propertySourceName = fieldWithPath("propertySources.[].name") - .description("Name of the property source."); + .description("Name of the property source."); @Test void env() throws Exception { - this.mockMvc.perform(get("/actuator/env")).andExpect(status().isOk()) - .andDo(document("env/all", preprocessResponse(replacePattern( - Pattern.compile("org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/"), - ""), filterProperties()), - responseFields(activeProfiles, propertySources, propertySourceName, - fieldWithPath("propertySources.[].properties") - .description("Properties in the property source keyed by property name."), - fieldWithPath("propertySources.[].properties.*.value") - .description("Value of the property."), - fieldWithPath("propertySources.[].properties.*.origin") - .description("Origin of the property, if any.").optional()))); + this.mockMvc.perform(get("/actuator/env")) + .andExpect(status().isOk()) + .andDo(document("env/all", + preprocessResponse( + replacePattern(Pattern.compile( + "org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/"), ""), + filterProperties()), + responseFields(activeProfiles, propertySources, propertySourceName, + fieldWithPath("propertySources.[].properties") + .description("Properties in the property source keyed by property name."), + fieldWithPath("propertySources.[].properties.*.value") + .description("Value of the property."), + fieldWithPath("propertySources.[].properties.*.origin") + .description("Origin of the property, if any.") + .optional()))); } @Test void singlePropertyFromEnv() throws Exception { - this.mockMvc.perform(get("/actuator/env/com.example.cache.max-size")).andExpect(status().isOk()).andDo(document( - "env/single", - preprocessResponse(replacePattern( - Pattern.compile("org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/"), - "")), - responseFields( - fieldWithPath("property").description("Property from the environment, if found.").optional(), - fieldWithPath("property.source").description("Name of the source of the property."), - fieldWithPath("property.value").description("Value of the property."), activeProfiles, - propertySources, propertySourceName, - fieldWithPath("propertySources.[].property") - .description("Property in the property source, if any.").optional(), - fieldWithPath("propertySources.[].property.value").description("Value of the property."), - fieldWithPath("propertySources.[].property.origin") - .description("Origin of the property, if any.").optional()))); + this.mockMvc.perform(get("/actuator/env/com.example.cache.max-size")) + .andExpect(status().isOk()) + .andDo(document("env/single", + preprocessResponse(replacePattern(Pattern + .compile("org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/"), "")), + responseFields( + fieldWithPath("property").description("Property from the environment, if found.") + .optional(), + fieldWithPath("property.source").description("Name of the source of the property."), + fieldWithPath("property.value").description("Value of the property."), activeProfiles, + propertySources, propertySourceName, + fieldWithPath("propertySources.[].property") + .description("Property in the property source, if any.") + .optional(), + fieldWithPath("propertySources.[].property.value").description("Value of the property."), + fieldWithPath("propertySources.[].property.origin") + .description("Origin of the property, if any.") + .optional()))); } private OperationPreprocessor filterProperties() { @@ -114,8 +121,11 @@ class EnvironmentEndpointDocumentationTests extends MockMvcEndpointDocumentation List> propertySources = (List>) payload.get("propertySources"); for (Map propertySource : propertySources) { Map properties = (Map) propertySource.get("properties"); - Set filteredKeys = properties.keySet().stream().filter(this::retainKey).limit(3) - .collect(Collectors.toSet()); + Set filteredKeys = properties.keySet() + .stream() + .filter(this::retainKey) + .limit(3) + .collect(Collectors.toSet()); properties.keySet().retainAll(filteredKeys); } return objectMapper.writeValueAsBytes(payload); @@ -139,8 +149,10 @@ class EnvironmentEndpointDocumentationTests extends MockMvcEndpointDocumentation @Override protected void customizePropertySources(MutablePropertySources propertySources) { - environment.getPropertySources().stream().filter(this::includedPropertySource) - .forEach(propertySources::addLast); + environment.getPropertySources() + .stream() + .filter(this::includedPropertySource) + .forEach(propertySources::addLast); } private boolean includedPropertySource(PropertySource propertySource) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/FlywayEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/FlywayEndpointDocumentationTests.java index 784c2a3a71..9e497847b6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/FlywayEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/FlywayEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,36 +51,37 @@ class FlywayEndpointDocumentationTests extends MockMvcEndpointDocumentationTests @Test void flyway() throws Exception { - this.mockMvc.perform(get("/actuator/flyway")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("flyway", - responseFields(fieldWithPath("contexts").description("Application contexts keyed by id"), - fieldWithPath("contexts.*.flywayBeans.*.migrations").description( - "Migrations performed by the Flyway instance, keyed by Flyway bean name.")) - .andWithPrefix("contexts.*.flywayBeans.*.migrations.[].", - migrationFieldDescriptors()) - .and(parentIdField()))); + this.mockMvc.perform(get("/actuator/flyway")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("flyway", + responseFields(fieldWithPath("contexts").description("Application contexts keyed by id"), + fieldWithPath("contexts.*.flywayBeans.*.migrations") + .description("Migrations performed by the Flyway instance, keyed by Flyway bean name.")) + .andWithPrefix("contexts.*.flywayBeans.*.migrations.[].", migrationFieldDescriptors()) + .and(parentIdField()))); } private List migrationFieldDescriptors() { return Arrays.asList(fieldWithPath("checksum").description("Checksum of the migration, if any.").optional(), fieldWithPath("description").description("Description of the migration, if any.").optional(), fieldWithPath("executionTime").description("Execution time in milliseconds of an applied migration.") - .optional(), + .optional(), fieldWithPath("installedBy").description("User that installed the applied migration, if any.") - .optional(), + .optional(), fieldWithPath("installedOn") - .description("Timestamp of when the applied migration was installed, if any.").optional(), + .description("Timestamp of when the applied migration was installed, if any.") + .optional(), fieldWithPath("installedRank") - .description("Rank of the applied migration, if any. Later migrations have higher ranks.") - .optional(), + .description("Rank of the applied migration, if any. Later migrations have higher ranks.") + .optional(), fieldWithPath("script").description("Name of the script used to execute the migration, if any.") - .optional(), + .optional(), fieldWithPath("state") - .description("State of the migration. (" + describeEnumValues(MigrationState.class) + ")"), + .description("State of the migration. (" + describeEnumValues(MigrationState.class) + ")"), fieldWithPath("type") - .description("Type of the migration. (" + describeEnumValues(MigrationType.class) + ")"), + .description("Type of the migration. (" + describeEnumValues(MigrationType.class) + ")"), fieldWithPath("version").description("Version of the database after applying the migration, if any.") - .optional()); + .optional()); } @Configuration(proxyBeanMethods = false) @@ -91,7 +92,8 @@ class FlywayEndpointDocumentationTests extends MockMvcEndpointDocumentationTests @Bean DataSource dataSource() { return new EmbeddedDatabaseBuilder().generateUniqueName(true) - .setType(EmbeddedDatabaseConnection.get(getClass().getClassLoader()).getType()).build(); + .setType(EmbeddedDatabaseConnection.get(getClass().getClassLoader()).getType()) + .build(); } @Bean diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HealthEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HealthEndpointDocumentationTests.java index a512ca7a1b..8d47a690cb 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HealthEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HealthEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,28 +77,32 @@ class HealthEndpointDocumentationTests extends MockMvcEndpointDocumentationTests FieldDescriptor status = fieldWithPath("status").description("Overall status of the application."); FieldDescriptor components = fieldWithPath("components").description("The components that make up the health."); FieldDescriptor componentStatus = fieldWithPath("components.*.status") - .description("Status of a specific part of the application."); + .description("Status of a specific part of the application."); FieldDescriptor nestedComponents = subsectionWithPath("components.*.components") - .description("The nested components that make up the health.").optional(); + .description("The nested components that make up the health.") + .optional(); FieldDescriptor componentDetails = subsectionWithPath("components.*.details") - .description("Details of the health of a specific part of the application. " - + "Presence is controlled by `management.endpoint.health.show-details`.") - .optional(); - this.mockMvc.perform(get("/actuator/health").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("health", - responseFields(status, components, componentStatus, nestedComponents, componentDetails))); + .description("Details of the health of a specific part of the application. " + + "Presence is controlled by `management.endpoint.health.show-details`.") + .optional(); + this.mockMvc.perform(get("/actuator/health").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("health", + responseFields(status, components, componentStatus, nestedComponents, componentDetails))); } @Test void healthComponent() throws Exception { - this.mockMvc.perform(get("/actuator/health/db").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("health/component", responseFields(componentFields))); + this.mockMvc.perform(get("/actuator/health/db").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("health/component", responseFields(componentFields))); } @Test void healthComponentInstance() throws Exception { this.mockMvc.perform(get("/actuator/health/broker/us1").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andDo(document("health/instance", responseFields(componentFields))); + .andExpect(status().isOk()) + .andDo(document("health/instance", responseFields(componentFields))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HeapDumpWebEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HeapDumpWebEndpointDocumentationTests.java index 6e84c73fe3..ff8ca9dbbd 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HeapDumpWebEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HeapDumpWebEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,17 +43,18 @@ class HeapDumpWebEndpointDocumentationTests extends MockMvcEndpointDocumentation @Test void heapDump() throws Exception { - this.mockMvc.perform(get("/actuator/heapdump")).andExpect(status().isOk()) - .andDo(document("heapdump", new CurlRequestSnippet(CliDocumentation.multiLineFormat()) { + this.mockMvc.perform(get("/actuator/heapdump")) + .andExpect(status().isOk()) + .andDo(document("heapdump", new CurlRequestSnippet(CliDocumentation.multiLineFormat()) { - @Override - protected Map createModel(Operation operation) { - Map model = super.createModel(operation); - model.put("options", "-O"); - return model; - } + @Override + protected Map createModel(Operation operation) { + Map model = super.createModel(operation); + model.put("options", "-O"); + return model; + } - })); + })); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HttpTraceEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HttpTraceEndpointDocumentationTests.java index 0117a9a272..5af0f8f6d4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HttpTraceEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HttpTraceEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,42 +63,42 @@ class HttpTraceEndpointDocumentationTests extends MockMvcEndpointDocumentationTe given(request.getUri()).willReturn(URI.create("https://api.example.com")); given(request.getMethod()).willReturn("GET"); given(request.getHeaders()) - .willReturn(Collections.singletonMap(HttpHeaders.ACCEPT, Arrays.asList("application/json"))); + .willReturn(Collections.singletonMap(HttpHeaders.ACCEPT, Arrays.asList("application/json"))); TraceableResponse response = mock(TraceableResponse.class); given(response.getStatus()).willReturn(200); given(response.getHeaders()) - .willReturn(Collections.singletonMap(HttpHeaders.CONTENT_TYPE, Arrays.asList("application/json"))); + .willReturn(Collections.singletonMap(HttpHeaders.CONTENT_TYPE, Arrays.asList("application/json"))); Principal principal = mock(Principal.class); given(principal.getName()).willReturn("alice"); HttpExchangeTracer tracer = new HttpExchangeTracer(EnumSet.allOf(Include.class)); HttpTrace trace = tracer.receivedRequest(request); tracer.sendingResponse(trace, response, () -> principal, () -> UUID.randomUUID().toString()); given(this.repository.findAll()).willReturn(Arrays.asList(trace)); - this.mockMvc.perform(get("/actuator/httptrace")).andExpect(status().isOk()) - .andDo(document("httptrace", responseFields( - fieldWithPath("traces").description("An array of traced HTTP request-response exchanges."), - fieldWithPath("traces.[].timestamp") - .description("Timestamp of when the traced exchange occurred."), - fieldWithPath("traces.[].principal").description("Principal of the exchange, if any.") - .optional(), - fieldWithPath("traces.[].principal.name").description("Name of the principal.").optional(), - fieldWithPath("traces.[].request.method").description("HTTP method of the request."), - fieldWithPath("traces.[].request.remoteAddress") - .description("Remote address from which the request was received, if known.").optional() - .type(JsonFieldType.STRING), - fieldWithPath("traces.[].request.uri").description("URI of the request."), - fieldWithPath("traces.[].request.headers") - .description("Headers of the request, keyed by header name."), - fieldWithPath("traces.[].request.headers.*.[]").description("Values of the header"), - fieldWithPath("traces.[].response.status").description("Status of the response"), - fieldWithPath("traces.[].response.headers") - .description("Headers of the response, keyed by header name."), - fieldWithPath("traces.[].response.headers.*.[]").description("Values of the header"), - fieldWithPath("traces.[].session").description("Session associated with the exchange, if any.") - .optional(), - fieldWithPath("traces.[].session.id").description("ID of the session."), - fieldWithPath("traces.[].timeTaken") - .description("Time, in milliseconds, taken to handle the exchange.")))); + this.mockMvc.perform(get("/actuator/httptrace")) + .andExpect(status().isOk()) + .andDo(document("httptrace", responseFields( + fieldWithPath("traces").description("An array of traced HTTP request-response exchanges."), + fieldWithPath("traces.[].timestamp").description("Timestamp of when the traced exchange occurred."), + fieldWithPath("traces.[].principal").description("Principal of the exchange, if any.").optional(), + fieldWithPath("traces.[].principal.name").description("Name of the principal.").optional(), + fieldWithPath("traces.[].request.method").description("HTTP method of the request."), + fieldWithPath("traces.[].request.remoteAddress") + .description("Remote address from which the request was received, if known.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("traces.[].request.uri").description("URI of the request."), + fieldWithPath("traces.[].request.headers") + .description("Headers of the request, keyed by header name."), + fieldWithPath("traces.[].request.headers.*.[]").description("Values of the header"), + fieldWithPath("traces.[].response.status").description("Status of the response"), + fieldWithPath("traces.[].response.headers") + .description("Headers of the response, keyed by header name."), + fieldWithPath("traces.[].response.headers.*.[]").description("Values of the header"), + fieldWithPath("traces.[].session").description("Session associated with the exchange, if any.") + .optional(), + fieldWithPath("traces.[].session.id").description("ID of the session."), + fieldWithPath("traces.[].timeTaken") + .description("Time, in milliseconds, taken to handle the exchange.")))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/InfoEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/InfoEndpointDocumentationTests.java index 900e43fea7..39987ab5c5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/InfoEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/InfoEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,24 +49,25 @@ class InfoEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test void info() throws Exception { - this.mockMvc.perform(get("/actuator/info")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("info", - responseFields(beneathPath("git"), - fieldWithPath("branch").description("Name of the Git branch, if any."), - fieldWithPath("commit").description("Details of the Git commit, if any."), - fieldWithPath("commit.time").description("Timestamp of the commit, if any.") - .type(JsonFieldType.VARIES), - fieldWithPath("commit.id").description("ID of the commit, if any.")), - responseFields(beneathPath("build"), - fieldWithPath("artifact").description("Artifact ID of the application, if any.") - .optional(), - fieldWithPath("group").description("Group ID of the application, if any.").optional(), - fieldWithPath("name").description("Name of the application, if any.") - .type(JsonFieldType.STRING).optional(), - fieldWithPath("version").description("Version of the application, if any.").optional(), - fieldWithPath("time") - .description("Timestamp of when the application was built, if any.") - .type(JsonFieldType.VARIES).optional()))); + this.mockMvc.perform(get("/actuator/info")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("info", + responseFields(beneathPath("git"), + fieldWithPath("branch").description("Name of the Git branch, if any."), + fieldWithPath("commit").description("Details of the Git commit, if any."), + fieldWithPath("commit.time").description("Timestamp of the commit, if any.") + .type(JsonFieldType.VARIES), + fieldWithPath("commit.id").description("ID of the commit, if any.")), + responseFields(beneathPath("build"), + fieldWithPath("artifact").description("Artifact ID of the application, if any.").optional(), + fieldWithPath("group").description("Group ID of the application, if any.").optional(), + fieldWithPath("name").description("Name of the application, if any.") + .type(JsonFieldType.STRING) + .optional(), + fieldWithPath("version").description("Version of the application, if any.").optional(), + fieldWithPath("time").description("Timestamp of when the application was built, if any.") + .type(JsonFieldType.VARIES) + .optional()))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/IntegrationGraphEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/IntegrationGraphEndpointDocumentationTests.java index ed3509172b..36e7fb1e65 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/IntegrationGraphEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/IntegrationGraphEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,14 +39,16 @@ class IntegrationGraphEndpointDocumentationTests extends MockMvcEndpointDocument @Test void graph() throws Exception { - this.mockMvc.perform(get("/actuator/integrationgraph")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("integrationgraph/graph")); + this.mockMvc.perform(get("/actuator/integrationgraph")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("integrationgraph/graph")); } @Test void rebuild() throws Exception { - this.mockMvc.perform(post("/actuator/integrationgraph")).andExpect(status().isNoContent()) - .andDo(MockMvcRestDocumentation.document("integrationgraph/rebuild")); + this.mockMvc.perform(post("/actuator/integrationgraph")) + .andExpect(status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("integrationgraph/rebuild")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LiquibaseEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LiquibaseEndpointDocumentationTests.java index e72a660e50..50329c8f86 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LiquibaseEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LiquibaseEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,14 +48,14 @@ class LiquibaseEndpointDocumentationTests extends MockMvcEndpointDocumentationTe @Test void liquibase() throws Exception { FieldDescriptor changeSetsField = fieldWithPath("contexts.*.liquibaseBeans.*.changeSets") - .description("Change sets made by the Liquibase beans, keyed by bean name."); - this.mockMvc.perform(get("/actuator/liquibase")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("liquibase", - responseFields(fieldWithPath("contexts").description("Application contexts keyed by id"), - changeSetsField) - .andWithPrefix("contexts.*.liquibaseBeans.*.changeSets[].", - getChangeSetFieldDescriptors()) - .and(parentIdField()))); + .description("Change sets made by the Liquibase beans, keyed by bean name."); + this.mockMvc.perform(get("/actuator/liquibase")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("liquibase", + responseFields(fieldWithPath("contexts").description("Application contexts keyed by id"), + changeSetsField) + .andWithPrefix("contexts.*.liquibaseBeans.*.changeSets[].", getChangeSetFieldDescriptors()) + .and(parentIdField()))); } private List getChangeSetFieldDescriptors() { @@ -67,13 +67,14 @@ class LiquibaseEndpointDocumentationTests extends MockMvcEndpointDocumentationTe fieldWithPath("deploymentId").description("ID of the deployment that ran the change set."), fieldWithPath("description").description("Description of the change set."), fieldWithPath("execType") - .description("Execution type of the change set (" + describeEnumValues(ExecType.class) + ")."), + .description("Execution type of the change set (" + describeEnumValues(ExecType.class) + ")."), fieldWithPath("id").description("ID of the change set."), fieldWithPath("labels").description("Labels associated with the change set."), fieldWithPath("checksum").description("Checksum of the change set."), fieldWithPath("orderExecuted").description("Order of the execution of the change set."), - fieldWithPath("tag").description("Tag associated with the change set, if any.").optional() - .type(JsonFieldType.STRING)); + fieldWithPath("tag").description("Tag associated with the change set, if any.") + .optional() + .type(JsonFieldType.STRING)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LogFileWebEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LogFileWebEndpointDocumentationTests.java index 668c702e84..cb80ee01f2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LogFileWebEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LogFileWebEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,14 +38,16 @@ class LogFileWebEndpointDocumentationTests extends MockMvcEndpointDocumentationT @Test void logFile() throws Exception { - this.mockMvc.perform(get("/actuator/logfile")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("logfile/entire")); + this.mockMvc.perform(get("/actuator/logfile")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("logfile/entire")); } @Test void logFileRange() throws Exception { this.mockMvc.perform(get("/actuator/logfile").header("Range", "bytes=0-1023")) - .andExpect(status().isPartialContent()).andDo(MockMvcRestDocumentation.document("logfile/range")); + .andExpect(status().isPartialContent()) + .andDo(MockMvcRestDocumentation.document("logfile/range")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LoggersEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LoggersEndpointDocumentationTests.java index ff01109eb1..33f90fbe75 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LoggersEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LoggersEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,10 +62,10 @@ class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentationTest private static final List groupLevelFields; static { - groupLevelFields = Arrays.asList( - fieldWithPath("configuredLevel").description("Configured level of the logger group, if any.") - .type(JsonFieldType.STRING).optional(), - fieldWithPath("members").description("Loggers that are part of this group")); + groupLevelFields = Arrays + .asList(fieldWithPath("configuredLevel").description("Configured level of the logger group, if any.") + .type(JsonFieldType.STRING) + .optional(), fieldWithPath("members").description("Loggers that are part of this group")); } @MockBean @@ -78,55 +78,60 @@ class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentationTest void allLoggers() throws Exception { given(this.loggingSystem.getSupportedLogLevels()).willReturn(EnumSet.allOf(LogLevel.class)); given(this.loggingSystem.getLoggerConfigurations()) - .willReturn(Arrays.asList(new LoggerConfiguration("ROOT", LogLevel.INFO, LogLevel.INFO), - new LoggerConfiguration("com.example", LogLevel.DEBUG, LogLevel.DEBUG))); - this.mockMvc.perform(get("/actuator/loggers")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("loggers/all", - responseFields(fieldWithPath("levels").description("Levels support by the logging system."), - fieldWithPath("loggers").description("Loggers keyed by name."), - fieldWithPath("groups").description("Logger groups keyed by name")) - .andWithPrefix("loggers.*.", levelFields) - .andWithPrefix("groups.*.", groupLevelFields))); + .willReturn(Arrays.asList(new LoggerConfiguration("ROOT", LogLevel.INFO, LogLevel.INFO), + new LoggerConfiguration("com.example", LogLevel.DEBUG, LogLevel.DEBUG))); + this.mockMvc.perform(get("/actuator/loggers")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("loggers/all", + responseFields(fieldWithPath("levels").description("Levels support by the logging system."), + fieldWithPath("loggers").description("Loggers keyed by name."), + fieldWithPath("groups").description("Logger groups keyed by name")) + .andWithPrefix("loggers.*.", levelFields) + .andWithPrefix("groups.*.", groupLevelFields))); } @Test void logger() throws Exception { given(this.loggingSystem.getLoggerConfiguration("com.example")) - .willReturn(new LoggerConfiguration("com.example", LogLevel.INFO, LogLevel.INFO)); - this.mockMvc.perform(get("/actuator/loggers/com.example")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("loggers/single", responseFields(levelFields))); + .willReturn(new LoggerConfiguration("com.example", LogLevel.INFO, LogLevel.INFO)); + this.mockMvc.perform(get("/actuator/loggers/com.example")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("loggers/single", responseFields(levelFields))); } @Test void loggerGroups() throws Exception { this.loggerGroups.get("test").configureLogLevel(LogLevel.INFO, (member, level) -> { }); - this.mockMvc.perform(get("/actuator/loggers/test")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("loggers/group", responseFields(groupLevelFields))); + this.mockMvc.perform(get("/actuator/loggers/test")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("loggers/group", responseFields(groupLevelFields))); resetLogger(); } @Test void setLogLevel() throws Exception { this.mockMvc - .perform(post("/actuator/loggers/com.example").content("{\"configuredLevel\":\"debug\"}") - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isNoContent()) - .andDo(MockMvcRestDocumentation.document("loggers/set", requestFields(fieldWithPath("configuredLevel") - .description("Level for the logger. May be omitted to clear the level.").optional()))); + .perform(post("/actuator/loggers/com.example").content("{\"configuredLevel\":\"debug\"}") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("loggers/set", + requestFields(fieldWithPath("configuredLevel") + .description("Level for the logger. May be omitted to clear the level.") + .optional()))); then(this.loggingSystem).should().setLogLevel("com.example", LogLevel.DEBUG); } @Test void setLogLevelOfLoggerGroup() throws Exception { this.mockMvc - .perform(post("/actuator/loggers/test") - .content("{\"configuredLevel\":\"debug\"}").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isNoContent()).andDo( - MockMvcRestDocumentation.document("loggers/setGroup", - requestFields(fieldWithPath("configuredLevel").description( - "Level for the logger group. May be omitted to clear the level of the loggers.") - .optional()))); + .perform(post("/actuator/loggers/test").content("{\"configuredLevel\":\"debug\"}") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("loggers/setGroup", + requestFields(fieldWithPath("configuredLevel") + .description("Level for the logger group. May be omitted to clear the level of the loggers.") + .optional()))); then(this.loggingSystem).should().setLogLevel("test.member1", LogLevel.DEBUG); then(this.loggingSystem).should().setLogLevel("test.member2", LogLevel.DEBUG); resetLogger(); @@ -140,8 +145,9 @@ class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentationTest @Test void clearLogLevel() throws Exception { this.mockMvc - .perform(post("/actuator/loggers/com.example").content("{}").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isNoContent()).andDo(MockMvcRestDocumentation.document("loggers/clear")); + .perform(post("/actuator/loggers/com.example").content("{}").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("loggers/clear")); then(this.loggingSystem).should().setLogLevel("com.example", null); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointReactiveDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointReactiveDocumentationTests.java index 6ecd2863f7..79c673e812 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointReactiveDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointReactiveDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,8 +73,10 @@ class MappingsEndpointReactiveDocumentationTests extends AbstractEndpointDocumen @BeforeEach void webTestClient(RestDocumentationContextProvider restDocumentation) { this.client = WebTestClient.bindToServer() - .filter(documentationConfiguration(restDocumentation).snippets().withDefaults()) - .baseUrl("http://localhost:" + this.port).responseTimeout(Duration.ofMinutes(5)).build(); + .filter(documentationConfiguration(restDocumentation).snippets().withDefaults()) + .baseUrl("http://localhost:" + this.port) + .responseTimeout(Duration.ofMinutes(5)) + .build(); } @Test @@ -92,41 +94,49 @@ class MappingsEndpointReactiveDocumentationTests extends AbstractEndpointDocumen requestMappingConditionField(".params").description("Details of the params condition."), requestMappingConditionField(".params.[].name").description("Name of the parameter."), requestMappingConditionField(".params.[].value") - .description("Required value of the parameter, if any."), + .description("Required value of the parameter, if any."), requestMappingConditionField(".params.[].negated").description("Whether the value is negated."), requestMappingConditionField(".patterns") - .description("Patterns identifying the paths handled by the mapping."), + .description("Patterns identifying the paths handled by the mapping."), requestMappingConditionField(".produces").description("Details of the produces condition."), requestMappingConditionField(".produces.[].mediaType").description("Produced media type."), requestMappingConditionField(".produces.[].negated").description("Whether the media type is negated.")); List handlerMethod = Arrays.asList( - fieldWithPath("*.[].details.handlerMethod").optional().type(JsonFieldType.OBJECT) - .description("Details of the method, if any, that will handle requests to this mapping."), + fieldWithPath("*.[].details.handlerMethod").optional() + .type(JsonFieldType.OBJECT) + .description("Details of the method, if any, that will handle requests to this mapping."), fieldWithPath("*.[].details.handlerMethod.className").type(JsonFieldType.STRING) - .description("Fully qualified name of the class of the method."), + .description("Fully qualified name of the class of the method."), fieldWithPath("*.[].details.handlerMethod.name").type(JsonFieldType.STRING) - .description("Name of the method."), + .description("Name of the method."), fieldWithPath("*.[].details.handlerMethod.descriptor").type(JsonFieldType.STRING) - .description("Descriptor of the method as specified in the Java Language Specification.")); + .description("Descriptor of the method as specified in the Java Language Specification.")); List handlerFunction = Arrays.asList( - fieldWithPath("*.[].details.handlerFunction").optional().type(JsonFieldType.OBJECT) - .description("Details of the function, if any, that will handle requests to this mapping."), + fieldWithPath("*.[].details.handlerFunction").optional() + .type(JsonFieldType.OBJECT) + .description("Details of the function, if any, that will handle requests to this mapping."), fieldWithPath("*.[].details.handlerFunction.className").type(JsonFieldType.STRING) - .description("Fully qualified name of the class of the function.")); + .description("Fully qualified name of the class of the function.")); List dispatcherHandlerFields = new ArrayList<>(Arrays.asList( fieldWithPath("*") - .description("Dispatcher handler mappings, if any, keyed by dispatcher handler bean name."), - fieldWithPath("*.[].details").optional().type(JsonFieldType.OBJECT) - .description("Additional implementation-specific details about the mapping. Optional."), + .description("Dispatcher handler mappings, if any, keyed by dispatcher handler bean name."), + fieldWithPath("*.[].details").optional() + .type(JsonFieldType.OBJECT) + .description("Additional implementation-specific details about the mapping. Optional."), fieldWithPath("*.[].handler").description("Handler for the mapping."), fieldWithPath("*.[].predicate").description("Predicate for the mapping."))); dispatcherHandlerFields.addAll(requestMappingConditions); dispatcherHandlerFields.addAll(handlerMethod); dispatcherHandlerFields.addAll(handlerFunction); - this.client.get().uri("/actuator/mappings").exchange().expectStatus().isOk().expectBody() - .consumeWith(document("mappings", responseFields( - beneathPath("contexts.*.mappings.dispatcherHandlers").withSubsectionId("dispatcher-handlers"), - dispatcherHandlerFields))); + this.client.get() + .uri("/actuator/mappings") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .consumeWith(document("mappings", responseFields( + beneathPath("contexts.*.mappings.dispatcherHandlers").withSubsectionId("dispatcher-handlers"), + dispatcherHandlerFields))); } private FieldDescriptor requestMappingConditionField(String path) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointServletDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointServletDocumentationTests.java index b45f0ea735..b6399c7c3d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointServletDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointServletDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,8 +72,11 @@ class MappingsEndpointServletDocumentationTests extends AbstractEndpointDocument @BeforeEach void webTestClient(RestDocumentationContextProvider restDocumentation) { - this.client = WebTestClient.bindToServer().filter(documentationConfiguration(restDocumentation)) - .baseUrl("http://localhost:" + this.port).responseTimeout(Duration.ofMinutes(5)).build(); + this.client = WebTestClient.bindToServer() + .filter(documentationConfiguration(restDocumentation)) + .baseUrl("http://localhost:" + this.port) + .responseTimeout(Duration.ofMinutes(5)) + .build(); } @Test @@ -82,18 +85,21 @@ class MappingsEndpointServletDocumentationTests extends AbstractEndpointDocument fieldWithPath("contexts").description("Application contexts keyed by id."), fieldWithPath("contexts.*.mappings").description("Mappings in the context, keyed by mapping type."), subsectionWithPath("contexts.*.mappings.dispatcherServlets") - .description("Dispatcher servlet mappings, if any."), + .description("Dispatcher servlet mappings, if any."), subsectionWithPath("contexts.*.mappings.servletFilters") - .description("Servlet filter mappings, if any."), + .description("Servlet filter mappings, if any."), subsectionWithPath("contexts.*.mappings.servlets").description("Servlet mappings, if any."), subsectionWithPath("contexts.*.mappings.dispatcherHandlers") - .description("Dispatcher handler mappings, if any.").optional().type(JsonFieldType.OBJECT), + .description("Dispatcher handler mappings, if any.") + .optional() + .type(JsonFieldType.OBJECT), parentIdField()); List dispatcherServletFields = new ArrayList<>(Arrays.asList( fieldWithPath("*") - .description("Dispatcher servlet mappings, if any, keyed by dispatcher servlet bean name."), - fieldWithPath("*.[].details").optional().type(JsonFieldType.OBJECT) - .description("Additional implementation-specific details about the mapping. Optional."), + .description("Dispatcher servlet mappings, if any, keyed by dispatcher servlet bean name."), + fieldWithPath("*.[].details").optional() + .type(JsonFieldType.OBJECT) + .description("Additional implementation-specific details about the mapping. Optional."), fieldWithPath("*.[].handler").description("Handler for the mapping."), fieldWithPath("*.[].predicate").description("Predicate for the mapping."))); List requestMappingConditions = Arrays.asList( @@ -109,39 +115,43 @@ class MappingsEndpointServletDocumentationTests extends AbstractEndpointDocument requestMappingConditionField(".params").description("Details of the params condition."), requestMappingConditionField(".params.[].name").description("Name of the parameter."), requestMappingConditionField(".params.[].value") - .description("Required value of the parameter, if any."), + .description("Required value of the parameter, if any."), requestMappingConditionField(".params.[].negated").description("Whether the value is negated."), requestMappingConditionField(".patterns") - .description("Patterns identifying the paths handled by the mapping."), + .description("Patterns identifying the paths handled by the mapping."), requestMappingConditionField(".produces").description("Details of the produces condition."), requestMappingConditionField(".produces.[].mediaType").description("Produced media type."), requestMappingConditionField(".produces.[].negated").description("Whether the media type is negated.")); List handlerMethod = Arrays.asList( - fieldWithPath("*.[].details.handlerMethod").optional().type(JsonFieldType.OBJECT) - .description("Details of the method, if any, that will handle requests to this mapping."), + fieldWithPath("*.[].details.handlerMethod").optional() + .type(JsonFieldType.OBJECT) + .description("Details of the method, if any, that will handle requests to this mapping."), fieldWithPath("*.[].details.handlerMethod.className") - .description("Fully qualified name of the class of the method."), + .description("Fully qualified name of the class of the method."), fieldWithPath("*.[].details.handlerMethod.name").description("Name of the method."), fieldWithPath("*.[].details.handlerMethod.descriptor") - .description("Descriptor of the method as specified in the Java Language Specification.")); + .description("Descriptor of the method as specified in the Java Language Specification.")); dispatcherServletFields.addAll(handlerMethod); dispatcherServletFields.addAll(requestMappingConditions); - this.client.get().uri("/actuator/mappings").exchange().expectBody() - .consumeWith(document("mappings", commonResponseFields, - responseFields(beneathPath("contexts.*.mappings.dispatcherServlets") - .withSubsectionId("dispatcher-servlets"), dispatcherServletFields), - responseFields( - beneathPath("contexts.*.mappings.servletFilters").withSubsectionId("servlet-filters"), - fieldWithPath("[].servletNameMappings") - .description("Names of the servlets to which the filter is mapped."), - fieldWithPath("[].urlPatternMappings") - .description("URL pattern to which the filter is mapped."), - fieldWithPath("[].name").description("Name of the filter."), - fieldWithPath("[].className").description("Class name of the filter")), - responseFields(beneathPath("contexts.*.mappings.servlets").withSubsectionId("servlets"), - fieldWithPath("[].mappings").description("Mappings of the servlet."), - fieldWithPath("[].name").description("Name of the servlet."), - fieldWithPath("[].className").description("Class name of the servlet")))); + this.client.get() + .uri("/actuator/mappings") + .exchange() + .expectBody() + .consumeWith(document("mappings", commonResponseFields, + responseFields(beneathPath("contexts.*.mappings.dispatcherServlets") + .withSubsectionId("dispatcher-servlets"), dispatcherServletFields), + responseFields( + beneathPath("contexts.*.mappings.servletFilters").withSubsectionId("servlet-filters"), + fieldWithPath("[].servletNameMappings") + .description("Names of the servlets to which the filter is mapped."), + fieldWithPath("[].urlPatternMappings") + .description("URL pattern to which the filter is mapped."), + fieldWithPath("[].name").description("Name of the filter."), + fieldWithPath("[].className").description("Class name of the filter")), + responseFields(beneathPath("contexts.*.mappings.servlets").withSubsectionId("servlets"), + fieldWithPath("[].mappings").description("Mappings of the servlet."), + fieldWithPath("[].name").description("Name of the servlet."), + fieldWithPath("[].className").description("Class name of the servlet")))); } private FieldDescriptor requestMappingConditionField(String path) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MetricsEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MetricsEndpointDocumentationTests.java index 6a179c3535..938d9a7c85 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MetricsEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MetricsEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,34 +43,37 @@ class MetricsEndpointDocumentationTests extends MockMvcEndpointDocumentationTest @Test void metricNames() throws Exception { - this.mockMvc.perform(get("/actuator/metrics")).andExpect(status().isOk()).andDo(document("metrics/names", - responseFields(fieldWithPath("names").description("Names of the known metrics.")))); + this.mockMvc.perform(get("/actuator/metrics")) + .andExpect(status().isOk()) + .andDo(document("metrics/names", + responseFields(fieldWithPath("names").description("Names of the known metrics.")))); } @Test void metric() throws Exception { - this.mockMvc.perform(get("/actuator/metrics/jvm.memory.max")).andExpect(status().isOk()) - .andDo(document("metrics/metric", - responseFields(fieldWithPath("name").description("Name of the metric"), - fieldWithPath("description").description("Description of the metric"), - fieldWithPath("baseUnit").description("Base unit of the metric"), - fieldWithPath("measurements").description("Measurements of the metric"), - fieldWithPath("measurements[].statistic").description( - "Statistic of the measurement. (" + describeEnumValues(Statistic.class) + ")."), - fieldWithPath("measurements[].value").description("Value of the measurement."), - fieldWithPath("availableTags").description("Tags that are available for drill-down."), - fieldWithPath("availableTags[].tag").description("Name of the tag."), - fieldWithPath("availableTags[].values").description("Possible values of the tag.")))); + this.mockMvc.perform(get("/actuator/metrics/jvm.memory.max")) + .andExpect(status().isOk()) + .andDo(document("metrics/metric", + responseFields(fieldWithPath("name").description("Name of the metric"), + fieldWithPath("description").description("Description of the metric"), + fieldWithPath("baseUnit").description("Base unit of the metric"), + fieldWithPath("measurements").description("Measurements of the metric"), + fieldWithPath("measurements[].statistic").description( + "Statistic of the measurement. (" + describeEnumValues(Statistic.class) + ")."), + fieldWithPath("measurements[].value").description("Value of the measurement."), + fieldWithPath("availableTags").description("Tags that are available for drill-down."), + fieldWithPath("availableTags[].tag").description("Name of the tag."), + fieldWithPath("availableTags[].values").description("Possible values of the tag.")))); } @Test void metricWithTags() throws Exception { this.mockMvc - .perform(get("/actuator/metrics/jvm.memory.max").param("tag", "area:nonheap").param("tag", - "id:Compressed Class Space")) - .andExpect(status().isOk()) - .andDo(document("metrics/metric-with-tags", requestParameters(parameterWithName("tag") - .description("A tag to use for drill-down in the form `name:value`.")))); + .perform(get("/actuator/metrics/jvm.memory.max").param("tag", "area:nonheap") + .param("tag", "id:Compressed Class Space")) + .andExpect(status().isOk()) + .andDo(document("metrics/metric-with-tags", requestParameters( + parameterWithName("tag").description("A tag to use for drill-down in the form `name:value`.")))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MockMvcEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MockMvcEndpointDocumentationTests.java index 3c2399f5fd..fbfabbc3f4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MockMvcEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MockMvcEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,8 @@ public abstract class MockMvcEndpointDocumentationTests extends AbstractEndpoint @BeforeEach void setup(RestDocumentationContextProvider restDocumentation) { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.applicationContext) - .apply(MockMvcRestDocumentation.documentationConfiguration(restDocumentation).uris()).build(); + .apply(MockMvcRestDocumentation.documentationConfiguration(restDocumentation).uris()) + .build(); } protected WebApplicationContext getApplicationContext() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/PrometheusScrapeEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/PrometheusScrapeEndpointDocumentationTests.java index 128ff6033f..2f0b7a96ae 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/PrometheusScrapeEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/PrometheusScrapeEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,19 +51,21 @@ class PrometheusScrapeEndpointDocumentationTests extends MockMvcEndpointDocument @Test void prometheusOpenmetrics() throws Exception { this.mockMvc.perform(get("/actuator/prometheus").accept(TextFormat.CONTENT_TYPE_OPENMETRICS_100)) - .andExpect(status().isOk()) - .andExpect(header().string("Content-Type", "application/openmetrics-text;version=1.0.0;charset=utf-8")) - .andDo(document("prometheus/openmetrics")); + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", "application/openmetrics-text;version=1.0.0;charset=utf-8")) + .andDo(document("prometheus/openmetrics")); } @Test void filteredPrometheus() throws Exception { this.mockMvc - .perform(get("/actuator/prometheus").param("includedNames", - "jvm_memory_used_bytes,jvm_memory_committed_bytes")) - .andExpect(status().isOk()) - .andDo(document("prometheus/names", requestParameters(parameterWithName("includedNames") - .description("Restricts the samples to those that match the names. Optional.").optional()))); + .perform(get("/actuator/prometheus").param("includedNames", + "jvm_memory_used_bytes,jvm_memory_committed_bytes")) + .andExpect(status().isOk()) + .andDo(document("prometheus/names", + requestParameters(parameterWithName("includedNames") + .description("Restricts the samples to those that match the names. Optional.") + .optional()))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/QuartzEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/QuartzEndpointDocumentationTests.java index 30fb15c047..842af57f95 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/QuartzEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/QuartzEndpointDocumentationTests.java @@ -83,63 +83,78 @@ class QuartzEndpointDocumentationTests extends MockMvcEndpointDocumentationTests private static final TimeZone timeZone = TimeZone.getTimeZone("Europe/Paris"); - private static final JobDetail jobOne = JobBuilder.newJob(DelegatingJob.class).withIdentity("jobOne", "samples") - .withDescription("A sample job").usingJobData("user", "admin").usingJobData("password", "secret").build(); + private static final JobDetail jobOne = JobBuilder.newJob(DelegatingJob.class) + .withIdentity("jobOne", "samples") + .withDescription("A sample job") + .usingJobData("user", "admin") + .usingJobData("password", "secret") + .build(); private static final JobDetail jobTwo = JobBuilder.newJob(Job.class).withIdentity("jobTwo", "samples").build(); private static final JobDetail jobThree = JobBuilder.newJob(Job.class).withIdentity("jobThree", "tests").build(); - private static final CronTrigger cronTrigger = TriggerBuilder.newTrigger().forJob(jobOne).withPriority(3) - .withDescription("3AM on weekdays").withIdentity("3am-weekdays", "samples") - .withSchedule( - CronScheduleBuilder.atHourAndMinuteOnGivenDaysOfWeek(3, 0, 1, 2, 3, 4, 5).inTimeZone(timeZone)) - .build(); - - private static final SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger().forJob(jobOne).withPriority(7) - .withDescription("Once a day").withIdentity("every-day", "samples") - .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(24)).build(); - - private static final CalendarIntervalTrigger calendarIntervalTrigger = TriggerBuilder.newTrigger().forJob(jobTwo) - .withDescription("Once a week").withIdentity("once-a-week", "samples") - .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(1) - .inTimeZone(timeZone)) - .build(); + private static final CronTrigger cronTrigger = TriggerBuilder.newTrigger() + .forJob(jobOne) + .withPriority(3) + .withDescription("3AM on weekdays") + .withIdentity("3am-weekdays", "samples") + .withSchedule(CronScheduleBuilder.atHourAndMinuteOnGivenDaysOfWeek(3, 0, 1, 2, 3, 4, 5).inTimeZone(timeZone)) + .build(); + + private static final SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger() + .forJob(jobOne) + .withPriority(7) + .withDescription("Once a day") + .withIdentity("every-day", "samples") + .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(24)) + .build(); + + private static final CalendarIntervalTrigger calendarIntervalTrigger = TriggerBuilder.newTrigger() + .forJob(jobTwo) + .withDescription("Once a week") + .withIdentity("once-a-week", "samples") + .withSchedule( + CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(1).inTimeZone(timeZone)) + .build(); private static final DailyTimeIntervalTrigger dailyTimeIntervalTrigger = TriggerBuilder.newTrigger() - .forJob(jobThree).withDescription("Every hour between 9AM and 6PM on Tuesday and Thursday") - .withIdentity("every-hour-tue-thu") - .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() - .onDaysOfTheWeek(Calendar.TUESDAY, Calendar.THURSDAY) - .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)) - .endingDailyAt(TimeOfDay.hourAndMinuteOfDay(18, 0)).withInterval(1, IntervalUnit.HOUR)) - .build(); + .forJob(jobThree) + .withDescription("Every hour between 9AM and 6PM on Tuesday and Thursday") + .withIdentity("every-hour-tue-thu") + .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() + .onDaysOfTheWeek(Calendar.TUESDAY, Calendar.THURSDAY) + .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)) + .endingDailyAt(TimeOfDay.hourAndMinuteOfDay(18, 0)) + .withInterval(1, IntervalUnit.HOUR)) + .build(); private static final List triggerSummary = Arrays.asList(previousFireTime(""), nextFireTime(""), priority("")); private static final List cronTriggerSummary = Arrays.asList( fieldWithPath("expression").description("Cron expression to use."), - fieldWithPath("timeZone").type(JsonFieldType.STRING).optional() - .description("Time zone for which the expression will be resolved, if any.")); + fieldWithPath("timeZone").type(JsonFieldType.STRING) + .optional() + .description("Time zone for which the expression will be resolved, if any.")); private static final List simpleTriggerSummary = Collections - .singletonList(fieldWithPath("interval").description("Interval, in milliseconds, between two executions.")); + .singletonList(fieldWithPath("interval").description("Interval, in milliseconds, between two executions.")); - private static final List dailyTimeIntervalTriggerSummary = Arrays.asList( - fieldWithPath("interval").description( - "Interval, in milliseconds, added to the fire time in order to calculate the time of the next trigger repeat."), - fieldWithPath("daysOfWeek").type(JsonFieldType.ARRAY) + private static final List dailyTimeIntervalTriggerSummary = Arrays + .asList(fieldWithPath("interval").description( + "Interval, in milliseconds, added to the fire time in order to calculate the time of the next trigger repeat."), + fieldWithPath("daysOfWeek").type(JsonFieldType.ARRAY) .description("An array of days of the week upon which to fire."), - fieldWithPath("startTimeOfDay").type(JsonFieldType.STRING) + fieldWithPath("startTimeOfDay").type(JsonFieldType.STRING) .description("Time of day to start firing at the given interval, if any."), - fieldWithPath("endTimeOfDay").type(JsonFieldType.STRING) + fieldWithPath("endTimeOfDay").type(JsonFieldType.STRING) .description("Time of day to complete firing at the given interval, if any.")); - private static final List calendarIntervalTriggerSummary = Arrays.asList( - fieldWithPath("interval").description( - "Interval, in milliseconds, added to the fire time in order to calculate the time of the next trigger repeat."), - fieldWithPath("timeZone").type(JsonFieldType.STRING) + private static final List calendarIntervalTriggerSummary = Arrays + .asList(fieldWithPath("interval").description( + "Interval, in milliseconds, added to the fire time in order to calculate the time of the next trigger repeat."), + fieldWithPath("timeZone").type(JsonFieldType.STRING) .description("Time zone within which time calculations will be performed, if any.")); private static final List customTriggerSummary = Collections.singletonList( @@ -150,16 +165,18 @@ class QuartzEndpointDocumentationTests extends MockMvcEndpointDocumentationTests fieldWithPath("name").description("Name of the trigger."), fieldWithPath("description").description("Description of the trigger, if any."), fieldWithPath("state") - .description("State of the trigger (" + describeEnumValues(TriggerState.class) + ")."), + .description("State of the trigger (" + describeEnumValues(TriggerState.class) + ")."), fieldWithPath("type").description( "Type of the trigger (`calendarInterval`, `cron`, `custom`, `dailyTimeInterval`, `simple`). " + "Determines the key of the object containing type-specific details."), fieldWithPath("calendarName").description("Name of the Calendar associated with this Trigger, if any."), startTime(""), endTime(""), previousFireTime(""), nextFireTime(""), priority(""), - fieldWithPath("finalFireTime").optional().type(JsonFieldType.STRING) - .description("Last time at which the Trigger will fire, if any."), - fieldWithPath("data").optional().type(JsonFieldType.OBJECT) - .description("Job data map keyed by name, if any.") }; + fieldWithPath("finalFireTime").optional() + .type(JsonFieldType.STRING) + .description("Last time at which the Trigger will fire, if any."), + fieldWithPath("data").optional() + .type(JsonFieldType.OBJECT) + .description("Job data map keyed by name, if any.") }; @MockBean private Scheduler scheduler; @@ -168,54 +185,63 @@ class QuartzEndpointDocumentationTests extends MockMvcEndpointDocumentationTests void quartzReport() throws Exception { mockJobs(jobOne, jobTwo, jobThree); mockTriggers(cronTrigger, simpleTrigger, calendarIntervalTrigger, dailyTimeIntervalTrigger); - this.mockMvc.perform(get("/actuator/quartz")).andExpect(status().isOk()) - .andDo(document("quartz/report", - responseFields(fieldWithPath("jobs.groups").description("An array of job group names."), - fieldWithPath("triggers.groups").description("An array of trigger group names.")))); + this.mockMvc.perform(get("/actuator/quartz")) + .andExpect(status().isOk()) + .andDo(document("quartz/report", + responseFields(fieldWithPath("jobs.groups").description("An array of job group names."), + fieldWithPath("triggers.groups").description("An array of trigger group names.")))); } @Test void quartzJobs() throws Exception { mockJobs(jobOne, jobTwo, jobThree); - this.mockMvc.perform(get("/actuator/quartz/jobs")).andExpect(status().isOk()).andDo( - document("quartz/jobs", responseFields(fieldWithPath("groups").description("Job groups keyed by name."), - fieldWithPath("groups.*.jobs").description("An array of job names.")))); + this.mockMvc.perform(get("/actuator/quartz/jobs")) + .andExpect(status().isOk()) + .andDo(document("quartz/jobs", + responseFields(fieldWithPath("groups").description("Job groups keyed by name."), + fieldWithPath("groups.*.jobs").description("An array of job names.")))); } @Test void quartzTriggers() throws Exception { mockTriggers(cronTrigger, simpleTrigger, calendarIntervalTrigger, dailyTimeIntervalTrigger); - this.mockMvc.perform(get("/actuator/quartz/triggers")).andExpect(status().isOk()) - .andDo(document("quartz/triggers", - responseFields(fieldWithPath("groups").description("Trigger groups keyed by name."), - fieldWithPath("groups.*.paused").description("Whether this trigger group is paused."), - fieldWithPath("groups.*.triggers").description("An array of trigger names.")))); + this.mockMvc.perform(get("/actuator/quartz/triggers")) + .andExpect(status().isOk()) + .andDo(document("quartz/triggers", + responseFields(fieldWithPath("groups").description("Trigger groups keyed by name."), + fieldWithPath("groups.*.paused").description("Whether this trigger group is paused."), + fieldWithPath("groups.*.triggers").description("An array of trigger names.")))); } @Test void quartzJobGroup() throws Exception { mockJobs(jobOne, jobTwo, jobThree); - this.mockMvc.perform(get("/actuator/quartz/jobs/samples")).andExpect(status().isOk()) - .andDo(document("quartz/job-group", - responseFields(fieldWithPath("group").description("Name of the group."), - fieldWithPath("jobs").description("Job details keyed by name."), - fieldWithPath("jobs.*.className") - .description("Fully qualified name of the job implementation.")))); + this.mockMvc.perform(get("/actuator/quartz/jobs/samples")) + .andExpect(status().isOk()) + .andDo(document("quartz/job-group", responseFields(fieldWithPath("group").description("Name of the group."), + fieldWithPath("jobs").description("Job details keyed by name."), + fieldWithPath("jobs.*.className").description("Fully qualified name of the job implementation.")))); } @Test void quartzTriggerGroup() throws Exception { - CronTrigger cron = cronTrigger.getTriggerBuilder().startAt(fromUtc("2020-11-30T17:00:00Z")) - .endAt(fromUtc("2020-12-30T03:00:00Z")).withIdentity("3am-week", "tests").build(); + CronTrigger cron = cronTrigger.getTriggerBuilder() + .startAt(fromUtc("2020-11-30T17:00:00Z")) + .endAt(fromUtc("2020-12-30T03:00:00Z")) + .withIdentity("3am-week", "tests") + .build(); setPreviousNextFireTime(cron, "2020-12-04T03:00:00Z", "2020-12-07T03:00:00Z"); SimpleTrigger simple = simpleTrigger.getTriggerBuilder().withIdentity("every-day", "tests").build(); setPreviousNextFireTime(simple, null, "2020-12-04T12:00:00Z"); CalendarIntervalTrigger calendarInterval = calendarIntervalTrigger.getTriggerBuilder() - .withIdentity("once-a-week", "tests").startAt(fromUtc("2019-07-10T14:00:00Z")) - .endAt(fromUtc("2023-01-01T12:00:00Z")).build(); + .withIdentity("once-a-week", "tests") + .startAt(fromUtc("2019-07-10T14:00:00Z")) + .endAt(fromUtc("2023-01-01T12:00:00Z")) + .build(); setPreviousNextFireTime(calendarInterval, "2020-12-02T14:00:00Z", "2020-12-08T14:00:00Z"); DailyTimeIntervalTrigger tueThuTrigger = dailyTimeIntervalTrigger.getTriggerBuilder() - .withIdentity("tue-thu", "tests").build(); + .withIdentity("tue-thu", "tests") + .build(); Trigger customTrigger = mock(Trigger.class); given(customTrigger.getKey()).willReturn(TriggerKey.triggerKey("once-a-year-custom", "tests")); given(customTrigger.toString()).willReturn("com.example.CustomTrigger@fdsfsd"); @@ -223,24 +249,25 @@ class QuartzEndpointDocumentationTests extends MockMvcEndpointDocumentationTests given(customTrigger.getPreviousFireTime()).willReturn(fromUtc("2020-07-14T16:00:00Z")); given(customTrigger.getNextFireTime()).willReturn(fromUtc("2021-07-14T16:00:00Z")); mockTriggers(cron, simple, calendarInterval, tueThuTrigger, customTrigger); - this.mockMvc.perform(get("/actuator/quartz/triggers/tests")).andExpect(status().isOk()).andDo(document( - "quartz/trigger-group", - responseFields(fieldWithPath("group").description("Name of the group."), - fieldWithPath("paused").description("Whether the group is paused."), - fieldWithPath("triggers.cron").description("Cron triggers keyed by name, if any."), - fieldWithPath("triggers.simple").description("Simple triggers keyed by name, if any."), - fieldWithPath("triggers.dailyTimeInterval") + this.mockMvc.perform(get("/actuator/quartz/triggers/tests")) + .andExpect(status().isOk()) + .andDo(document("quartz/trigger-group", + responseFields(fieldWithPath("group").description("Name of the group."), + fieldWithPath("paused").description("Whether the group is paused."), + fieldWithPath("triggers.cron").description("Cron triggers keyed by name, if any."), + fieldWithPath("triggers.simple").description("Simple triggers keyed by name, if any."), + fieldWithPath("triggers.dailyTimeInterval") .description("Daily time interval triggers keyed by name, if any."), - fieldWithPath("triggers.calendarInterval") + fieldWithPath("triggers.calendarInterval") .description("Calendar interval triggers keyed by name, if any."), - fieldWithPath("triggers.custom").description("Any other triggers keyed by name, if any.")) - .andWithPrefix("triggers.cron.*.", concat(triggerSummary, cronTriggerSummary)) - .andWithPrefix("triggers.simple.*.", concat(triggerSummary, simpleTriggerSummary)) - .andWithPrefix("triggers.dailyTimeInterval.*.", - concat(triggerSummary, dailyTimeIntervalTriggerSummary)) - .andWithPrefix("triggers.calendarInterval.*.", - concat(triggerSummary, calendarIntervalTriggerSummary)) - .andWithPrefix("triggers.custom.*.", concat(triggerSummary, customTriggerSummary)))); + fieldWithPath("triggers.custom").description("Any other triggers keyed by name, if any.")) + .andWithPrefix("triggers.cron.*.", concat(triggerSummary, cronTriggerSummary)) + .andWithPrefix("triggers.simple.*.", concat(triggerSummary, simpleTriggerSummary)) + .andWithPrefix("triggers.dailyTimeInterval.*.", + concat(triggerSummary, dailyTimeIntervalTriggerSummary)) + .andWithPrefix("triggers.calendarInterval.*.", + concat(triggerSummary, calendarIntervalTriggerSummary)) + .andWithPrefix("triggers.custom.*.", concat(triggerSummary, customTriggerSummary)))); } @Test @@ -252,89 +279,101 @@ class QuartzEndpointDocumentationTests extends MockMvcEndpointDocumentationTests setPreviousNextFireTime(secondTrigger, "2020-12-04T03:00:00Z", "2020-12-04T12:00:00Z"); mockTriggers(firstTrigger, secondTrigger); given(this.scheduler.getTriggersOfJob(jobOne.getKey())) - .willAnswer((invocation) -> Arrays.asList(firstTrigger, secondTrigger)); - this.mockMvc.perform(get("/actuator/quartz/jobs/samples/jobOne")).andExpect(status().isOk()).andDo(document( - "quartz/job-details", - responseFields(fieldWithPath("group").description("Name of the group."), - fieldWithPath("name").description("Name of the job."), - fieldWithPath("description").description("Description of the job, if any."), - fieldWithPath("className").description("Fully qualified name of the job implementation."), - fieldWithPath("durable") - .description("Whether the job should remain stored after it is orphaned."), - fieldWithPath("requestRecovery").description( - "Whether the job should be re-executed if a 'recovery' or 'fail-over' situation is encountered."), - fieldWithPath("data.*").description("Job data map as key/value pairs, if any."), - fieldWithPath("triggers").description("An array of triggers associated to the job, if any."), - fieldWithPath("triggers.[].group").description("Name of the trigger group."), - fieldWithPath("triggers.[].name").description("Name of the trigger."), - previousFireTime("triggers.[]."), nextFireTime("triggers.[]."), priority("triggers.[].")))); + .willAnswer((invocation) -> Arrays.asList(firstTrigger, secondTrigger)); + this.mockMvc.perform(get("/actuator/quartz/jobs/samples/jobOne")) + .andExpect(status().isOk()) + .andDo(document("quartz/job-details", responseFields( + fieldWithPath("group").description("Name of the group."), + fieldWithPath("name").description("Name of the job."), + fieldWithPath("description").description("Description of the job, if any."), + fieldWithPath("className").description("Fully qualified name of the job implementation."), + fieldWithPath("durable").description("Whether the job should remain stored after it is orphaned."), + fieldWithPath("requestRecovery").description( + "Whether the job should be re-executed if a 'recovery' or 'fail-over' situation is encountered."), + fieldWithPath("data.*").description("Job data map as key/value pairs, if any."), + fieldWithPath("triggers").description("An array of triggers associated to the job, if any."), + fieldWithPath("triggers.[].group").description("Name of the trigger group."), + fieldWithPath("triggers.[].name").description("Name of the trigger."), + previousFireTime("triggers.[]."), nextFireTime("triggers.[]."), priority("triggers.[].")))); } @Test void quartzTriggerCommon() throws Exception { setupTriggerDetails(cronTrigger.getTriggerBuilder(), TriggerState.NORMAL); - this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")).andExpect(status().isOk()) - .andDo(document("quartz/trigger-details-common", responseFields(commonCronDetails).and( - subsectionWithPath("calendarInterval").description( - "Calendar time interval trigger details, if any. Present when `type` is `calendarInterval`.") - .optional().type(JsonFieldType.OBJECT), - subsectionWithPath("custom") - .description("Custom trigger details, if any. Present when `type` is `custom`.") - .optional().type(JsonFieldType.OBJECT), - subsectionWithPath("cron") - .description("Cron trigger details, if any. Present when `type` is `cron`.").optional() - .type(JsonFieldType.OBJECT), - subsectionWithPath("dailyTimeInterval").description( - "Daily time interval trigger details, if any. Present when `type` is `dailyTimeInterval`.") - .optional().type(JsonFieldType.OBJECT), - subsectionWithPath("simple") - .description("Simple trigger details, if any. Present when `type` is `simple`.") - .optional().type(JsonFieldType.OBJECT)))); + this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")) + .andExpect(status().isOk()) + .andDo(document("quartz/trigger-details-common", responseFields(commonCronDetails).and(subsectionWithPath( + "calendarInterval") + .description( + "Calendar time interval trigger details, if any. Present when `type` is `calendarInterval`.") + .optional() + .type(JsonFieldType.OBJECT), + subsectionWithPath("custom") + .description("Custom trigger details, if any. Present when `type` is `custom`.") + .optional() + .type(JsonFieldType.OBJECT), + subsectionWithPath("cron") + .description("Cron trigger details, if any. Present when `type` is `cron`.") + .optional() + .type(JsonFieldType.OBJECT), + subsectionWithPath("dailyTimeInterval").description( + "Daily time interval trigger details, if any. Present when `type` is `dailyTimeInterval`.") + .optional() + .type(JsonFieldType.OBJECT), + subsectionWithPath("simple") + .description("Simple trigger details, if any. Present when `type` is `simple`.") + .optional() + .type(JsonFieldType.OBJECT)))); } @Test void quartzTriggerCron() throws Exception { setupTriggerDetails(cronTrigger.getTriggerBuilder(), TriggerState.NORMAL); - this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")).andExpect(status().isOk()) - .andDo(document("quartz/trigger-details-cron", - relaxedResponseFields(fieldWithPath("cron").description("Cron trigger specific details.")) - .andWithPrefix("cron.", cronTriggerSummary))); + this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")) + .andExpect(status().isOk()) + .andDo(document("quartz/trigger-details-cron", + relaxedResponseFields(fieldWithPath("cron").description("Cron trigger specific details.")) + .andWithPrefix("cron.", cronTriggerSummary))); } @Test void quartzTriggerSimple() throws Exception { setupTriggerDetails(simpleTrigger.getTriggerBuilder(), TriggerState.NORMAL); - this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")).andExpect(status().isOk()) - .andDo(document("quartz/trigger-details-simple", - relaxedResponseFields(fieldWithPath("simple").description("Simple trigger specific details.")) - .andWithPrefix("simple.", simpleTriggerSummary) - .and(repeatCount("simple."), timesTriggered("simple.")))); + this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")) + .andExpect(status().isOk()) + .andDo(document("quartz/trigger-details-simple", + relaxedResponseFields(fieldWithPath("simple").description("Simple trigger specific details.")) + .andWithPrefix("simple.", simpleTriggerSummary) + .and(repeatCount("simple."), timesTriggered("simple.")))); } @Test void quartzTriggerCalendarInterval() throws Exception { setupTriggerDetails(calendarIntervalTrigger.getTriggerBuilder(), TriggerState.NORMAL); - this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")).andExpect(status().isOk()) - .andDo(document("quartz/trigger-details-calendar-interval", relaxedResponseFields( - fieldWithPath("calendarInterval").description("Calendar interval trigger specific details.")) - .andWithPrefix("calendarInterval.", calendarIntervalTriggerSummary) - .and(timesTriggered("calendarInterval."), fieldWithPath( - "calendarInterval.preserveHourOfDayAcrossDaylightSavings").description( - "Whether to fire the trigger at the same time of day, regardless of daylight " - + "saving time transitions."), - fieldWithPath("calendarInterval.skipDayIfHourDoesNotExist").description( - "Whether to skip if the hour of the day does not exist on a given day.")))); + this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")) + .andExpect(status().isOk()) + .andDo(document("quartz/trigger-details-calendar-interval", + relaxedResponseFields(fieldWithPath("calendarInterval") + .description("Calendar interval trigger specific details.")) + .andWithPrefix("calendarInterval.", calendarIntervalTriggerSummary) + .and(timesTriggered("calendarInterval."), + fieldWithPath("calendarInterval.preserveHourOfDayAcrossDaylightSavings").description( + "Whether to fire the trigger at the same time of day, regardless of daylight " + + "saving time transitions."), + fieldWithPath("calendarInterval.skipDayIfHourDoesNotExist").description( + "Whether to skip if the hour of the day does not exist on a given day.")))); } @Test void quartzTriggerDailyTimeInterval() throws Exception { setupTriggerDetails(dailyTimeIntervalTrigger.getTriggerBuilder(), TriggerState.PAUSED); - this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")).andExpect(status().isOk()) - .andDo(document("quartz/trigger-details-daily-time-interval", - relaxedResponseFields(fieldWithPath("dailyTimeInterval") - .description("Daily time interval trigger specific details.")) - .andWithPrefix("dailyTimeInterval.", dailyTimeIntervalTriggerSummary) - .and(repeatCount("dailyTimeInterval."), timesTriggered("dailyTimeInterval.")))); + this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")) + .andExpect(status().isOk()) + .andDo(document("quartz/trigger-details-daily-time-interval", + relaxedResponseFields(fieldWithPath("dailyTimeInterval") + .description("Daily time interval trigger specific details.")) + .andWithPrefix("dailyTimeInterval.", dailyTimeIntervalTriggerSummary) + .and(repeatCount("dailyTimeInterval."), timesTriggered("dailyTimeInterval.")))); } @Test @@ -351,17 +390,21 @@ class QuartzEndpointDocumentationTests extends MockMvcEndpointDocumentationTests given(trigger.getNextFireTime()).willReturn(fromUtc("2020-12-07T03:00:00Z")); given(this.scheduler.getTriggerState(trigger.getKey())).willReturn(TriggerState.NORMAL); mockTriggers(trigger); - this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")).andExpect(status().isOk()) - .andDo(document("quartz/trigger-details-custom", - relaxedResponseFields(fieldWithPath("custom").description("Custom trigger specific details.")) - .andWithPrefix("custom.", customTriggerSummary))); + this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")) + .andExpect(status().isOk()) + .andDo(document("quartz/trigger-details-custom", + relaxedResponseFields(fieldWithPath("custom").description("Custom trigger specific details.")) + .andWithPrefix("custom.", customTriggerSummary))); } private T setupTriggerDetails(TriggerBuilder builder, TriggerState state) throws SchedulerException { - T trigger = builder.withIdentity("example", "samples").withDescription("Example trigger") - .startAt(fromUtc("2020-11-30T17:00:00Z")).modifiedByCalendar("bankHolidays") - .endAt(fromUtc("2020-12-30T03:00:00Z")).build(); + T trigger = builder.withIdentity("example", "samples") + .withDescription("Example trigger") + .startAt(fromUtc("2020-11-30T17:00:00Z")) + .modifiedByCalendar("bankHolidays") + .endAt(fromUtc("2020-12-30T03:00:00Z")) + .build(); setPreviousNextFireTime(trigger, "2020-12-04T03:00:00Z", "2020-12-07T03:00:00Z"); given(this.scheduler.getTriggerState(trigger.getKey())).willReturn(state); mockTriggers(trigger); @@ -378,23 +421,25 @@ class QuartzEndpointDocumentationTests extends MockMvcEndpointDocumentationTests } private static FieldDescriptor previousFireTime(String prefix) { - return fieldWithPath(prefix + "previousFireTime").optional().type(JsonFieldType.STRING) - .description("Last time the trigger fired, if any."); + return fieldWithPath(prefix + "previousFireTime").optional() + .type(JsonFieldType.STRING) + .description("Last time the trigger fired, if any."); } private static FieldDescriptor nextFireTime(String prefix) { - return fieldWithPath(prefix + "nextFireTime").optional().type(JsonFieldType.STRING) - .description("Next time at which the Trigger is scheduled to fire, if any."); + return fieldWithPath(prefix + "nextFireTime").optional() + .type(JsonFieldType.STRING) + .description("Next time at which the Trigger is scheduled to fire, if any."); } private static FieldDescriptor priority(String prefix) { return fieldWithPath(prefix + "priority") - .description("Priority to use if two triggers have the same scheduled fire time."); + .description("Priority to use if two triggers have the same scheduled fire time."); } private static FieldDescriptor repeatCount(String prefix) { return fieldWithPath(prefix + "repeatCount") - .description("Number of times the trigger should repeat, or -1 to repeat indefinitely."); + .description("Number of times the trigger should repeat, or -1 to repeat indefinitely."); } private static FieldDescriptor timesTriggered(String prefix) { @@ -417,7 +462,7 @@ class QuartzEndpointDocumentationTests extends MockMvcEndpointDocumentationTests given(this.scheduler.getJobGroupNames()).willReturn(new ArrayList<>(jobKeys.keySet())); for (Entry> entry : jobKeys.entrySet()) { given(this.scheduler.getJobKeys(GroupMatcher.jobGroupEquals(entry.getKey()))) - .willReturn(new LinkedHashSet<>(entry.getValue())); + .willReturn(new LinkedHashSet<>(entry.getValue())); } } @@ -431,7 +476,7 @@ class QuartzEndpointDocumentationTests extends MockMvcEndpointDocumentationTests given(this.scheduler.getTriggerGroupNames()).willReturn(new ArrayList<>(triggerKeys.keySet())); for (Entry> entry : triggerKeys.entrySet()) { given(this.scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(entry.getKey()))) - .willReturn(new LinkedHashSet<>(entry.getValue())); + .willReturn(new LinkedHashSet<>(entry.getValue())); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ScheduledTasksEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ScheduledTasksEndpointDocumentationTests.java index a056ca55d3..2aa94ba126 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ScheduledTasksEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ScheduledTasksEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,28 +52,29 @@ class ScheduledTasksEndpointDocumentationTests extends MockMvcEndpointDocumentat @Test void scheduledTasks() throws Exception { - this.mockMvc.perform(get("/actuator/scheduledtasks")).andExpect(status().isOk()) - .andDo(document("scheduled-tasks", - preprocessResponse(replacePattern( - Pattern.compile("org.*\\.ScheduledTasksEndpointDocumentationTests\\$TestConfiguration"), - "com.example.Processor")), - responseFields(fieldWithPath("cron").description("Cron tasks, if any."), - targetFieldWithPrefix("cron.[]."), - fieldWithPath("cron.[].expression").description("Cron expression."), - fieldWithPath("fixedDelay").description("Fixed delay tasks, if any."), - targetFieldWithPrefix("fixedDelay.[]."), initialDelayWithPrefix("fixedDelay.[]."), - fieldWithPath("fixedDelay.[].interval") - .description("Interval, in milliseconds, between the end of the last" - + " execution and the start of the next."), - fieldWithPath("fixedRate").description("Fixed rate tasks, if any."), - targetFieldWithPrefix("fixedRate.[]."), - fieldWithPath("fixedRate.[].interval") - .description("Interval, in milliseconds, between the start of each execution."), - initialDelayWithPrefix("fixedRate.[]."), - fieldWithPath("custom").description("Tasks with custom triggers, if any."), - targetFieldWithPrefix("custom.[]."), - fieldWithPath("custom.[].trigger").description("Trigger for the task.")))) - .andDo(MockMvcResultHandlers.print()); + this.mockMvc.perform(get("/actuator/scheduledtasks")) + .andExpect(status().isOk()) + .andDo(document("scheduled-tasks", + preprocessResponse(replacePattern( + Pattern.compile("org.*\\.ScheduledTasksEndpointDocumentationTests\\$TestConfiguration"), + "com.example.Processor")), + responseFields(fieldWithPath("cron").description("Cron tasks, if any."), + targetFieldWithPrefix("cron.[]."), + fieldWithPath("cron.[].expression").description("Cron expression."), + fieldWithPath("fixedDelay").description("Fixed delay tasks, if any."), + targetFieldWithPrefix("fixedDelay.[]."), initialDelayWithPrefix("fixedDelay.[]."), + fieldWithPath("fixedDelay.[].interval") + .description("Interval, in milliseconds, between the end of the last" + + " execution and the start of the next."), + fieldWithPath("fixedRate").description("Fixed rate tasks, if any."), + targetFieldWithPrefix("fixedRate.[]."), + fieldWithPath("fixedRate.[].interval") + .description("Interval, in milliseconds, between the start of each execution."), + initialDelayWithPrefix("fixedRate.[]."), + fieldWithPath("custom").description("Tasks with custom triggers, if any."), + targetFieldWithPrefix("custom.[]."), + fieldWithPath("custom.[].trigger").description("Trigger for the task.")))) + .andDo(MockMvcResultHandlers.print()); } private FieldDescriptor targetFieldWithPrefix(String prefix) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/SessionsEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/SessionsEndpointDocumentationTests.java index d2282f986d..d9d523ec40 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/SessionsEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/SessionsEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,7 +71,7 @@ class SessionsEndpointDocumentationTests extends MockMvcEndpointDocumentationTes fieldWithPath("creationTime").description("Timestamp of when the session was created."), fieldWithPath("lastAccessedTime").description("Timestamp of when the session was last accessed."), fieldWithPath("maxInactiveInterval") - .description("Maximum permitted period of inactivity, in seconds, before the session will expire."), + .description("Maximum permitted period of inactivity, in seconds, before the session will expire."), fieldWithPath("expired").description("Whether the session has expired.")); @MockBean @@ -84,24 +84,27 @@ class SessionsEndpointDocumentationTests extends MockMvcEndpointDocumentationTes sessions.put(sessionTwo.getId(), sessionTwo); sessions.put(sessionThree.getId(), sessionThree); given(this.sessionRepository.findByPrincipalName("alice")).willReturn(sessions); - this.mockMvc.perform(get("/actuator/sessions").param("username", "alice")).andExpect(status().isOk()) - .andDo(document("sessions/username", - responseFields(fieldWithPath("sessions").description("Sessions for the given username.")) - .andWithPrefix("sessions.[].", sessionFields), - requestParameters(parameterWithName("username").description("Name of the user.")))); + this.mockMvc.perform(get("/actuator/sessions").param("username", "alice")) + .andExpect(status().isOk()) + .andDo(document("sessions/username", + responseFields(fieldWithPath("sessions").description("Sessions for the given username.")) + .andWithPrefix("sessions.[].", sessionFields), + requestParameters(parameterWithName("username").description("Name of the user.")))); } @Test void sessionWithId() throws Exception { given(this.sessionRepository.findById(sessionTwo.getId())).willReturn(sessionTwo); - this.mockMvc.perform(get("/actuator/sessions/{id}", sessionTwo.getId())).andExpect(status().isOk()) - .andDo(document("sessions/id", responseFields(sessionFields))); + this.mockMvc.perform(get("/actuator/sessions/{id}", sessionTwo.getId())) + .andExpect(status().isOk()) + .andDo(document("sessions/id", responseFields(sessionFields))); } @Test void deleteASession() throws Exception { - this.mockMvc.perform(delete("/actuator/sessions/{id}", sessionTwo.getId())).andExpect(status().isNoContent()) - .andDo(document("sessions/delete")); + this.mockMvc.perform(delete("/actuator/sessions/{id}", sessionTwo.getId())) + .andExpect(status().isNoContent()) + .andDo(document("sessions/delete")); then(this.sessionRepository).should().deleteById(sessionTwo.getId()); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ShutdownEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ShutdownEndpointDocumentationTests.java index 957462f239..033312870b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ShutdownEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ShutdownEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,9 +40,10 @@ class ShutdownEndpointDocumentationTests extends MockMvcEndpointDocumentationTes @Test void shutdown() throws Exception { - this.mockMvc.perform(post("/actuator/shutdown")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("shutdown", responseFields( - fieldWithPath("message").description("Message describing the result of the request.")))); + this.mockMvc.perform(post("/actuator/shutdown")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("shutdown", responseFields( + fieldWithPath("message").description("Message describing the result of the request.")))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/StartupEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/StartupEndpointDocumentationTests.java index e2651b884f..85e5a6e7a0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/StartupEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/StartupEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,36 +56,40 @@ class StartupEndpointDocumentationTests extends MockMvcEndpointDocumentationTest @Test void startupSnapshot() throws Exception { - this.mockMvc.perform(get("/actuator/startup")).andExpect(status().isOk()) - .andDo(document("startup-snapshot", PayloadDocumentation.responseFields(responseFields()))); + this.mockMvc.perform(get("/actuator/startup")) + .andExpect(status().isOk()) + .andDo(document("startup-snapshot", PayloadDocumentation.responseFields(responseFields()))); } @Test void startup() throws Exception { - this.mockMvc.perform(post("/actuator/startup")).andExpect(status().isOk()) - .andDo(document("startup", PayloadDocumentation.responseFields(responseFields()))); + this.mockMvc.perform(post("/actuator/startup")) + .andExpect(status().isOk()) + .andDo(document("startup", PayloadDocumentation.responseFields(responseFields()))); } private FieldDescriptor[] responseFields() { return new FieldDescriptor[] { fieldWithPath("springBootVersion").type(JsonFieldType.STRING) - .description("Spring Boot version for this application.").optional(), + .description("Spring Boot version for this application.") + .optional(), fieldWithPath("timeline.startTime").description("Start time of the application."), fieldWithPath("timeline.events") - .description("An array of steps collected during application startup so far."), + .description("An array of steps collected during application startup so far."), fieldWithPath("timeline.events.[].startTime").description("The timestamp of the start of this event."), fieldWithPath("timeline.events.[].endTime").description("The timestamp of the end of this event."), fieldWithPath("timeline.events.[].duration").description("The precise duration of this event."), fieldWithPath("timeline.events.[].startupStep.name").description("The name of the StartupStep."), fieldWithPath("timeline.events.[].startupStep.id").description("The id of this StartupStep."), fieldWithPath("timeline.events.[].startupStep.parentId") - .description("The parent id for this StartupStep.").optional(), + .description("The parent id for this StartupStep.") + .optional(), fieldWithPath("timeline.events.[].startupStep.tags") - .description("An array of key/value pairs with additional step info."), + .description("An array of key/value pairs with additional step info."), fieldWithPath("timeline.events.[].startupStep.tags[].key") - .description("The key of the StartupStep Tag."), + .description("The key of the StartupStep Tag."), fieldWithPath("timeline.events.[].startupStep.tags[].value") - .description("The value of the StartupStep Tag.") }; + .description("The value of the StartupStep Tag.") }; } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ThreadDumpEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ThreadDumpEndpointDocumentationTests.java index 53d85c503d..afed23b877 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ThreadDumpEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ThreadDumpEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,135 +63,132 @@ class ThreadDumpEndpointDocumentationTests extends MockMvcEndpointDocumentationT Thread.currentThread().interrupt(); } }).start(); - this.mockMvc.perform(get("/actuator/threaddump").accept(MediaType.APPLICATION_JSON)).andExpect( - status().isOk()).andDo( - MockMvcRestDocumentation - .document("threaddump/json", preprocessResponse(limit("threads")), - responseFields(fieldWithPath("threads").description("JVM's threads."), - fieldWithPath("threads.[].blockedCount").description( - "Total number of times that the thread has been blocked."), - fieldWithPath("threads.[].blockedTime").description( - "Time in milliseconds that the thread has spent " - + "blocked. -1 if thread contention " - + "monitoring is disabled."), - fieldWithPath("threads.[].daemon") - .description("Whether the thread is a daemon " - + "thread. Only available on Java 9 or later.") - .optional().type(JsonFieldType.BOOLEAN), - fieldWithPath("threads.[].inNative") - .description("Whether the thread is executing native code."), - fieldWithPath("threads.[].lockName") - .description("Description of the object on which the " - + "thread is blocked, if any.") - .optional().type(JsonFieldType.STRING), - fieldWithPath("threads.[].lockInfo") - .description("Object for which the thread is blocked waiting.") - .optional().type(JsonFieldType.OBJECT), - fieldWithPath("threads.[].lockInfo.className") - .description("Fully qualified class name of the lock object.") - .optional().type(JsonFieldType.STRING), - fieldWithPath("threads.[].lockInfo.identityHashCode") - .description("Identity hash code of the lock object.") - .optional().type(JsonFieldType.NUMBER), - fieldWithPath("threads.[].lockedMonitors") - .description("Monitors locked by this thread, if any"), - fieldWithPath("threads.[].lockedMonitors.[].className") - .description("Class name of the lock object.").optional() - .type(JsonFieldType.STRING), - fieldWithPath("threads.[].lockedMonitors.[].identityHashCode") - .description("Identity hash code of the lock object.") - .optional().type(JsonFieldType.NUMBER), - fieldWithPath("threads.[].lockedMonitors.[].lockedStackDepth") - .description("Stack depth where the monitor was locked.") - .optional().type(JsonFieldType.NUMBER), - subsectionWithPath("threads.[].lockedMonitors.[].lockedStackFrame") - .description("Stack frame that locked the monitor.").optional() - .type(JsonFieldType.OBJECT), - fieldWithPath("threads.[].lockedSynchronizers") - .description("Synchronizers locked by this thread."), - fieldWithPath("threads.[].lockedSynchronizers.[].className") - .description("Class name of the locked synchronizer.") - .optional().type(JsonFieldType.STRING), - fieldWithPath("threads.[].lockedSynchronizers.[].identityHashCode") - .description("Identity hash code of the locked synchronizer.") - .optional().type(JsonFieldType.NUMBER), - fieldWithPath("threads.[].lockOwnerId") - .description("ID of the thread that owns the object on which " - + "the thread is blocked. `-1` if the " - + "thread is not blocked."), - fieldWithPath("threads.[].lockOwnerName") - .description("Name of the thread that owns the " - + "object on which the thread is blocked, if any.") - .optional().type(JsonFieldType.STRING), - fieldWithPath("threads.[].priority") - .description("Priority of the thread. Only " - + "available on Java 9 or later.") - .optional().type(JsonFieldType.NUMBER), - fieldWithPath("threads.[].stackTrace") - .description("Stack trace of the thread."), - fieldWithPath("threads.[].stackTrace.[].classLoaderName") - .description("Name of the class loader of the " - + "class that contains the execution " - + "point identified by this entry, if " - + "any. Only available on Java 9 or later.") - .optional().type(JsonFieldType.STRING), - fieldWithPath("threads.[].stackTrace.[].className") - .description("Name of the class that contains the " - + "execution point identified by this entry."), - fieldWithPath("threads.[].stackTrace.[].fileName") - .description("Name of the source file that " - + "contains the execution point " - + "identified by this entry, if any.") - .optional().type(JsonFieldType.STRING), - fieldWithPath("threads.[].stackTrace.[].lineNumber") - .description("Line number of the execution " - + "point identified by this entry. " - + "Negative if unknown."), - fieldWithPath("threads.[].stackTrace.[].methodName") - .description("Name of the method."), - fieldWithPath("threads.[].stackTrace.[].moduleName") - .description("Name of the module that contains " - + "the execution point identified by " - + "this entry, if any. Only available " - + "on Java 9 or later.") - .optional().type(JsonFieldType.STRING), - fieldWithPath("threads.[].stackTrace.[].moduleVersion") - .description("Version of the module that " - + "contains the execution point " - + "identified by this entry, if any. " - + "Only available on Java 9 or later.") - .optional().type(JsonFieldType.STRING), - fieldWithPath("threads.[].stackTrace.[].nativeMethod") - .description("Whether the execution point is a native method."), - fieldWithPath("threads.[].suspended") - .description("Whether the thread is suspended."), - fieldWithPath("threads.[].threadId").description("ID of the thread."), - fieldWithPath("threads.[].threadName") - .description("Name of the thread."), - fieldWithPath("threads.[].threadState") - .description("State of the thread (" - + describeEnumValues(Thread.State.class) + ")."), - fieldWithPath("threads.[].waitedCount") - .description("Total number of times that the thread has waited" - + " for notification."), - fieldWithPath("threads.[].waitedTime") - .description("Time in milliseconds that the thread has spent " - + "waiting. -1 if thread contention " - + "monitoring is disabled")))); + this.mockMvc.perform(get("/actuator/threaddump").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation + .document("threaddump/json", preprocessResponse(limit("threads")), responseFields( + fieldWithPath("threads").description("JVM's threads."), + fieldWithPath("threads.[].blockedCount") + .description("Total number of times that the thread has been blocked."), + fieldWithPath("threads.[].blockedTime") + .description("Time in milliseconds that the thread has spent " + + "blocked. -1 if thread contention " + "monitoring is disabled."), + fieldWithPath("threads.[].daemon") + .description( + "Whether the thread is a daemon " + "thread. Only available on Java 9 or later.") + .optional() + .type(JsonFieldType.BOOLEAN), + fieldWithPath("threads.[].inNative") + .description("Whether the thread is executing native code."), + fieldWithPath("threads.[].lockName") + .description("Description of the object on which the " + "thread is blocked, if any.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].lockInfo") + .description("Object for which the thread is blocked waiting.") + .optional() + .type(JsonFieldType.OBJECT), + fieldWithPath("threads.[].lockInfo.className") + .description("Fully qualified class name of the lock object.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].lockInfo.identityHashCode") + .description("Identity hash code of the lock object.") + .optional() + .type(JsonFieldType.NUMBER), + fieldWithPath("threads.[].lockedMonitors") + .description("Monitors locked by this thread, if any"), + fieldWithPath("threads.[].lockedMonitors.[].className") + .description("Class name of the lock object.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].lockedMonitors.[].identityHashCode") + .description("Identity hash code of the lock object.") + .optional() + .type(JsonFieldType.NUMBER), + fieldWithPath("threads.[].lockedMonitors.[].lockedStackDepth") + .description("Stack depth where the monitor was locked.") + .optional() + .type(JsonFieldType.NUMBER), + subsectionWithPath("threads.[].lockedMonitors.[].lockedStackFrame") + .description("Stack frame that locked the monitor.") + .optional() + .type(JsonFieldType.OBJECT), + fieldWithPath("threads.[].lockedSynchronizers") + .description("Synchronizers locked by this thread."), + fieldWithPath("threads.[].lockedSynchronizers.[].className") + .description("Class name of the locked synchronizer.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].lockedSynchronizers.[].identityHashCode") + .description("Identity hash code of the locked synchronizer.") + .optional() + .type(JsonFieldType.NUMBER), + fieldWithPath("threads.[].lockOwnerId") + .description("ID of the thread that owns the object on which " + + "the thread is blocked. `-1` if the " + "thread is not blocked."), + fieldWithPath("threads.[].lockOwnerName") + .description("Name of the thread that owns the " + + "object on which the thread is blocked, if any.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].priority") + .description("Priority of the thread. Only " + "available on Java 9 or later.") + .optional() + .type(JsonFieldType.NUMBER), + fieldWithPath("threads.[].stackTrace").description("Stack trace of the thread."), + fieldWithPath("threads.[].stackTrace.[].classLoaderName") + .description("Name of the class loader of the " + "class that contains the execution " + + "point identified by this entry, if " + "any. Only available on Java 9 or later.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].stackTrace.[].className").description( + "Name of the class that contains the " + "execution point identified by this entry."), + fieldWithPath("threads.[].stackTrace.[].fileName") + .description("Name of the source file that " + "contains the execution point " + + "identified by this entry, if any.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].stackTrace.[].lineNumber").description("Line number of the execution " + + "point identified by this entry. " + "Negative if unknown."), + fieldWithPath("threads.[].stackTrace.[].methodName").description("Name of the method."), + fieldWithPath("threads.[].stackTrace.[].moduleName") + .description("Name of the module that contains " + "the execution point identified by " + + "this entry, if any. Only available " + "on Java 9 or later.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].stackTrace.[].moduleVersion") + .description("Version of the module that " + "contains the execution point " + + "identified by this entry, if any. " + "Only available on Java 9 or later.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].stackTrace.[].nativeMethod") + .description("Whether the execution point is a native method."), + fieldWithPath("threads.[].suspended").description("Whether the thread is suspended."), + fieldWithPath("threads.[].threadId").description("ID of the thread."), + fieldWithPath("threads.[].threadName").description("Name of the thread."), + fieldWithPath("threads.[].threadState") + .description("State of the thread (" + describeEnumValues(Thread.State.class) + ")."), + fieldWithPath("threads.[].waitedCount") + .description("Total number of times that the thread has waited" + " for notification."), + fieldWithPath("threads.[].waitedTime") + .description("Time in milliseconds that the thread has spent " + + "waiting. -1 if thread contention " + "monitoring is disabled")))); latch.countDown(); } @Test void textThreadDump() throws Exception { - this.mockMvc.perform(get("/actuator/threaddump").accept(MediaType.TEXT_PLAIN)).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("threaddump/text", - preprocessResponse(new ContentModifyingOperationPreprocessor((bytes, mediaType) -> { - String content = new String(bytes, StandardCharsets.UTF_8); - int mainThreadIndex = content.indexOf("\"main\" - Thread"); - String truncatedContent = (mainThreadIndex >= 0) ? content.substring(0, mainThreadIndex) - : content; - return truncatedContent.getBytes(); - })))); + this.mockMvc.perform(get("/actuator/threaddump").accept(MediaType.TEXT_PLAIN)) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("threaddump/text", + preprocessResponse(new ContentModifyingOperationPreprocessor((bytes, mediaType) -> { + String content = new String(bytes, StandardCharsets.UTF_8); + int mainThreadIndex = content.indexOf("\"main\" - Thread"); + String truncatedContent = (mainThreadIndex >= 0) ? content.substring(0, mainThreadIndex) + : content; + return truncatedContent.getBytes(); + })))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointIntegrationTests.java index 03d8f497ae..b7bdb93c7e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,19 +47,20 @@ class JerseyWebEndpointIntegrationTests { @Test void whenJerseyIsConfiguredToUseAFilterThenResourceRegistrationSucceeds() { new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class, - JerseyAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - JerseyWebEndpointManagementContextConfiguration.class)) - .withUserConfiguration(ResourceConfigConfiguration.class) - .withClassLoader(new FilteredClassLoader(DispatcherServlet.class)) - .withPropertyValues("spring.jersey.type=filter", "server.port=0").run((context) -> { - assertThat(context).hasNotFailed(); - Set resources = context.getBean(ResourceConfig.class).getResources(); - assertThat(resources).hasSize(1); - Resource resource = resources.iterator().next(); - assertThat(resource.getPath()).isEqualTo("/actuator"); - }); + .withConfiguration( + AutoConfigurations.of(JerseySameManagementContextConfiguration.class, JerseyAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, JerseyWebEndpointManagementContextConfiguration.class)) + .withUserConfiguration(ResourceConfigConfiguration.class) + .withClassLoader(new FilteredClassLoader(DispatcherServlet.class)) + .withPropertyValues("spring.jersey.type=filter", "server.port=0") + .run((context) -> { + assertThat(context).hasNotFailed(); + Set resources = context.getBean(ResourceConfig.class).getResources(); + assertThat(resources).hasSize(1); + Resource resource = resources.iterator().next(); + assertThat(resource.getPath()).isEqualTo("/actuator"); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfigurationTests.java index 475cbd073a..4a667841c3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,9 +41,9 @@ import static org.assertj.core.api.Assertions.assertThat; class JerseyWebEndpointManagementContextConfigurationTests { private final WebApplicationContextRunner runner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(WebEndpointAutoConfiguration.class, - JerseyWebEndpointManagementContextConfiguration.class)) - .withBean(WebEndpointsSupplier.class, () -> Collections::emptyList); + .withConfiguration(AutoConfigurations.of(WebEndpointAutoConfiguration.class, + JerseyWebEndpointManagementContextConfiguration.class)) + .withBean(WebEndpointsSupplier.class, () -> Collections::emptyList); @Test void jerseyWebEndpointsResourcesRegistrarForEndpointsIsAutoConfigured() { @@ -53,15 +53,15 @@ class JerseyWebEndpointManagementContextConfigurationTests { @Test void autoConfigurationIsConditionalOnServletWebApplication() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test void autoConfigurationIsConditionalOnClassResourceConfig() { this.runner.withClassLoader(new FilteredClassLoader(ResourceConfig.class)) - .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfigurationTests.java index 1f2b93d013..42b90e1a03 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,19 +44,19 @@ import static org.assertj.core.api.Assertions.assertThat; class EnvironmentEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(EnvironmentEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(EnvironmentEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=env") - .withSystemProperties("dbPassword=123456", "apiKey=123456") - .run(validateSystemProperties("******", "******")); + .withSystemProperties("dbPassword=123456", "apiKey=123456") + .run(validateSystemProperties("******", "******")); } @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.env.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(EnvironmentEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(EnvironmentEndpoint.class)); } @Test @@ -67,41 +67,42 @@ class EnvironmentEndpointAutoConfigurationTests { @Test void keysToSanitizeCanBeConfiguredViaTheEnvironment() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=env") - .withSystemProperties("dbPassword=123456", "apiKey=123456") - .withPropertyValues("management.endpoint.env.keys-to-sanitize=.*pass.*") - .run(validateSystemProperties("******", "123456")); + .withSystemProperties("dbPassword=123456", "apiKey=123456") + .withPropertyValues("management.endpoint.env.keys-to-sanitize=.*pass.*") + .run(validateSystemProperties("******", "123456")); } @Test void customSanitizingFunctionsAreAppliedInOrder() { this.contextRunner.withUserConfiguration(SanitizingFunctionConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=env") - .withSystemProperties("custom=123456", "password=123456").run((context) -> { - assertThat(context).hasSingleBean(EnvironmentEndpoint.class); - EnvironmentEndpoint endpoint = context.getBean(EnvironmentEndpoint.class); - EnvironmentDescriptor env = endpoint.environment(null); - Map systemProperties = getSource("systemProperties", env) - .getProperties(); - assertThat(systemProperties.get("custom").getValue()).isEqualTo("$$$111$$$"); - assertThat(systemProperties.get("password").getValue()).isEqualTo("$$$222$$$"); - }); + .withPropertyValues("management.endpoints.web.exposure.include=env") + .withSystemProperties("custom=123456", "password=123456") + .run((context) -> { + assertThat(context).hasSingleBean(EnvironmentEndpoint.class); + EnvironmentEndpoint endpoint = context.getBean(EnvironmentEndpoint.class); + EnvironmentDescriptor env = endpoint.environment(null); + Map systemProperties = getSource("systemProperties", env) + .getProperties(); + assertThat(systemProperties.get("custom").getValue()).isEqualTo("$$$111$$$"); + assertThat(systemProperties.get("password").getValue()).isEqualTo("$$$222$$$"); + }); } @Test void additionalKeysToSanitizeCanBeConfiguredViaTheEnvironment() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=env") - .withSystemProperties("dbPassword=123456", "apiKey=123456") - .withPropertyValues("management.endpoint.env.additional-keys-to-sanitize=key") - .run(validateSystemProperties("******", "******")); + .withSystemProperties("dbPassword=123456", "apiKey=123456") + .withPropertyValues("management.endpoint.env.additional-keys-to-sanitize=key") + .run(validateSystemProperties("******", "******")); } @Test void runWhenOnlyExposedOverJmxShouldHaveEndpointBeanWithoutWebExtension() { this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=info", "spring.jmx.enabled=true", - "management.endpoints.jmx.exposure.include=env") - .run((context) -> assertThat(context).hasSingleBean(EnvironmentEndpoint.class) - .doesNotHaveBean(EnvironmentEndpointWebExtension.class)); + .withPropertyValues("management.endpoints.web.exposure.include=info", "spring.jmx.enabled=true", + "management.endpoints.jmx.exposure.include=env") + .run((context) -> assertThat(context).hasSingleBean(EnvironmentEndpoint.class) + .doesNotHaveBean(EnvironmentEndpointWebExtension.class)); } private ContextConsumer validateSystemProperties(String dbPassword, String apiKey) { @@ -116,8 +117,11 @@ class EnvironmentEndpointAutoConfigurationTests { } private PropertySourceDescriptor getSource(String name, EnvironmentDescriptor descriptor) { - return descriptor.getPropertySources().stream().filter((source) -> name.equals(source.getName())).findFirst() - .get(); + return descriptor.getPropertySources() + .stream() + .filter((source) -> name.equals(source.getName())) + .findFirst() + .get(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/flyway/FlywayEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/flyway/FlywayEndpointAutoConfigurationTests.java index 6f99929e49..fcc99dcc75 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/flyway/FlywayEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/flyway/FlywayEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,19 +34,19 @@ import static org.mockito.Mockito.mock; class FlywayEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(FlywayEndpointAutoConfiguration.class)) - .withBean(Flyway.class, () -> mock(Flyway.class)); + .withConfiguration(AutoConfigurations.of(FlywayEndpointAutoConfiguration.class)) + .withBean(Flyway.class, () -> mock(Flyway.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=flyway") - .run((context) -> assertThat(context).hasSingleBean(FlywayEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(FlywayEndpoint.class)); } @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.flyway.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(FlywayEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(FlywayEndpoint.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/hazelcast/HazelcastHealthContributorAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/hazelcast/HazelcastHealthContributorAutoConfigurationIntegrationTests.java index 51b6f0128b..7101dd9522 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/hazelcast/HazelcastHealthContributorAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/hazelcast/HazelcastHealthContributorAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,8 @@ import static org.assertj.core.api.Assertions.assertThat; class HazelcastHealthContributorAutoConfigurationIntegrationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HazelcastHealthContributorAutoConfiguration.class, - HazelcastAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HazelcastHealthContributorAutoConfiguration.class, + HazelcastAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void hazelcastUp() { @@ -47,8 +47,9 @@ class HazelcastHealthContributorAutoConfigurationIntegrationTests { HazelcastInstance hazelcast = context.getBean(HazelcastInstance.class); Health health = context.getBean(HazelcastHealthIndicator.class).health(); assertThat(health.getStatus()).isEqualTo(Status.UP); - assertThat(health.getDetails()).containsOnlyKeys("name", "uuid").containsEntry("name", hazelcast.getName()) - .containsEntry("uuid", hazelcast.getLocalEndpoint().getUuid().toString()); + assertThat(health.getDetails()).containsOnlyKeys("name", "uuid") + .containsEntry("name", hazelcast.getName()) + .containsEntry("uuid", hazelcast.getLocalEndpoint().getUuid().toString()); }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/hazelcast/HazelcastHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/hazelcast/HazelcastHealthContributorAutoConfigurationTests.java index 0d0ea309bd..73ed857e17 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/hazelcast/HazelcastHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/hazelcast/HazelcastHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,8 @@ import static org.assertj.core.api.Assertions.assertThat; class HazelcastHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class, - HazelcastHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class, + HazelcastHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { @@ -45,7 +45,7 @@ class HazelcastHealthContributorAutoConfigurationTests { @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.hazelcast.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(HazelcastHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(HazelcastHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AbstractCompositeHealthContributorConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AbstractCompositeHealthContributorConfigurationTests.java index ce2b322614..e769d93ef3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AbstractCompositeHealthContributorConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AbstractCompositeHealthContributorConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,7 @@ abstract class AbstractCompositeHealthContributorConfigurationTests beans = Collections.emptyMap(); assertThatIllegalArgumentException().isThrownBy(() -> newComposite().createContributor(beans)) - .withMessage("Beans must not be empty"); + .withMessage("Beans must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthContributorRegistryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthContributorRegistryTests.java index d17a8e8612..b00c909453 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthContributorRegistryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthContributorRegistryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,10 +37,9 @@ class AutoConfiguredHealthContributorRegistryTests { @Test void createWhenContributorsClashesWithGroupNameThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> new AutoConfiguredHealthContributorRegistry( - Collections.singletonMap("boot", mock(HealthContributor.class)), - Arrays.asList("spring", "boot"))) - .withMessage("HealthContributor with name \"boot\" clashes with group"); + .isThrownBy(() -> new AutoConfiguredHealthContributorRegistry( + Collections.singletonMap("boot", mock(HealthContributor.class)), Arrays.asList("spring", "boot"))) + .withMessage("HealthContributor with name \"boot\" clashes with group"); } @Test @@ -48,8 +47,8 @@ class AutoConfiguredHealthContributorRegistryTests { HealthContributorRegistry registry = new AutoConfiguredHealthContributorRegistry(Collections.emptyMap(), Arrays.asList("spring", "boot")); assertThatIllegalStateException() - .isThrownBy(() -> registry.registerContributor("spring", mock(HealthContributor.class))) - .withMessage("HealthContributor with name \"spring\" clashes with group"); + .isThrownBy(() -> registry.registerContributor("spring", mock(HealthContributor.class))) + .withMessage("HealthContributor with name \"spring\" clashes with group"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupTests.java index 7c30ed2ed1..89f2922358 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -131,7 +131,7 @@ class AutoConfiguredHealthEndpointGroupTests { Arrays.asList("admin", "root", "bossmode"), null); Authentication principal = mock(Authentication.class); given(principal.getAuthorities()) - .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("admin"))); + .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("admin"))); given(this.securityContext.getPrincipal()).willReturn(principal); assertThat(group.showDetails(this.securityContext)).isTrue(); } @@ -143,7 +143,7 @@ class AutoConfiguredHealthEndpointGroupTests { Arrays.asList("admin", "rot", "bossmode"), null); Authentication principal = mock(Authentication.class); given(principal.getAuthorities()) - .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("other"))); + .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("other"))); given(this.securityContext.getPrincipal()).willReturn(principal); assertThat(group.showDetails(this.securityContext)).isFalse(); } @@ -219,7 +219,7 @@ class AutoConfiguredHealthEndpointGroupTests { Arrays.asList("admin", "root", "bossmode"), null); Authentication principal = mock(Authentication.class); given(principal.getAuthorities()) - .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("admin"))); + .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("admin"))); given(this.securityContext.getPrincipal()).willReturn(principal); assertThat(group.showComponents(this.securityContext)).isTrue(); } @@ -231,7 +231,7 @@ class AutoConfiguredHealthEndpointGroupTests { Arrays.asList("admin", "rot", "bossmode"), null); Authentication principal = mock(Authentication.class); given(principal.getAuthorities()) - .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("other"))); + .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("other"))); given(this.securityContext.getPrincipal()).willReturn(principal); assertThat(group.showComponents(this.securityContext)).isFalse(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupsTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupsTests.java index 36ac40b308..f967126a9d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupsTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ import static org.assertj.core.api.Assertions.assertThat; class AutoConfiguredHealthEndpointGroupsTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AutoConfiguredHealthEndpointGroupsTestConfiguration.class)); + .withConfiguration(AutoConfigurations.of(AutoConfiguredHealthEndpointGroupsTestConfiguration.class)); @Test void getPrimaryGroupMatchesAllMembers() { @@ -63,11 +63,13 @@ class AutoConfiguredHealthEndpointGroupsTests { @Test void getNamesReturnsGroupNames() { - this.contextRunner.withPropertyValues("management.endpoint.health.group.a.include=*", - "management.endpoint.health.group.b.include=*").run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - assertThat(groups.getNames()).containsExactlyInAnyOrder("a", "b"); - }); + this.contextRunner + .withPropertyValues("management.endpoint.health.group.a.include=*", + "management.endpoint.health.group.b.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + assertThat(groups.getNames()).containsExactlyInAnyOrder("a", "b"); + }); } @Test @@ -90,233 +92,245 @@ class AutoConfiguredHealthEndpointGroupsTests { @Test void createWhenNoDefinedBeansAdaptsProperties() { - this.contextRunner.withPropertyValues("management.endpoint.health.show-components=always", - "management.endpoint.health.show-details=never", "management.endpoint.health.status.order=up,down", - "management.endpoint.health.status.http-mapping.down=200").run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - assertThat(primary.showComponents(SecurityContext.NONE)).isTrue(); - assertThat(primary.showDetails(SecurityContext.NONE)).isFalse(); - assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN)) - .isEqualTo(Status.UP); - assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); - }); + this.contextRunner + .withPropertyValues("management.endpoint.health.show-components=always", + "management.endpoint.health.show-details=never", "management.endpoint.health.status.order=up,down", + "management.endpoint.health.status.http-mapping.down=200") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + assertThat(primary.showComponents(SecurityContext.NONE)).isTrue(); + assertThat(primary.showDetails(SecurityContext.NONE)).isFalse(); + assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN)) + .isEqualTo(Status.UP); + assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); + }); } @Test void createWhenHasStatusAggregatorBeanReturnsInstanceWithAggregatorUsedForAllGroups() { this.contextRunner.withUserConfiguration(CustomStatusAggregatorConfiguration.class) - .withPropertyValues("management.endpoint.health.status.order=up,down", - "management.endpoint.health.group.a.include=*") - .run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UNKNOWN); - assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UNKNOWN); - }); + .withPropertyValues("management.endpoint.health.status.order=up,down", + "management.endpoint.health.group.a.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UNKNOWN); + assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UNKNOWN); + }); } @Test void createWhenHasStatusAggregatorBeanAndGroupSpecificPropertyReturnsInstanceThatUsesBeanOnlyForUnconfiguredGroups() { this.contextRunner.withUserConfiguration(CustomStatusAggregatorConfiguration.class) - .withPropertyValues("management.endpoint.health.group.a.include=*", - "management.endpoint.health.group.a.status.order=up,down", - "management.endpoint.health.group.b.include=*") - .run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - HealthEndpointGroup groupB = groups.get("b"); - assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UNKNOWN); - assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UP); - assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UNKNOWN); - }); + .withPropertyValues("management.endpoint.health.group.a.include=*", + "management.endpoint.health.group.a.status.order=up,down", + "management.endpoint.health.group.b.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + HealthEndpointGroup groupB = groups.get("b"); + assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UNKNOWN); + assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UP); + assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UNKNOWN); + }); } @Test void createWhenHasStatusAggregatorPropertyReturnsInstanceWithPropertyUsedForAllGroups() { - this.contextRunner.withPropertyValues("management.endpoint.health.status.order=up,down", - "management.endpoint.health.group.a.include=*").run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN)) - .isEqualTo(Status.UP); - assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN)) - .isEqualTo(Status.UP); - }); + this.contextRunner + .withPropertyValues("management.endpoint.health.status.order=up,down", + "management.endpoint.health.group.a.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN)) + .isEqualTo(Status.UP); + assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN)) + .isEqualTo(Status.UP); + }); } @Test void createWhenHasStatusAggregatorPropertyAndGroupSpecificPropertyReturnsInstanceWithPropertyUsedForExpectedGroups() { - this.contextRunner.withPropertyValues("management.endpoint.health.status.order=up,down", - "management.endpoint.health.group.a.include=*", - "management.endpoint.health.group.a.status.order=unknown,up,down", - "management.endpoint.health.group.b.include=*").run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - HealthEndpointGroup groupB = groups.get("b"); - assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UP); - assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UNKNOWN); - assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UP); - }); + this.contextRunner + .withPropertyValues("management.endpoint.health.status.order=up,down", + "management.endpoint.health.group.a.include=*", + "management.endpoint.health.group.a.status.order=unknown,up,down", + "management.endpoint.health.group.b.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + HealthEndpointGroup groupB = groups.get("b"); + assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UP); + assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UNKNOWN); + assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UP); + }); } @Test void createWhenHasStatusAggregatorPropertyAndGroupQualifiedBeanReturnsInstanceWithBeanUsedForExpectedGroups() { this.contextRunner.withUserConfiguration(CustomStatusAggregatorGroupAConfiguration.class) - .withPropertyValues("management.endpoint.health.status.order=up,down", - "management.endpoint.health.group.a.include=*", - "management.endpoint.health.group.a.status.order=up,down", - "management.endpoint.health.group.b.include=*") - .run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - HealthEndpointGroup groupB = groups.get("b"); - assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UP); - assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UNKNOWN); - assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UP); - }); + .withPropertyValues("management.endpoint.health.status.order=up,down", + "management.endpoint.health.group.a.include=*", + "management.endpoint.health.group.a.status.order=up,down", + "management.endpoint.health.group.b.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + HealthEndpointGroup groupB = groups.get("b"); + assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UP); + assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UNKNOWN); + assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UP); + }); } @Test void createWhenHasGroupSpecificStatusAggregatorPropertyAndGroupQualifiedBeanReturnsInstanceWithBeanUsedForExpectedGroups() { this.contextRunner.withUserConfiguration(CustomStatusAggregatorGroupAConfiguration.class) - .withPropertyValues("management.endpoint.health.group.a.include=*", - "management.endpoint.health.group.a.status.order=up,down", - "management.endpoint.health.group.b.include=*", - "management.endpoint.health.group.b.status.order=up,down") - .run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - HealthEndpointGroup groupB = groups.get("b"); - assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.DOWN); - assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UNKNOWN); - assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UP); - }); + .withPropertyValues("management.endpoint.health.group.a.include=*", + "management.endpoint.health.group.a.status.order=up,down", + "management.endpoint.health.group.b.include=*", + "management.endpoint.health.group.b.status.order=up,down") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + HealthEndpointGroup groupB = groups.get("b"); + assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.DOWN); + assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UNKNOWN); + assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UP); + }); } @Test void createWhenHasHttpCodeStatusMapperBeanReturnsInstanceWithMapperUsedForAllGroups() { this.contextRunner.withUserConfiguration(CustomHttpCodeStatusMapperConfiguration.class) - .withPropertyValues("management.endpoint.health.status.http-mapping.down=201", - "management.endpoint.health.group.a.include=*") - .run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); - assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); - }); + .withPropertyValues("management.endpoint.health.status.http-mapping.down=201", + "management.endpoint.health.group.a.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); + assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); + }); } @Test void createWhenHasHttpCodeStatusMapperBeanAndGroupSpecificPropertyReturnsInstanceThatUsesBeanOnlyForUnconfiguredGroups() { this.contextRunner.withUserConfiguration(CustomHttpCodeStatusMapperConfiguration.class) - .withPropertyValues("management.endpoint.health.group.a.include=*", - "management.endpoint.health.group.a.status.http-mapping.down=201", - "management.endpoint.health.group.b.include=*") - .run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - HealthEndpointGroup groupB = groups.get("b"); - assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); - assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); - assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); - }); + .withPropertyValues("management.endpoint.health.group.a.include=*", + "management.endpoint.health.group.a.status.http-mapping.down=201", + "management.endpoint.health.group.b.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + HealthEndpointGroup groupB = groups.get("b"); + assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); + assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); + assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); + }); } @Test void createWhenHasHttpCodeStatusMapperPropertyReturnsInstanceWithPropertyUsedForAllGroups() { - this.contextRunner.withPropertyValues("management.endpoint.health.status.http-mapping.down=201", - "management.endpoint.health.group.a.include=*").run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); - assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); - }); + this.contextRunner + .withPropertyValues("management.endpoint.health.status.http-mapping.down=201", + "management.endpoint.health.group.a.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); + assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); + }); } @Test void createWhenHasHttpCodeStatusMapperPropertyAndGroupSpecificPropertyReturnsInstanceWithPropertyUsedForExpectedGroups() { - this.contextRunner.withPropertyValues("management.endpoint.health.status.http-mapping.down=201", - "management.endpoint.health.group.a.include=*", - "management.endpoint.health.group.a.status.http-mapping.down=202", - "management.endpoint.health.group.b.include=*").run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - HealthEndpointGroup groupB = groups.get("b"); - assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); - assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(202); - assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); - }); + this.contextRunner + .withPropertyValues("management.endpoint.health.status.http-mapping.down=201", + "management.endpoint.health.group.a.include=*", + "management.endpoint.health.group.a.status.http-mapping.down=202", + "management.endpoint.health.group.b.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + HealthEndpointGroup groupB = groups.get("b"); + assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); + assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(202); + assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); + }); } @Test void createWhenHasHttpCodeStatusMapperPropertyAndGroupQualifiedBeanReturnsInstanceWithBeanUsedForExpectedGroups() { this.contextRunner.withUserConfiguration(CustomHttpCodeStatusMapperGroupAConfiguration.class) - .withPropertyValues("management.endpoint.health.status.http-mapping.down=201", - "management.endpoint.health.group.a.include=*", - "management.endpoint.health.group.a.status.http-mapping.down=201", - "management.endpoint.health.group.b.include=*") - .run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - HealthEndpointGroup groupB = groups.get("b"); - assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); - assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); - assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); - }); + .withPropertyValues("management.endpoint.health.status.http-mapping.down=201", + "management.endpoint.health.group.a.include=*", + "management.endpoint.health.group.a.status.http-mapping.down=201", + "management.endpoint.health.group.b.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + HealthEndpointGroup groupB = groups.get("b"); + assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); + assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); + assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); + }); } @Test void createWhenHasGroupSpecificHttpCodeStatusMapperPropertyAndGroupQualifiedBeanReturnsInstanceWithBeanUsedForExpectedGroups() { this.contextRunner.withUserConfiguration(CustomHttpCodeStatusMapperGroupAConfiguration.class) - .withPropertyValues("management.endpoint.health.group.a.include=*", - "management.endpoint.health.group.a.status.http-mapping.down=201", - "management.endpoint.health.group.b.include=*", - "management.endpoint.health.group.b.status.http-mapping.down=201") - .run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - HealthEndpointGroup groupB = groups.get("b"); - assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(503); - assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); - assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); - }); + .withPropertyValues("management.endpoint.health.group.a.include=*", + "management.endpoint.health.group.a.status.http-mapping.down=201", + "management.endpoint.health.group.b.include=*", + "management.endpoint.health.group.b.status.http-mapping.down=201") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + HealthEndpointGroup groupB = groups.get("b"); + assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(503); + assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); + assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); + }); } @Test void createWhenGroupWithNoShowDetailsOverrideInheritsShowDetails() { - this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always", - "management.endpoint.health.group.a.include=*").run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup groupA = groups.get("a"); - assertThat(groupA.showDetails(SecurityContext.NONE)).isTrue(); - }); + this.contextRunner + .withPropertyValues("management.endpoint.health.show-details=always", + "management.endpoint.health.group.a.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup groupA = groups.get("a"); + assertThat(groupA.showDetails(SecurityContext.NONE)).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredReactiveHealthContributorRegistryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredReactiveHealthContributorRegistryTests.java index 2f9482cdf8..c222878319 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredReactiveHealthContributorRegistryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredReactiveHealthContributorRegistryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,10 +37,10 @@ class AutoConfiguredReactiveHealthContributorRegistryTests { @Test void createWhenContributorsClashesWithGroupNameThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> new AutoConfiguredReactiveHealthContributorRegistry( - Collections.singletonMap("boot", mock(ReactiveHealthContributor.class)), - Arrays.asList("spring", "boot"))) - .withMessage("ReactiveHealthContributor with name \"boot\" clashes with group"); + .isThrownBy(() -> new AutoConfiguredReactiveHealthContributorRegistry( + Collections.singletonMap("boot", mock(ReactiveHealthContributor.class)), + Arrays.asList("spring", "boot"))) + .withMessage("ReactiveHealthContributor with name \"boot\" clashes with group"); } @Test @@ -48,8 +48,8 @@ class AutoConfiguredReactiveHealthContributorRegistryTests { ReactiveHealthContributorRegistry registry = new AutoConfiguredReactiveHealthContributorRegistry( Collections.emptyMap(), Arrays.asList("spring", "boot")); assertThatIllegalStateException() - .isThrownBy(() -> registry.registerContributor("spring", mock(ReactiveHealthContributor.class))) - .withMessage("ReactiveHealthContributor with name \"spring\" clashes with group"); + .isThrownBy(() -> registry.registerContributor("spring", mock(ReactiveHealthContributor.class))) + .withMessage("ReactiveHealthContributor with name \"spring\" clashes with group"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthContributorAutoConfigurationTests.java index 78e7fa9b03..42a30bca3c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,34 +37,34 @@ import static org.assertj.core.api.Assertions.assertThat; class HealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class)); @Test void runWhenNoOtherIndicatorsCreatesPingHealthIndicator() { this.contextRunner.run((context) -> assertThat(context).getBean(HealthIndicator.class) - .isInstanceOf(PingHealthIndicator.class)); + .isInstanceOf(PingHealthIndicator.class)); } @Test void runWhenHasDefinedIndicatorCreatesPingHealthIndicator() { this.contextRunner.withUserConfiguration(CustomHealthIndicatorConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(PingHealthIndicator.class) - .hasSingleBean(CustomHealthIndicator.class)); + .run((context) -> assertThat(context).hasSingleBean(PingHealthIndicator.class) + .hasSingleBean(CustomHealthIndicator.class)); } @Test void runWhenHasDefaultsDisabledDoesNotCreatePingHealthIndicator() { this.contextRunner.withUserConfiguration(CustomHealthIndicatorConfiguration.class) - .withPropertyValues("management.health.defaults.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(HealthIndicator.class)); + .withPropertyValues("management.health.defaults.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(HealthIndicator.class)); } @Test void runWhenHasDefaultsDisabledAndPingIndicatorEnabledCreatesPingHealthIndicator() { this.contextRunner.withUserConfiguration(CustomHealthIndicatorConfiguration.class) - .withPropertyValues("management.health.defaults.enabled:false", "management.health.ping.enabled:true") - .run((context) -> assertThat(context).hasSingleBean(PingHealthIndicator.class)); + .withPropertyValues("management.health.defaults.enabled:false", "management.health.ping.enabled:true") + .run((context) -> assertThat(context).hasSingleBean(PingHealthIndicator.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointAutoConfigurationTests.java index 332077f140..0fa0520945 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,14 +71,15 @@ import static org.mockito.Mockito.mock; class HealthEndpointAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withUserConfiguration(HealthIndicatorsConfiguration.class).withConfiguration(AutoConfigurations - .of(HealthContributorAutoConfiguration.class, HealthEndpointAutoConfiguration.class)); + .withUserConfiguration(HealthIndicatorsConfiguration.class) + .withConfiguration( + AutoConfigurations.of(HealthContributorAutoConfiguration.class, HealthEndpointAutoConfiguration.class)); private final ReactiveWebApplicationContextRunner reactiveContextRunner = new ReactiveWebApplicationContextRunner() - .withUserConfiguration(HealthIndicatorsConfiguration.class) - .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - EndpointAutoConfiguration.class)); + .withUserConfiguration(HealthIndicatorsConfiguration.class) + .withConfiguration( + AutoConfigurations.of(HealthContributorAutoConfiguration.class, HealthEndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, EndpointAutoConfiguration.class)); @Test void runWhenHealthEndpointIsDisabledDoesNotCreateBeans() { @@ -105,28 +106,30 @@ class HealthEndpointAutoConfigurationTests { @Test void runWhenHasStatusAggregatorBeanIgnoresProperties() { this.contextRunner.withUserConfiguration(StatusAggregatorConfiguration.class) - .withPropertyValues("management.endpoint.health.status.order=up,down").run((context) -> { - StatusAggregator aggregator = context.getBean(StatusAggregator.class); - assertThat(aggregator.getAggregateStatus(Status.UP, Status.DOWN)).isEqualTo(Status.UNKNOWN); - }); + .withPropertyValues("management.endpoint.health.status.order=up,down") + .run((context) -> { + StatusAggregator aggregator = context.getBean(StatusAggregator.class); + assertThat(aggregator.getAggregateStatus(Status.UP, Status.DOWN)).isEqualTo(Status.UNKNOWN); + }); } @Test void runCreatesHttpCodeStatusMapperFromProperties() { this.contextRunner.withPropertyValues("management.endpoint.health.status.http-mapping.up=123") - .run((context) -> { - HttpCodeStatusMapper mapper = context.getBean(HttpCodeStatusMapper.class); - assertThat(mapper.getStatusCode(Status.UP)).isEqualTo(123); - }); + .run((context) -> { + HttpCodeStatusMapper mapper = context.getBean(HttpCodeStatusMapper.class); + assertThat(mapper.getStatusCode(Status.UP)).isEqualTo(123); + }); } @Test void runWhenHasHttpCodeStatusMapperBeanIgnoresProperties() { this.contextRunner.withUserConfiguration(HttpCodeStatusMapperConfiguration.class) - .withPropertyValues("management.endpoint.health.status.http-mapping.up=123").run((context) -> { - HttpCodeStatusMapper mapper = context.getBean(HttpCodeStatusMapper.class); - assertThat(mapper.getStatusCode(Status.UP)).isEqualTo(456); - }); + .withPropertyValues("management.endpoint.health.status.http-mapping.up=123") + .run((context) -> { + HttpCodeStatusMapper mapper = context.getBean(HttpCodeStatusMapper.class); + assertThat(mapper.getStatusCode(Status.UP)).isEqualTo(456); + }); } @Test @@ -141,10 +144,11 @@ class HealthEndpointAutoConfigurationTests { @Test void runWhenHasHealthEndpointGroupsBeanDoesNotCreateAdditionalHealthEndpointGroups() { this.contextRunner.withUserConfiguration(HealthEndpointGroupsConfiguration.class) - .withPropertyValues("management.endpoint.health.group.ready.include=*").run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - assertThat(groups.getNames()).containsOnly("mock"); - }); + .withPropertyValues("management.endpoint.health.group.ready.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + assertThat(groups.getNames()).containsOnly("mock"); + }); } @Test @@ -204,12 +208,11 @@ class HealthEndpointAutoConfigurationTests { @Test void runWhenHasReactiveHealthContributorRegistryBeanDoesNotCreateAdditionalReactiveHealthContributorRegistry() { this.reactiveContextRunner.withUserConfiguration(ReactiveHealthContributorRegistryConfiguration.class) - .run((context) -> { - ReactiveHealthContributorRegistry registry = context - .getBean(ReactiveHealthContributorRegistry.class); - Object[] names = registry.stream().map(NamedContributor::getName).toArray(); - assertThat(names).isEmpty(); - }); + .run((context) -> { + ReactiveHealthContributorRegistry registry = context.getBean(ReactiveHealthContributorRegistry.class); + Object[] names = registry.stream().map(NamedContributor::getName).toArray(); + assertThat(names).isEmpty(); + }); } @Test @@ -248,49 +251,53 @@ class HealthEndpointAutoConfigurationTests { @Test void runWhenHasReactiveHealthEndpointWebExtensionBeanDoesNotCreateExtraReactiveHealthEndpointWebExtension() { this.reactiveContextRunner.withUserConfiguration(ReactiveHealthEndpointWebExtensionConfiguration.class) - .run((context) -> { - ReactiveHealthEndpointWebExtension webExtension = context - .getBean(ReactiveHealthEndpointWebExtension.class); - Mono> response = webExtension.health(ApiVersion.V3, - WebServerNamespace.SERVER, SecurityContext.NONE, true, "simple"); - assertThat(response).isNull(); - }); + .run((context) -> { + ReactiveHealthEndpointWebExtension webExtension = context + .getBean(ReactiveHealthEndpointWebExtension.class); + Mono> response = webExtension.health(ApiVersion.V3, + WebServerNamespace.SERVER, SecurityContext.NONE, true, "simple"); + assertThat(response).isNull(); + }); } @Test void runWhenHasHealthEndpointGroupsPostProcessorPerformsProcessing() { - this.contextRunner.withPropertyValues("management.endpoint.health.group.ready.include=*").withUserConfiguration( - HealthEndpointGroupsConfiguration.class, TestHealthEndpointGroupsPostProcessor.class).run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> groups.get("test")) - .withMessage("postprocessed"); - }); + this.contextRunner.withPropertyValues("management.endpoint.health.group.ready.include=*") + .withUserConfiguration(HealthEndpointGroupsConfiguration.class, TestHealthEndpointGroupsPostProcessor.class) + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> groups.get("test")) + .withMessage("postprocessed"); + }); } @Test void runWithIndicatorsInParentContextFindsIndicators() { new ApplicationContextRunner().withUserConfiguration(HealthIndicatorsConfiguration.class) - .run((parent) -> new WebApplicationContextRunner().withConfiguration(AutoConfigurations - .of(HealthContributorAutoConfiguration.class, HealthEndpointAutoConfiguration.class)) - .withParent(parent).run((context) -> { - HealthComponent health = context.getBean(HealthEndpoint.class).health(); - Map components = ((SystemHealth) health).getComponents(); - assertThat(components).containsKeys("additional", "ping", "simple"); - })); + .run((parent) -> new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, + HealthEndpointAutoConfiguration.class)) + .withParent(parent) + .run((context) -> { + HealthComponent health = context.getBean(HealthEndpoint.class).health(); + Map components = ((SystemHealth) health).getComponents(); + assertThat(components).containsKeys("additional", "ping", "simple"); + })); } @Test void runWithReactiveContextAndIndicatorsInParentContextFindsIndicators() { new ApplicationContextRunner().withUserConfiguration(HealthIndicatorsConfiguration.class) - .run((parent) -> new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - EndpointAutoConfiguration.class)) - .withParent(parent).run((context) -> { - HealthComponent health = context.getBean(HealthEndpoint.class).health(); - Map components = ((SystemHealth) health).getComponents(); - assertThat(components).containsKeys("additional", "ping", "simple"); - })); + .run((parent) -> new ReactiveWebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, + HealthEndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + EndpointAutoConfiguration.class)) + .withParent(parent) + .run((context) -> { + HealthComponent health = context.getBean(HealthEndpoint.class).health(); + Map components = ((SystemHealth) health).getComponents(); + assertThat(components).containsKeys("additional", "ping", "simple"); + })); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/influx/InfluxDbHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/influx/InfluxDbHealthContributorAutoConfigurationTests.java index dacea343e2..4ed923d504 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/influx/InfluxDbHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/influx/InfluxDbHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,9 @@ import static org.mockito.Mockito.mock; class InfluxDbHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withBean(InfluxDB.class, () -> mock(InfluxDB.class)).withConfiguration(AutoConfigurations - .of(InfluxDbHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withBean(InfluxDB.class, () -> mock(InfluxDB.class)) + .withConfiguration(AutoConfigurations.of(InfluxDbHealthContributorAutoConfiguration.class, + HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { @@ -46,7 +47,7 @@ class InfluxDbHealthContributorAutoConfigurationTests { @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.influxdb.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(InfluxDbHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(InfluxDbHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfigurationTests.java index faa2f8befe..0e15c48a1d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,12 +48,12 @@ import static org.assertj.core.api.Assertions.assertThat; class InfoContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(InfoContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(InfoContributorAutoConfiguration.class)); @Test void envContributor() { this.contextRunner.withPropertyValues("management.info.env.enabled=true") - .run((context) -> assertThat(context).hasSingleBean(EnvironmentInfoContributor.class)); + .run((context) -> assertThat(context).hasSingleBean(EnvironmentInfoContributor.class)); } @Test @@ -64,16 +64,16 @@ class InfoContributorAutoConfigurationTests { @Test void defaultInfoContributorsEnabledWithPrerequisitesInPlace() { this.contextRunner.withUserConfiguration(GitPropertiesConfiguration.class, BuildPropertiesConfiguration.class) - .run((context) -> assertThat(context.getBeansOfType(InfoContributor.class)).hasSize(2) - .satisfies((contributors) -> assertThat(contributors.values()) - .hasOnlyElementsOfTypes(BuildInfoContributor.class, GitInfoContributor.class))); + .run((context) -> assertThat(context.getBeansOfType(InfoContributor.class)).hasSize(2) + .satisfies((contributors) -> assertThat(contributors.values()) + .hasOnlyElementsOfTypes(BuildInfoContributor.class, GitInfoContributor.class))); } @Test void defaultInfoContributorsDisabledWithPrerequisitesInPlace() { this.contextRunner.withUserConfiguration(GitPropertiesConfiguration.class, BuildPropertiesConfiguration.class) - .withPropertyValues("management.info.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(InfoContributor.class)); + .withPropertyValues("management.info.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(InfoContributor.class)); } @Test @@ -101,15 +101,16 @@ class InfoContributorAutoConfigurationTests { @Test void gitPropertiesFullMode() { this.contextRunner.withPropertyValues("management.info.git.mode=full") - .withUserConfiguration(GitPropertiesConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(GitInfoContributor.class); - Map content = invokeContributor(context.getBean(GitInfoContributor.class)); - Object git = content.get("git"); - assertThat(git).isInstanceOf(Map.class); - Map gitInfo = (Map) git; - assertThat(gitInfo).containsOnlyKeys("branch", "commit", "foo"); - assertThat(gitInfo.get("foo")).isEqualTo("bar"); - }); + .withUserConfiguration(GitPropertiesConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(GitInfoContributor.class); + Map content = invokeContributor(context.getBean(GitInfoContributor.class)); + Object git = content.get("git"); + assertThat(git).isInstanceOf(Map.class); + Map gitInfo = (Map) git; + assertThat(gitInfo).containsOnlyKeys("branch", "commit", "foo"); + assertThat(gitInfo.get("foo")).isEqualTo("bar"); + }); } @Test @@ -139,7 +140,7 @@ class InfoContributorAutoConfigurationTests { this.contextRunner.withUserConfiguration(CustomBuildInfoContributorConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(BuildInfoContributor.class); assertThat(context.getBean(BuildInfoContributor.class)) - .isSameAs(context.getBean("customBuildInfoContributor")); + .isSameAs(context.getBean("customBuildInfoContributor")); }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfigurationTests.java index 79a10f45f2..fdf1d7a181 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,12 +32,12 @@ import static org.assertj.core.api.Assertions.assertThat; class InfoEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(InfoEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(InfoEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=info") - .run((context) -> assertThat(context).hasSingleBean(InfoEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(InfoEndpoint.class)); } @Test @@ -48,7 +48,7 @@ class InfoEndpointAutoConfigurationTests { @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.info.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(InfoEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(InfoEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfigurationTests.java index 4e2fb0ab38..a67d7bf9db 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,13 +36,13 @@ import static org.assertj.core.api.Assertions.assertThat; class IntegrationGraphEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class, - IntegrationGraphEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class, + IntegrationGraphEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=integrationgraph") - .run((context) -> assertThat(context).hasSingleBean(IntegrationGraphEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(IntegrationGraphEndpoint.class)); } @Test @@ -64,7 +64,7 @@ class IntegrationGraphEndpointAutoConfigurationTests { @Test void runWhenSpringIntegrationIsNotEnabledShouldNotHaveEndpointBean() { ApplicationContextRunner noSpringIntegrationRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(IntegrationGraphEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(IntegrationGraphEndpointAutoConfiguration.class)); noSpringIntegrationRunner.run((context) -> { assertThat(context).doesNotHaveBean(IntegrationGraphEndpoint.class); assertThat(context).doesNotHaveBean(IntegrationGraphServer.class); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/AbstractHealthEndpointAdditionalPathIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/AbstractHealthEndpointAdditionalPathIntegrationTests.java index e07687f90e..5e31018325 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/AbstractHealthEndpointAdditionalPathIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/AbstractHealthEndpointAdditionalPathIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,46 +46,52 @@ abstract class AbstractHealthEndpointAdditionalPathIntegrationTests client.get().uri("/healthz").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isNotFound(), "local.server.port")); + .withPropertyValues("spring.jmx.enabled=true", "management.endpoints.web.exposure.exclude=health", + "management.server.port=0", "management.endpoint.health.group.live.include=diskSpace", + "management.endpoint.health.group.live.additional-path=server:healthz", + "management.endpoint.health.group.live.show-components=always") + .run(withWebTestClient((client) -> client.get() + .uri("/healthz") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isNotFound(), "local.server.port")); } @Test @@ -94,25 +100,42 @@ abstract class AbstractHealthEndpointAdditionalPathIntegrationTests client.get().uri("/healthz").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isNotFound(), "local.server.port")); + .run(withWebTestClient((client) -> client.get() + .uri("/healthz") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isNotFound(), "local.server.port")); } @Test void groupsAreNotConfiguredWhenHealthEndpointIsNotExposedWithDifferentManagementPortAndCloudFoundryPlatform() { this.runner - .withPropertyValues("spring.jmx.enabled=true", "management.endpoints.web.exposure.exclude=health", - "spring.main.cloud-platform=cloud_foundry", "management.server.port=0", - "management.endpoint.health.group.live.include=diskSpace", - "management.endpoint.health.group.live.additional-path=server:healthz", - "management.endpoint.health.group.live.show-components=always") - .run(withWebTestClient((client) -> client.get().uri("/healthz").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isNotFound(), "local.server.port")); + .withPropertyValues("spring.jmx.enabled=true", "management.endpoints.web.exposure.exclude=health", + "spring.main.cloud-platform=cloud_foundry", "management.server.port=0", + "management.endpoint.health.group.live.include=diskSpace", + "management.endpoint.health.group.live.additional-path=server:healthz", + "management.endpoint.health.group.live.show-components=always") + .run(withWebTestClient((client) -> client.get() + .uri("/healthz") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isNotFound(), "local.server.port")); } private void testResponse(WebTestClient client) { - client.get().uri("/healthz").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("status").isEqualTo("UP").jsonPath("components.diskSpace").exists(); + client.get() + .uri("/healthz") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("status") + .isEqualTo("UP") + .jsonPath("components.diskSpace") + .exists(); } private ContextConsumer withWebTestClient(Consumer consumer, String property) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebFluxIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebFluxIntegrationTests.java index 442ad7dff8..884d7bda46 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebFluxIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebFluxIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,7 +58,7 @@ class ControllerEndpointWebFluxIntegrationTests { @Test void endpointsCanBeAccessed() { TestSecurityContextHolder.getContext() - .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); + .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); this.context = new AnnotationConfigReactiveWebApplicationContext(); this.context.register(DefaultConfiguration.class, ExampleController.class); TestPropertyValues.of("management.endpoints.web.exposure.include=*").applyTo(this.context); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebMvcIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebMvcIntegrationTests.java index 98187bed94..7c9c7b8f93 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebMvcIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebMvcIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,18 +74,18 @@ class ControllerEndpointWebMvcIntegrationTests { this.context.register(SecureConfiguration.class, ExampleController.class); MockMvc mockMvc = createSecureMockMvc(); mockMvc.perform(get("/actuator/example").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isUnauthorized()); + .andExpect(status().isUnauthorized()); } @Test void endpointsCanBeAccessed() throws Exception { TestSecurityContextHolder.getContext() - .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); + .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); this.context = new AnnotationConfigServletWebApplicationContext(); this.context.register(SecureConfiguration.class, ExampleController.class); TestPropertyValues - .of("management.endpoints.web.base-path:/management", "management.endpoints.web.exposure.include=*") - .applyTo(this.context); + .of("management.endpoints.web.base-path:/management", "management.endpoints.web.exposure.include=*") + .applyTo(this.context); MockMvc mockMvc = createSecureMockMvc(); mockMvc.perform(get("/management/example")).andExpect(status().isOk()); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyEndpointIntegrationTests.java index c60196cebf..2bea402663 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,14 +60,17 @@ class JerseyEndpointIntegrationTests { @Test void linksPageIsNotAvailableWhenDisabled() { getContextRunner(new Class[] { EndpointsConfiguration.class, ResourceConfigConfiguration.class }) - .withPropertyValues("management.endpoints.web.discovery.enabled:false").run((context) -> { - int port = context - .getSourceApplicationContext(AnnotationConfigServletWebServerApplicationContext.class) - .getWebServer().getPort(); - WebTestClient client = WebTestClient.bindToServer().baseUrl("http://localhost:" + port) - .responseTimeout(Duration.ofMinutes(5)).build(); - client.get().uri("/actuator").exchange().expectStatus().isNotFound(); - }); + .withPropertyValues("management.endpoints.web.discovery.enabled:false") + .run((context) -> { + int port = context.getSourceApplicationContext(AnnotationConfigServletWebServerApplicationContext.class) + .getWebServer() + .getPort(); + WebTestClient client = WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port) + .responseTimeout(Duration.ofMinutes(5)) + .build(); + client.get().uri("/actuator").exchange().expectStatus().isNotFound(); + }); } @Test @@ -82,9 +85,12 @@ class JerseyEndpointIntegrationTests { getAutoconfigurations(SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class)); contextRunner.run((context) -> { int port = context.getSourceApplicationContext(AnnotationConfigServletWebServerApplicationContext.class) - .getWebServer().getPort(); - WebTestClient client = WebTestClient.bindToServer().baseUrl("http://localhost:" + port) - .responseTimeout(Duration.ofMinutes(5)).build(); + .getWebServer() + .getPort(); + WebTestClient client = WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port) + .responseTimeout(Duration.ofMinutes(5)) + .build(); client.get().uri("/actuator").exchange().expectStatus().isUnauthorized(); }); @@ -93,12 +99,24 @@ class JerseyEndpointIntegrationTests { protected void testJerseyEndpoints(Class[] userConfigurations) { getContextRunner(userConfigurations).run((context) -> { int port = context.getSourceApplicationContext(AnnotationConfigServletWebServerApplicationContext.class) - .getWebServer().getPort(); - WebTestClient client = WebTestClient.bindToServer().baseUrl("http://localhost:" + port) - .responseTimeout(Duration.ofMinutes(5)).build(); - client.get().uri("/actuator").exchange().expectStatus().isOk().expectBody().jsonPath("_links.beans") - .isNotEmpty().jsonPath("_links.restcontroller").doesNotExist().jsonPath("_links.controller") - .doesNotExist(); + .getWebServer() + .getPort(); + WebTestClient client = WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port) + .responseTimeout(Duration.ofMinutes(5)) + .build(); + client.get() + .uri("/actuator") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("_links.beans") + .isNotEmpty() + .jsonPath("_links.restcontroller") + .doesNotExist() + .jsonPath("_links.controller") + .doesNotExist(); }); } @@ -106,10 +124,10 @@ class JerseyEndpointIntegrationTests { Class... additionalAutoConfigurations) { FilteredClassLoader classLoader = new FilteredClassLoader(DispatcherServlet.class); return new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withClassLoader(classLoader) - .withConfiguration(AutoConfigurations.of(getAutoconfigurations(additionalAutoConfigurations))) - .withUserConfiguration(userConfigurations) - .withPropertyValues("management.endpoints.web.exposure.include:*", "server.port:0"); + .withClassLoader(classLoader) + .withConfiguration(AutoConfigurations.of(getAutoconfigurations(additionalAutoConfigurations))) + .withUserConfiguration(userConfigurations) + .withPropertyValues("management.endpoints.web.exposure.include:*", "server.port:0"); } private Class[] getAutoconfigurations(Class... additional) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyHealthEndpointAdditionalPathIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyHealthEndpointAdditionalPathIntegrationTests.java index aa9f9ce0d2..e995ddfd0e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyHealthEndpointAdditionalPathIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyHealthEndpointAdditionalPathIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,13 +44,14 @@ class JerseyHealthEndpointAdditionalPathIntegrationTests extends JerseyHealthEndpointAdditionalPathIntegrationTests() { super(new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, JerseyAutoConfiguration.class, - EndpointAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, - WebEndpointAutoConfiguration.class, JerseyAutoConfiguration.class, - ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, DiskSpaceHealthContributorAutoConfiguration.class)) - .withInitializer(new ServerPortInfoApplicationContextInitializer()) - .withClassLoader(new FilteredClassLoader(DispatcherServlet.class)).withPropertyValues("server.port=0")); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, JerseyAutoConfiguration.class, + EndpointAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, + WebEndpointAutoConfiguration.class, JerseyAutoConfiguration.class, + ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, + HealthEndpointAutoConfiguration.class, DiskSpaceHealthContributorAutoConfiguration.class)) + .withInitializer(new ServerPortInfoApplicationContextInitializer()) + .withClassLoader(new FilteredClassLoader(DispatcherServlet.class)) + .withPropertyValues("server.port=0")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JmxEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JmxEndpointIntegrationTests.java index 1db1217918..9c7b3c0cea 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JmxEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JmxEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,12 +51,12 @@ import static org.assertj.core.api.Assertions.assertThat; class JmxEndpointIntegrationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, EndpointAutoConfiguration.class, - JmxEndpointAutoConfiguration.class, HealthContributorAutoConfiguration.class, - HttpTraceAutoConfiguration.class)) - .withUserConfiguration(HttpTraceRepositoryConfiguration.class, AuditEventRepositoryConfiguration.class) - .withPropertyValues("spring.jmx.enabled=true") - .withConfiguration(AutoConfigurations.of(EndpointAutoConfigurationClasses.ALL)); + .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, EndpointAutoConfiguration.class, + JmxEndpointAutoConfiguration.class, HealthContributorAutoConfiguration.class, + HttpTraceAutoConfiguration.class)) + .withUserConfiguration(HttpTraceRepositoryConfiguration.class, AuditEventRepositoryConfiguration.class) + .withPropertyValues("spring.jmx.enabled=true") + .withConfiguration(AutoConfigurations.of(EndpointAutoConfigurationClasses.ALL)); @Test void jmxEndpointsAreExposed() { @@ -69,12 +69,13 @@ class JmxEndpointIntegrationTests { @Test void jmxEndpointsAreExposedWhenLazyInitializationIsEnabled() { - this.contextRunner.withBean(LazyInitializationBeanFactoryPostProcessor.class, - LazyInitializationBeanFactoryPostProcessor::new).run((context) -> { - MBeanServer mBeanServer = context.getBean(MBeanServer.class); - checkEndpointMBeans(mBeanServer, new String[] { "beans", "conditions", "configprops", "env", - "health", "info", "mappings", "threaddump", "httptrace" }, new String[] { "shutdown" }); - }); + this.contextRunner + .withBean(LazyInitializationBeanFactoryPostProcessor.class, LazyInitializationBeanFactoryPostProcessor::new) + .run((context) -> { + MBeanServer mBeanServer = context.getBean(MBeanServer.class); + checkEndpointMBeans(mBeanServer, new String[] { "beans", "conditions", "configprops", "env", "health", + "info", "mappings", "threaddump", "httptrace" }, new String[] { "shutdown" }); + }); } @Test @@ -99,11 +100,13 @@ class JmxEndpointIntegrationTests { private void checkEndpointMBeans(MBeanServer mBeanServer, String[] enabledEndpoints, String[] disabledEndpoints) { for (String enabledEndpoint : enabledEndpoints) { assertThat(isRegistered(mBeanServer, getDefaultObjectName(enabledEndpoint))) - .as(String.format("Endpoint %s", enabledEndpoint)).isTrue(); + .as(String.format("Endpoint %s", enabledEndpoint)) + .isTrue(); } for (String disabledEndpoint : disabledEndpoints) { assertThat(isRegistered(mBeanServer, getDefaultObjectName(disabledEndpoint))) - .as(String.format("Endpoint %s", disabledEndpoint)).isFalse(); + .as(String.format("Endpoint %s", disabledEndpoint)) + .isFalse(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JolokiaEndpointAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JolokiaEndpointAutoConfigurationIntegrationTests.java index 74ba6b3d44..1e8bf46fdd 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JolokiaEndpointAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JolokiaEndpointAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -90,7 +90,7 @@ class JolokiaEndpointAutoConfigurationIntegrationTests { @Test void list() { ResponseEntity response = this.restTemplate - .getForEntity("/actuator/jolokia/list/java.lang/type=Memory/attr", String.class); + .getForEntity("/actuator/jolokia/list/java.lang/type=Memory/attr", String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(response.getBody()).contains("NonHeapMemoryUsage"); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebEndpointsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebEndpointsAutoConfigurationIntegrationTests.java index 1c95dff9de..69a6e7b85a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebEndpointsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebEndpointsAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,17 +62,17 @@ class WebEndpointsAutoConfigurationIntegrationTests { @Test void healthEndpointReactiveWebExtensionIsAutoConfigured() { reactiveWebRunner() - .run((context) -> assertThat(context).hasSingleBean(ReactiveHealthEndpointWebExtension.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveHealthEndpointWebExtension.class)); } private WebApplicationContextRunner servletWebRunner() { return new WebApplicationContextRunner() - .withConfiguration(UserConfigurations.of(WebEndpointTestApplication.class)); + .withConfiguration(UserConfigurations.of(WebEndpointTestApplication.class)); } private ReactiveWebApplicationContextRunner reactiveWebRunner() { return new ReactiveWebApplicationContextRunner() - .withConfiguration(UserConfigurations.of(WebEndpointTestApplication.class)); + .withConfiguration(UserConfigurations.of(WebEndpointTestApplication.class)); } @EnableAutoConfiguration(exclude = { FlywayAutoConfiguration.class, LiquibaseAutoConfiguration.class, diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointCorsIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointCorsIntegrationTests.java index 2cb180b832..c04d88d360 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointCorsIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointCorsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,126 +47,168 @@ import org.springframework.test.web.reactive.server.WebTestClient; class WebFluxEndpointCorsIntegrationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, - WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class, - ReactiveManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class)) - .withPropertyValues("management.endpoints.web.exposure.include:*"); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, + WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ReactiveManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class)) + .withPropertyValues("management.endpoints.web.exposure.include:*"); @Test void corsIsDisabledByDefault() { - this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") - .header("Origin", "spring.example.org").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") - .exchange().expectHeader().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.options() + .uri("/actuator/beans") + .header("Origin", "spring.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .exchange() + .expectHeader() + .doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN))); } @Test void settingAllowedOriginsEnablesCors() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") - .run(withWebTestClient((webTestClient) -> { - webTestClient.options().uri("/actuator/beans").header("Origin", "test.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").exchange().expectStatus() - .isForbidden(); - performAcceptedCorsRequest(webTestClient, "/actuator/beans"); - })); + .run(withWebTestClient((webTestClient) -> { + webTestClient.options() + .uri("/actuator/beans") + .header("Origin", "test.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .exchange() + .expectStatus() + .isForbidden(); + performAcceptedCorsRequest(webTestClient, "/actuator/beans"); + })); } @Test void settingAllowedOriginPatternsEnablesCors() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origin-patterns:*.example.org", - "management.endpoints.web.cors.allow-credentials:true") - .run(withWebTestClient((webTestClient) -> { - webTestClient.options().uri("/actuator/beans").header("Origin", "spring.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").exchange().expectStatus() - .isForbidden(); - performAcceptedCorsRequest(webTestClient, "/actuator/beans"); - })); + .withPropertyValues("management.endpoints.web.cors.allowed-origin-patterns:*.example.org", + "management.endpoints.web.cors.allow-credentials:true") + .run(withWebTestClient((webTestClient) -> { + webTestClient.options() + .uri("/actuator/beans") + .header("Origin", "spring.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .exchange() + .expectStatus() + .isForbidden(); + performAcceptedCorsRequest(webTestClient, "/actuator/beans"); + })); } @Test void maxAgeDefaultsTo30Minutes() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") - .run(withWebTestClient((webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans") - .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"))); + .run(withWebTestClient( + (webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans").expectHeader() + .valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"))); } @Test void maxAgeCanBeConfigured() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.max-age: 2400") - .run(withWebTestClient((webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans") - .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "2400"))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.max-age: 2400") + .run(withWebTestClient( + (webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans").expectHeader() + .valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "2400"))); } @Test void requestsWithDisallowedHeadersAreRejected() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") - .run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") - .header("Origin", "spring.example.org").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha").exchange().expectStatus() - .isForbidden())); + .run(withWebTestClient((webTestClient) -> webTestClient.options() + .uri("/actuator/beans") + .header("Origin", "spring.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha") + .exchange() + .expectStatus() + .isForbidden())); } @Test void allowedHeadersCanBeConfigured() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.allowed-headers:Alpha,Bravo") - .run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") - .header("Origin", "spring.example.org").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha").exchange().expectStatus().isOk() - .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Alpha"))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.allowed-headers:Alpha,Bravo") + .run(withWebTestClient((webTestClient) -> webTestClient.options() + .uri("/actuator/beans") + .header("Origin", "spring.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Alpha"))); } @Test void requestsWithDisallowedMethodsAreRejected() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") - .run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") - .header("Origin", "spring.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH").exchange().expectStatus() - .isForbidden())); + .run(withWebTestClient((webTestClient) -> webTestClient.options() + .uri("/actuator/beans") + .header("Origin", "spring.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH") + .exchange() + .expectStatus() + .isForbidden())); } @Test void allowedMethodsCanBeConfigured() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.allowed-methods:GET,HEAD") - .run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") - .header("Origin", "spring.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "HEAD").exchange().expectStatus().isOk() - .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD"))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.allowed-methods:GET,HEAD") + .run(withWebTestClient((webTestClient) -> webTestClient.options() + .uri("/actuator/beans") + .header("Origin", "spring.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "HEAD") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD"))); } @Test void credentialsCanBeAllowed() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.allow-credentials:true") - .run(withWebTestClient((webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans") - .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.allow-credentials:true") + .run(withWebTestClient( + (webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans").expectHeader() + .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"))); } @Test void credentialsCanBeDisabled() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.allow-credentials:false") - .run(withWebTestClient((webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans") - .expectHeader().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.allow-credentials:false") + .run(withWebTestClient( + (webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans").expectHeader() + .doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS))); } private ContextConsumer withWebTestClient(Consumer webTestClient) { - return (context) -> webTestClient.accept(WebTestClient.bindToApplicationContext(context).configureClient() - .baseUrl("https://spring.example.org").build()); + return (context) -> webTestClient.accept(WebTestClient.bindToApplicationContext(context) + .configureClient() + .baseUrl("https://spring.example.org") + .build()); } private WebTestClient.ResponseSpec performAcceptedCorsRequest(WebTestClient webTestClient, String url) { - return webTestClient.options().uri(url).header(HttpHeaders.ORIGIN, "spring.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").exchange().expectHeader() - .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "spring.example.org").expectStatus().isOk(); + return webTestClient.options() + .uri(url) + .header(HttpHeaders.ORIGIN, "spring.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .exchange() + .expectHeader() + .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "spring.example.org") + .expectStatus() + .isOk(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointIntegrationTests.java index 65bf929442..6fb5600969 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,19 +44,28 @@ import org.springframework.test.web.reactive.server.WebTestClient; class WebFluxEndpointIntegrationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, - WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class, - ReactiveManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class)) - .withUserConfiguration(EndpointsConfiguration.class); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, + WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ReactiveManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class)) + .withUserConfiguration(EndpointsConfiguration.class); @Test void linksAreProvidedToAllEndpointTypes() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include:*").run((context) -> { WebTestClient client = createWebTestClient(context); - client.get().uri("/actuator").exchange().expectStatus().isOk().expectBody().jsonPath("_links.beans") - .isNotEmpty().jsonPath("_links.restcontroller").isNotEmpty().jsonPath("_links.controller") - .isNotEmpty(); + client.get() + .uri("/actuator") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("_links.beans") + .isNotEmpty() + .jsonPath("_links.restcontroller") + .isNotEmpty() + .jsonPath("_links.controller") + .isNotEmpty(); }); } @@ -69,8 +78,10 @@ class WebFluxEndpointIntegrationTests { } private WebTestClient createWebTestClient(ApplicationContext context) { - return WebTestClient.bindToApplicationContext(context).configureClient().baseUrl("https://spring.example.org") - .build(); + return WebTestClient.bindToApplicationContext(context) + .configureClient() + .baseUrl("https://spring.example.org") + .build(); } @ControllerEndpoint(id = "controller") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxHealthEndpointAdditionalPathIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxHealthEndpointAdditionalPathIntegrationTests.java index 9189dda05a..2010657947 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxHealthEndpointAdditionalPathIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxHealthEndpointAdditionalPathIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,14 +45,14 @@ class WebFluxHealthEndpointAdditionalPathIntegrationTests extends WebFluxHealthEndpointAdditionalPathIntegrationTests() { super(new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, - WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, - EndpointAutoConfiguration.class, HealthEndpointAutoConfiguration.class, - DiskSpaceHealthContributorAutoConfiguration.class, WebEndpointAutoConfiguration.class, - ManagementContextAutoConfiguration.class, ReactiveWebServerFactoryAutoConfiguration.class, - ReactiveManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class)) - .withInitializer(new ServerPortInfoApplicationContextInitializer()) - .withPropertyValues("server.port=0")); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, + WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, EndpointAutoConfiguration.class, + HealthEndpointAutoConfiguration.class, DiskSpaceHealthContributorAutoConfiguration.class, + WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ReactiveWebServerFactoryAutoConfiguration.class, ReactiveManagementContextAutoConfiguration.class, + BeansEndpointAutoConfiguration.class)) + .withInitializer(new ServerPortInfoApplicationContextInitializer()) + .withPropertyValues("server.port=0")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointCorsIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointCorsIntegrationTests.java index 0d063be271..9a0ee8a1b4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointCorsIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointCorsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,120 +51,125 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. class WebMvcEndpointCorsIntegrationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class)) - .withPropertyValues("management.endpoints.web.exposure.include:*"); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, + DispatcherServletAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ServletManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class)) + .withPropertyValues("management.endpoints.web.exposure.include:*"); @Test void corsIsDisabledByDefault() { this.contextRunner.run(withMockMvc((mockMvc) -> mockMvc - .perform(options("/actuator/beans").header("Origin", "foo.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) - .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)))); + .perform(options("/actuator/beans").header("Origin", "foo.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)))); } @Test void settingAllowedOriginsEnablesCors() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") - .run(withMockMvc((mockMvc) -> { - mockMvc.perform(options("/actuator/beans").header("Origin", "bar.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) - .andExpect(status().isForbidden()); - performAcceptedCorsRequest(mockMvc); - })); + .run(withMockMvc((mockMvc) -> { + mockMvc + .perform(options("/actuator/beans").header("Origin", "bar.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) + .andExpect(status().isForbidden()); + performAcceptedCorsRequest(mockMvc); + })); } @Test void settingAllowedOriginPatternsEnablesCors() { - this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origin-patterns:*.example.com", - "management.endpoints.web.cors.allow-credentials:true").run(withMockMvc((mockMvc) -> { - mockMvc.perform(options("/actuator/beans").header("Origin", "bar.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) - .andExpect(status().isForbidden()); - performAcceptedCorsRequest(mockMvc); - })); + this.contextRunner + .withPropertyValues("management.endpoints.web.cors.allowed-origin-patterns:*.example.com", + "management.endpoints.web.cors.allow-credentials:true") + .run(withMockMvc((mockMvc) -> { + mockMvc + .perform(options("/actuator/beans").header("Origin", "bar.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) + .andExpect(status().isForbidden()); + performAcceptedCorsRequest(mockMvc); + })); } @Test void maxAgeDefaultsTo30Minutes() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") - .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")))); + .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")))); } @Test void maxAgeCanBeConfigured() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", - "management.endpoints.web.cors.max-age: 2400") - .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "2400")))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", + "management.endpoints.web.cors.max-age: 2400") + .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "2400")))); } @Test void requestsWithDisallowedHeadersAreRejected() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") - .run(withMockMvc((mockMvc) -> + .run(withMockMvc((mockMvc) -> - mockMvc.perform(options("/actuator/beans").header("Origin", "foo.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha")) - .andExpect(status().isForbidden()))); + mockMvc + .perform(options("/actuator/beans").header("Origin", "foo.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha")) + .andExpect(status().isForbidden()))); } @Test void allowedHeadersCanBeConfigured() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", - "management.endpoints.web.cors.allowed-headers:Alpha,Bravo") - .run(withMockMvc((mockMvc) -> mockMvc - .perform(options("/actuator/beans").header("Origin", "foo.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha")) - .andExpect(status().isOk()) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Alpha")))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", + "management.endpoints.web.cors.allowed-headers:Alpha,Bravo") + .run(withMockMvc((mockMvc) -> mockMvc + .perform(options("/actuator/beans").header("Origin", "foo.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Alpha")))); } @Test void requestsWithDisallowedMethodsAreRejected() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") - .run(withMockMvc((mockMvc) -> mockMvc - .perform(options("/actuator/beans").header(HttpHeaders.ORIGIN, "foo.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH")) - .andExpect(status().isForbidden()))); + .run(withMockMvc((mockMvc) -> mockMvc + .perform(options("/actuator/beans").header(HttpHeaders.ORIGIN, "foo.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH")) + .andExpect(status().isForbidden()))); } @Test void allowedMethodsCanBeConfigured() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", - "management.endpoints.web.cors.allowed-methods:GET,HEAD") - .run(withMockMvc((mockMvc) -> mockMvc - .perform(options("/actuator/beans").header(HttpHeaders.ORIGIN, "foo.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "HEAD")) - .andExpect(status().isOk()) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD")))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", + "management.endpoints.web.cors.allowed-methods:GET,HEAD") + .run(withMockMvc((mockMvc) -> mockMvc + .perform(options("/actuator/beans").header(HttpHeaders.ORIGIN, "foo.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "HEAD")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD")))); } @Test void credentialsCanBeAllowed() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", - "management.endpoints.web.cors.allow-credentials:true") - .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", + "management.endpoints.web.cors.allow-credentials:true") + .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")))); } @Test void credentialsCanBeDisabled() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", - "management.endpoints.web.cors.allow-credentials:false") - .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) - .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", + "management.endpoints.web.cors.allow-credentials:false") + .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)))); } private ContextConsumer withMockMvc(MockMvcConsumer mockMvc) { @@ -177,10 +182,10 @@ class WebMvcEndpointCorsIntegrationTests { private ResultActions performAcceptedCorsRequest(MockMvc mockMvc, String url) throws Exception { return mockMvc - .perform(options(url).header(HttpHeaders.ORIGIN, "foo.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "foo.example.com")) - .andExpect(status().isOk()); + .perform(options(url).header(HttpHeaders.ORIGIN, "foo.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "foo.example.com")) + .andExpect(status().isOk()); } @FunctionalInterface diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointExposureIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointExposureIntegrationTests.java index fd8346d920..d301a52af9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointExposureIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointExposureIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,17 +69,17 @@ class WebMvcEndpointExposureIntegrationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ServletWebServerFactoryAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, - ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, - HttpTraceAutoConfiguration.class, HealthContributorAutoConfiguration.class)) - .withConfiguration(AutoConfigurations.of(EndpointAutoConfigurationClasses.ALL)) - .withUserConfiguration(CustomMvcEndpoint.class, CustomServletEndpoint.class, - HttpTraceRepositoryConfiguration.class, AuditEventRepositoryConfiguration.class) - .withPropertyValues("server.port:0"); + .withConfiguration(AutoConfigurations.of(ServletWebServerFactoryAutoConfiguration.class, + DispatcherServletAutoConfiguration.class, JacksonAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, + EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, + ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, + HttpTraceAutoConfiguration.class, HealthContributorAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(EndpointAutoConfigurationClasses.ALL)) + .withUserConfiguration(CustomMvcEndpoint.class, CustomServletEndpoint.class, + HttpTraceRepositoryConfiguration.class, AuditEventRepositoryConfiguration.class) + .withPropertyValues("server.port:0"); @Test void webEndpointsAreDisabledByDefault() { @@ -103,7 +103,7 @@ class WebMvcEndpointExposureIntegrationTests { @Test void webEndpointsCanBeExposed() { WebApplicationContextRunner contextRunner = this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=*"); + .withPropertyValues("management.endpoints.web.exposure.include=*"); contextRunner.run((context) -> { WebTestClient client = createClient(context); assertThat(isExposed(client, HttpMethod.GET, "beans")).isTrue(); @@ -124,7 +124,7 @@ class WebMvcEndpointExposureIntegrationTests { @Test void singleWebEndpointCanBeExposed() { WebApplicationContextRunner contextRunner = this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=beans"); + .withPropertyValues("management.endpoints.web.exposure.include=beans"); contextRunner.run((context) -> { WebTestClient client = createClient(context); assertThat(isExposed(client, HttpMethod.GET, "beans")).isTrue(); @@ -164,12 +164,17 @@ class WebMvcEndpointExposureIntegrationTests { } private WebTestClient createClient(AssertableWebApplicationContext context) { - int port = context.getSourceApplicationContext(ServletWebServerApplicationContext.class).getWebServer() - .getPort(); + int port = context.getSourceApplicationContext(ServletWebServerApplicationContext.class) + .getWebServer() + .getPort(); ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() - .codecs((configurer) -> configurer.defaultCodecs().maxInMemorySize(-1)).build(); - return WebTestClient.bindToServer().baseUrl("http://localhost:" + port).exchangeStrategies(exchangeStrategies) - .responseTimeout(Duration.ofMinutes(5)).build(); + .codecs((configurer) -> configurer.defaultCodecs().maxInMemorySize(-1)) + .build(); + return WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port) + .exchangeStrategies(exchangeStrategies) + .responseTimeout(Duration.ofMinutes(5)) + .build(); } private boolean isExposed(WebTestClient client, HttpMethod method, String path) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointIntegrationTests.java index afa442cc4f..683b32886f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -105,18 +105,18 @@ class WebMvcEndpointIntegrationTests { TestPropertyValues.of("management.endpoints.web.base-path:/management").applyTo(this.context); MockMvc mockMvc = createSecureMockMvc(); mockMvc.perform(get("/management/beans").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isUnauthorized()); + .andExpect(status().isUnauthorized()); } @Test void endpointsAreSecureWithActuatorRoleWithCustomBasePath() throws Exception { TestSecurityContextHolder.getContext() - .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); + .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); this.context = new AnnotationConfigServletWebApplicationContext(); this.context.register(SecureConfiguration.class); TestPropertyValues - .of("management.endpoints.web.base-path:/management", "management.endpoints.web.exposure.include=*") - .applyTo(this.context); + .of("management.endpoints.web.base-path:/management", "management.endpoints.web.exposure.include=*") + .applyTo(this.context); MockMvc mockMvc = createSecureMockMvc(); mockMvc.perform(get("/management/beans")).andExpect(status().isOk()); } @@ -127,8 +127,12 @@ class WebMvcEndpointIntegrationTests { this.context.register(DefaultConfiguration.class, EndpointsConfiguration.class); TestPropertyValues.of("management.endpoints.web.exposure.include=*").applyTo(this.context); MockMvc mockMvc = doCreateMockMvc(); - mockMvc.perform(get("/actuator").accept("*/*")).andExpect(status().isOk()).andExpect(jsonPath("_links", - both(hasKey("beans")).and(hasKey("servlet")).and(hasKey("restcontroller")).and(hasKey("controller")))); + mockMvc.perform(get("/actuator").accept("*/*")) + .andExpect(status().isOk()) + .andExpect(jsonPath("_links", + both(hasKey("beans")).and(hasKey("servlet")) + .and(hasKey("restcontroller")) + .and(hasKey("controller")))); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcHealthEndpointAdditionalPathIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcHealthEndpointAdditionalPathIntegrationTests.java index 03bc1904a2..1c2167bdbb 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcHealthEndpointAdditionalPathIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcHealthEndpointAdditionalPathIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,14 +44,14 @@ class WebMvcHealthEndpointAdditionalPathIntegrationTests extends WebMvcHealthEndpointAdditionalPathIntegrationTests() { super(new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, ManagementContextAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class, WebMvcAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, WebEndpointAutoConfiguration.class, - EndpointAutoConfiguration.class, DispatcherServletAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, DiskSpaceHealthContributorAutoConfiguration.class)) - .withInitializer(new ServerPortInfoApplicationContextInitializer()) - .withPropertyValues("server.port=0")); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class, WebMvcAutoConfiguration.class, + ServletManagementContextAutoConfiguration.class, WebEndpointAutoConfiguration.class, + EndpointAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + HealthEndpointAutoConfiguration.class, DiskSpaceHealthContributorAutoConfiguration.class)) + .withInitializer(new ServerPortInfoApplicationContextInitializer()) + .withPropertyValues("server.port=0")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfigurationTests.java index 8316f0acd9..6945cb71bb 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,8 @@ import static org.mockito.Mockito.mock; class DataSourceHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - HealthContributorAutoConfiguration.class, DataSourceHealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + HealthContributorAutoConfiguration.class, DataSourceHealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { @@ -68,33 +68,34 @@ class DataSourceHealthContributorAutoConfigurationTests { @Test void runWhenMultipleDataSourceBeansShouldCreateCompositeIndicator() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, DataSourceConfig.class) - .run((context) -> { - assertThat(context).hasSingleBean(CompositeHealthContributor.class); - CompositeHealthContributor contributor = context.getBean(CompositeHealthContributor.class); - String[] names = contributor.stream().map(NamedContributor::getName).toArray(String[]::new); - assertThat(names).containsExactlyInAnyOrder("dataSource", "testDataSource"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(CompositeHealthContributor.class); + CompositeHealthContributor contributor = context.getBean(CompositeHealthContributor.class); + String[] names = contributor.stream().map(NamedContributor::getName).toArray(String[]::new); + assertThat(names).containsExactlyInAnyOrder("dataSource", "testDataSource"); + }); } @Test void runWithRoutingAndEmbeddedDataSourceShouldIncludeRoutingDataSource() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, RoutingDataSourceConfig.class) - .run((context) -> { - CompositeHealthContributor composite = context.getBean(CompositeHealthContributor.class); - assertThat(composite.getContributor("dataSource")).isInstanceOf(DataSourceHealthIndicator.class); - assertThat(composite.getContributor("routingDataSource")) - .isInstanceOf(RoutingDataSourceHealthContributor.class); - }); + .run((context) -> { + CompositeHealthContributor composite = context.getBean(CompositeHealthContributor.class); + assertThat(composite.getContributor("dataSource")).isInstanceOf(DataSourceHealthIndicator.class); + assertThat(composite.getContributor("routingDataSource")) + .isInstanceOf(RoutingDataSourceHealthContributor.class); + }); } @Test void runWithRoutingAndEmbeddedDataSourceShouldNotIncludeRoutingDataSourceWhenIgnored() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, RoutingDataSourceConfig.class) - .withPropertyValues("management.health.db.ignore-routing-datasources:true").run((context) -> { - assertThat(context).doesNotHaveBean(CompositeHealthContributor.class); - assertThat(context).hasSingleBean(DataSourceHealthIndicator.class); - assertThat(context).doesNotHaveBean(RoutingDataSourceHealthContributor.class); - }); + .withPropertyValues("management.health.db.ignore-routing-datasources:true") + .run((context) -> { + assertThat(context).doesNotHaveBean(CompositeHealthContributor.class); + assertThat(context).hasSingleBean(DataSourceHealthIndicator.class); + assertThat(context).doesNotHaveBean(RoutingDataSourceHealthContributor.class); + }); } @Test @@ -102,39 +103,42 @@ class DataSourceHealthContributorAutoConfigurationTests { this.contextRunner.withUserConfiguration(RoutingDataSourceConfig.class).run((context) -> { assertThat(context).hasSingleBean(RoutingDataSourceHealthContributor.class); RoutingDataSourceHealthContributor routingHealthContributor = context - .getBean(RoutingDataSourceHealthContributor.class); + .getBean(RoutingDataSourceHealthContributor.class); assertThat(routingHealthContributor.getContributor("one")).isInstanceOf(DataSourceHealthIndicator.class); assertThat(routingHealthContributor.getContributor("two")).isInstanceOf(DataSourceHealthIndicator.class); - assertThat(routingHealthContributor.iterator()).toIterable().extracting("name") - .containsExactlyInAnyOrder("one", "two"); + assertThat(routingHealthContributor.iterator()).toIterable() + .extracting("name") + .containsExactlyInAnyOrder("one", "two"); }); } @Test void runWithOnlyRoutingDataSourceShouldCrashWhenIgnored() { this.contextRunner.withUserConfiguration(RoutingDataSourceConfig.class) - .withPropertyValues("management.health.db.ignore-routing-datasources:true") - .run((context) -> assertThat(context).hasFailed().getFailure() - .hasRootCauseInstanceOf(IllegalArgumentException.class)); + .withPropertyValues("management.health.db.ignore-routing-datasources:true") + .run((context) -> assertThat(context).hasFailed() + .getFailure() + .hasRootCauseInstanceOf(IllegalArgumentException.class)); } @Test void runWithValidationQueryPropertyShouldUseCustomQuery() { this.contextRunner - .withUserConfiguration(DataSourceConfig.class, DataSourcePoolMetadataProvidersConfiguration.class) - .withPropertyValues("spring.datasource.test.validation-query:SELECT from FOOBAR").run((context) -> { - assertThat(context).hasSingleBean(DataSourceHealthIndicator.class); - DataSourceHealthIndicator indicator = context.getBean(DataSourceHealthIndicator.class); - assertThat(indicator.getQuery()).isEqualTo("SELECT from FOOBAR"); - }); + .withUserConfiguration(DataSourceConfig.class, DataSourcePoolMetadataProvidersConfiguration.class) + .withPropertyValues("spring.datasource.test.validation-query:SELECT from FOOBAR") + .run((context) -> { + assertThat(context).hasSingleBean(DataSourceHealthIndicator.class); + DataSourceHealthIndicator indicator = context.getBean(DataSourceHealthIndicator.class); + assertThat(indicator.getQuery()).isEqualTo("SELECT from FOOBAR"); + }); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("management.health.db.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(DataSourceHealthIndicator.class) - .doesNotHaveBean(CompositeHealthContributor.class)); + .withPropertyValues("management.health.db.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(DataSourceHealthIndicator.class) + .doesNotHaveBean(CompositeHealthContributor.class)); } @Test @@ -142,12 +146,13 @@ class DataSourceHealthContributorAutoConfigurationTests { this.contextRunner.withUserConfiguration(NullKeyRoutingDataSourceConfig.class).run((context) -> { assertThat(context).hasSingleBean(RoutingDataSourceHealthContributor.class); RoutingDataSourceHealthContributor routingHealthContributor = context - .getBean(RoutingDataSourceHealthContributor.class); + .getBean(RoutingDataSourceHealthContributor.class); assertThat(routingHealthContributor.getContributor("unnamed")) - .isInstanceOf(DataSourceHealthIndicator.class); + .isInstanceOf(DataSourceHealthIndicator.class); assertThat(routingHealthContributor.getContributor("one")).isInstanceOf(DataSourceHealthIndicator.class); - assertThat(routingHealthContributor.iterator()).toIterable().extracting("name") - .containsExactlyInAnyOrder("unnamed", "one"); + assertThat(routingHealthContributor.iterator()).toIterable() + .extracting("name") + .containsExactlyInAnyOrder("unnamed", "one"); }); } @@ -158,8 +163,12 @@ class DataSourceHealthContributorAutoConfigurationTests { @Bean @ConfigurationProperties(prefix = "spring.datasource.test") DataSource testDataSource() { - return DataSourceBuilder.create().type(org.apache.tomcat.jdbc.pool.DataSource.class) - .driverClassName("org.hsqldb.jdbc.JDBCDriver").url("jdbc:hsqldb:mem:test").username("sa").build(); + return DataSourceBuilder.create() + .type(org.apache.tomcat.jdbc.pool.DataSource.class) + .driverClassName("org.hsqldb.jdbc.JDBCDriver") + .url("jdbc:hsqldb:mem:test") + .username("sa") + .build(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthContributorAutoConfigurationTests.java index 102f183950..a7d7c35738 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,8 @@ import static org.assertj.core.api.Assertions.assertThat; class JmsHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class, - JmsHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class, + JmsHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { @@ -46,7 +46,7 @@ class JmsHealthContributorAutoConfigurationTests { @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.jms.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(LdapHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LdapHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jolokia/JolokiaEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jolokia/JolokiaEndpointAutoConfigurationTests.java index 902defaef0..c741dbe3f2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jolokia/JolokiaEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jolokia/JolokiaEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,10 +49,10 @@ import static org.assertj.core.api.Assertions.assertThat; class JolokiaEndpointAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DispatcherServletAutoConfiguration.class, - ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, - ServletEndpointManagementContextConfiguration.class, JolokiaEndpointAutoConfiguration.class, - TestConfiguration.class)); + .withConfiguration(AutoConfigurations.of(DispatcherServletAutoConfiguration.class, + ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, + ServletEndpointManagementContextConfiguration.class, JolokiaEndpointAutoConfiguration.class, + TestConfiguration.class)); @Test void jolokiaServletShouldBeEnabledByDefault() { @@ -68,7 +68,7 @@ class JolokiaEndpointAutoConfigurationTests { void jolokiaServletWhenEndpointNotExposedShouldNotBeDiscovered() { this.contextRunner.run((context) -> { Collection endpoints = context.getBean(ServletEndpointsSupplier.class) - .getEndpoints(); + .getEndpoints(); assertThat(endpoints).isEmpty(); }); } @@ -76,21 +76,23 @@ class JolokiaEndpointAutoConfigurationTests { @Test void jolokiaServletWhenDisabledShouldNotBeDiscovered() { this.contextRunner.withPropertyValues("management.endpoint.jolokia.enabled=false") - .withPropertyValues("management.endpoints.web.exposure.include=jolokia").run((context) -> { - Collection endpoints = context.getBean(ServletEndpointsSupplier.class) - .getEndpoints(); - assertThat(endpoints).isEmpty(); - }); + .withPropertyValues("management.endpoints.web.exposure.include=jolokia") + .run((context) -> { + Collection endpoints = context.getBean(ServletEndpointsSupplier.class) + .getEndpoints(); + assertThat(endpoints).isEmpty(); + }); } @Test void jolokiaServletWhenHasCustomConfigShouldApplyInitParams() { this.contextRunner.withPropertyValues("management.endpoint.jolokia.config.debug=true") - .withPropertyValues("management.endpoints.web.exposure.include=jolokia").run((context) -> { - ExposableServletEndpoint endpoint = getEndpoint(context); - assertThat(endpoint.getEndpointServlet()).extracting("initParameters") - .isEqualTo(Collections.singletonMap("debug", "true")); - }); + .withPropertyValues("management.endpoints.web.exposure.include=jolokia") + .run((context) -> { + ExposableServletEndpoint endpoint = getEndpoint(context); + assertThat(endpoint.getEndpointServlet()).extracting("initParameters") + .isEqualTo(Collections.singletonMap("debug", "true")); + }); } private ExposableServletEndpoint getEndpoint(AssertableWebApplicationContext context) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthContributorAutoConfigurationTests.java index 38f897ab94..90ee152976 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,9 @@ import static org.mockito.Mockito.mock; class LdapHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withBean(LdapOperations.class, () -> mock(LdapOperations.class)).withConfiguration(AutoConfigurations - .of(LdapHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withBean(LdapOperations.class, () -> mock(LdapOperations.class)) + .withConfiguration(AutoConfigurations.of(LdapHealthContributorAutoConfiguration.class, + HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { @@ -47,7 +48,7 @@ class LdapHealthContributorAutoConfigurationTests { @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.ldap.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(LdapHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LdapHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfigurationTests.java index 02e82ed131..d1c8a0b0a6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,20 +37,20 @@ import static org.mockito.Mockito.mock; class LiquibaseEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(LiquibaseEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(LiquibaseEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=liquibase") - .withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class)) - .run((context) -> assertThat(context).hasSingleBean(LiquibaseEndpoint.class)); + .withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class)) + .run((context) -> assertThat(context).hasSingleBean(LiquibaseEndpoint.class)); } @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class)) - .withPropertyValues("management.endpoint.liquibase.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class)); + .withPropertyValues("management.endpoint.liquibase.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class)); } @Test @@ -61,21 +61,23 @@ class LiquibaseEndpointAutoConfigurationTests { @Test void disablesCloseOfDataSourceWhenEndpointIsEnabled() { this.contextRunner.withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=liquibase").run((context) -> { - assertThat(context).hasSingleBean(LiquibaseEndpoint.class); - assertThat(context.getBean(DataSourceClosingSpringLiquibase.class)) - .hasFieldOrPropertyWithValue("closeDataSourceOnceMigrated", false); - }); + .withPropertyValues("management.endpoints.web.exposure.include=liquibase") + .run((context) -> { + assertThat(context).hasSingleBean(LiquibaseEndpoint.class); + assertThat(context.getBean(DataSourceClosingSpringLiquibase.class)) + .hasFieldOrPropertyWithValue("closeDataSourceOnceMigrated", false); + }); } @Test void doesNotDisableCloseOfDataSourceWhenEndpointIsDisabled() { this.contextRunner.withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class) - .withPropertyValues("management.endpoint.liquibase.enabled:false").run((context) -> { - assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class); - DataSourceClosingSpringLiquibase bean = context.getBean(DataSourceClosingSpringLiquibase.class); - assertThat(bean).hasFieldOrPropertyWithValue("closeDataSourceOnceMigrated", true); - }); + .withPropertyValues("management.endpoint.liquibase.enabled:false") + .run((context) -> { + assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class); + DataSourceClosingSpringLiquibase bean = context.getBean(DataSourceClosingSpringLiquibase.class); + assertThat(bean).hasFieldOrPropertyWithValue("closeDataSourceOnceMigrated", true); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfigurationTests.java index 6492a90207..27831b04ae 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,66 +43,68 @@ import static org.assertj.core.api.Assertions.contentOf; class LogFileWebEndpointAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(LogFileWebEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(LogFileWebEndpointAutoConfiguration.class)); @Test void runWithOnlyExposedShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=logfile") - .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); } @Test void runWhenLoggingFileIsSetAndNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("logging.file.name:test.log") - .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); } @Test void runWhenLoggingFileIsSetAndExposedShouldHaveEndpointBean() { this.contextRunner - .withPropertyValues("logging.file.name:test.log", "management.endpoints.web.exposure.include=logfile") - .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); + .withPropertyValues("logging.file.name:test.log", "management.endpoints.web.exposure.include=logfile") + .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); } @Test void runWhenLoggingPathIsSetAndNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("logging.file.path:test/logs") - .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); } @Test void runWhenLoggingPathIsSetAndExposedShouldHaveEndpointBean() { this.contextRunner - .withPropertyValues("logging.file.path:test/logs", "management.endpoints.web.exposure.include=logfile") - .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); + .withPropertyValues("logging.file.path:test/logs", "management.endpoints.web.exposure.include=logfile") + .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); } @Test void logFileWebEndpointIsAutoConfiguredWhenExternalFileIsSet() { this.contextRunner - .withPropertyValues("management.endpoint.logfile.external-file:external.log", - "management.endpoints.web.exposure.include=logfile") - .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); + .withPropertyValues("management.endpoint.logfile.external-file:external.log", + "management.endpoints.web.exposure.include=logfile") + .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); } @Test void logFileWebEndpointCanBeDisabled() { this.contextRunner.withPropertyValues("logging.file.name:test.log", "management.endpoint.logfile.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); } @Test void logFileWebEndpointUsesConfiguredExternalFile(@TempDir Path temp) throws IOException { File file = new File(temp.toFile(), "logfile"); FileCopyUtils.copy("--TEST--".getBytes(), file); - this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=logfile", - "management.endpoint.logfile.external-file:" + file.getAbsolutePath()).run((context) -> { - assertThat(context).hasSingleBean(LogFileWebEndpoint.class); - LogFileWebEndpoint endpoint = context.getBean(LogFileWebEndpoint.class); - Resource resource = endpoint.logFile(); - assertThat(resource).isNotNull(); - assertThat(contentOf(resource.getFile())).isEqualTo("--TEST--"); - }); + this.contextRunner + .withPropertyValues("management.endpoints.web.exposure.include=logfile", + "management.endpoint.logfile.external-file:" + file.getAbsolutePath()) + .run((context) -> { + assertThat(context).hasSingleBean(LogFileWebEndpoint.class); + LogFileWebEndpoint endpoint = context.getBean(LogFileWebEndpoint.class); + Resource resource = endpoint.logFile(); + assertThat(resource).isNotNull(); + assertThat(contentOf(resource.getFile())).isEqualTo("--TEST--"); + }); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfigurationTests.java index 9c0ee779c9..271fdef003 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,19 +36,19 @@ import static org.mockito.Mockito.mock; class LoggersEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(LoggersEndpointAutoConfiguration.class)) - .withUserConfiguration(LoggingConfiguration.class); + .withConfiguration(AutoConfigurations.of(LoggersEndpointAutoConfiguration.class)) + .withUserConfiguration(LoggingConfiguration.class); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=loggers") - .run((context) -> assertThat(context).hasSingleBean(LoggersEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(LoggersEndpoint.class)); } @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.loggers.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class)); } @Test @@ -59,7 +59,7 @@ class LoggersEndpointAutoConfigurationTests { @Test void runWithNoneLoggingSystemShouldNotHaveEndpointBean() { this.contextRunner.withSystemProperties("org.springframework.boot.logging.LoggingSystem=none") - .run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthContributorAutoConfigurationTests.java index b51a8fed00..1c599275d6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,9 +34,9 @@ import static org.assertj.core.api.Assertions.assertThat; class MailHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MailSenderAutoConfiguration.class, - MailHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)) - .withPropertyValues("spring.mail.host:smtp.example.com"); + .withConfiguration(AutoConfigurations.of(MailSenderAutoConfiguration.class, + MailHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)) + .withPropertyValues("spring.mail.host:smtp.example.com"); @Test void runShouldCreateIndicator() { @@ -46,7 +46,7 @@ class MailHealthContributorAutoConfigurationTests { @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.mail.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(MailHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(MailHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/HeapDumpWebEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/HeapDumpWebEndpointAutoConfigurationTests.java index 48403bc5b2..23a4296c21 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/HeapDumpWebEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/HeapDumpWebEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,8 @@ import static org.assertj.core.api.Assertions.assertThat; class HeapDumpWebEndpointAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withPropertyValues("management.endpoints.web.exposure.include:*") - .withUserConfiguration(HeapDumpWebEndpointAutoConfiguration.class); + .withPropertyValues("management.endpoints.web.exposure.include:*") + .withUserConfiguration(HeapDumpWebEndpointAutoConfiguration.class); @Test void runShouldCreateIndicator() { @@ -42,7 +42,7 @@ class HeapDumpWebEndpointAutoConfigurationTests { @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.endpoint.heapdump.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(HeapDumpWebEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(HeapDumpWebEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfigurationTests.java index ac7fb7be20..c3ddd2756a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,12 +32,12 @@ import static org.assertj.core.api.Assertions.assertThat; class ThreadDumpEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ThreadDumpEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ThreadDumpEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=threaddump") - .run((context) -> assertThat(context).hasSingleBean(ThreadDumpEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(ThreadDumpEndpoint.class)); } @Test @@ -48,8 +48,8 @@ class ThreadDumpEndpointAutoConfigurationTests { @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=*") - .withPropertyValues("management.endpoint.threaddump.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(ThreadDumpEndpoint.class)); + .withPropertyValues("management.endpoint.threaddump.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(ThreadDumpEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfigurationTests.java index 4b6f8610be..26d59a87a0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,8 @@ class CompositeMeterRegistryAutoConfigurationTests { private static final String COMPOSITE_NAME = "compositeMeterRegistry"; private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(BaseConfig.class) - .withConfiguration(AutoConfigurations.of(CompositeMeterRegistryAutoConfiguration.class)); + .withUserConfiguration(BaseConfig.class) + .withConfiguration(AutoConfigurations.of(CompositeMeterRegistryAutoConfiguration.class)); @Test void registerWhenHasNoMeterRegistryShouldRegisterEmptyNoOpComposite() { @@ -66,8 +66,8 @@ class CompositeMeterRegistryAutoConfigurationTests { @Test void registerWhenHasMultipleMeterRegistriesShouldAddPrimaryComposite() { this.contextRunner.withUserConfiguration(MultipleMeterRegistriesConfig.class).run((context) -> { - assertThat(context.getBeansOfType(MeterRegistry.class)).hasSize(3).containsKeys("meterRegistryOne", - "meterRegistryTwo", COMPOSITE_NAME); + assertThat(context.getBeansOfType(MeterRegistry.class)).hasSize(3) + .containsKeys("meterRegistryOne", "meterRegistryTwo", COMPOSITE_NAME); MeterRegistry primary = context.getBean(MeterRegistry.class); assertThat(primary).isInstanceOf(CompositeMeterRegistry.class); assertThat(((CompositeMeterRegistry) primary).getRegistries()).hasSize(2); @@ -78,8 +78,8 @@ class CompositeMeterRegistryAutoConfigurationTests { @Test void registerWhenHasMultipleRegistriesAndOneIsPrimaryShouldDoNothing() { this.contextRunner.withUserConfiguration(MultipleMeterRegistriesWithOnePrimaryConfig.class).run((context) -> { - assertThat(context.getBeansOfType(MeterRegistry.class)).hasSize(2).containsKeys("meterRegistryOne", - "meterRegistryTwo"); + assertThat(context.getBeansOfType(MeterRegistry.class)).hasSize(2) + .containsKeys("meterRegistryOne", "meterRegistryTwo"); MeterRegistry primary = context.getBean(MeterRegistry.class); assertThat(primary).isInstanceOf(TestMeterRegistry.class); }); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/JvmMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/JvmMetricsAutoConfigurationTests.java index ecb3a5ad2a..cfd1a12b53 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/JvmMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/JvmMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; class JvmMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class)); @Test void autoConfiguresJvmMetrics() { @@ -52,37 +52,40 @@ class JvmMetricsAutoConfigurationTests { @Test void allowsCustomJvmGcMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomJvmGcMetricsConfiguration.class) - .run(assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customJvmGcMetrics"))); + .run(assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customJvmGcMetrics"))); } @Test void allowsCustomJvmHeapPressureMetricsToBeUsed() { - this.contextRunner.withUserConfiguration(CustomJvmHeapPressureMetricsConfiguration.class).run( - assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customJvmHeapPressureMetrics"))); + this.contextRunner.withUserConfiguration(CustomJvmHeapPressureMetricsConfiguration.class) + .run(assertMetricsBeans() + .andThen((context) -> assertThat(context).hasBean("customJvmHeapPressureMetrics"))); } @Test void allowsCustomJvmMemoryMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomJvmMemoryMetricsConfiguration.class) - .run(assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customJvmMemoryMetrics"))); + .run(assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customJvmMemoryMetrics"))); } @Test void allowsCustomJvmThreadMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomJvmThreadMetricsConfiguration.class) - .run(assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customJvmThreadMetrics"))); + .run(assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customJvmThreadMetrics"))); } @Test void allowsCustomClassLoaderMetricsToBeUsed() { - this.contextRunner.withUserConfiguration(CustomClassLoaderMetricsConfiguration.class).run( - assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customClassLoaderMetrics"))); + this.contextRunner.withUserConfiguration(CustomClassLoaderMetricsConfiguration.class) + .run(assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customClassLoaderMetrics"))); } private ContextConsumer assertMetricsBeans() { return (context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class) - .hasSingleBean(JvmHeapPressureMetrics.class).hasSingleBean(JvmMemoryMetrics.class) - .hasSingleBean(JvmThreadMetrics.class).hasSingleBean(ClassLoaderMetrics.class); + .hasSingleBean(JvmHeapPressureMetrics.class) + .hasSingleBean(JvmMemoryMetrics.class) + .hasSingleBean(JvmThreadMetrics.class) + .hasSingleBean(ClassLoaderMetrics.class); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/KafkaMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/KafkaMetricsAutoConfigurationTests.java index 8a2dcf27c1..2b23092193 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/KafkaMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/KafkaMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,50 +50,52 @@ import static org.assertj.core.api.Assertions.assertThat; class KafkaMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(KafkaMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(KafkaMetricsAutoConfiguration.class)); @Test void whenThereIsAMeterRegistryThenMetricsListenersAreAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(KafkaAutoConfiguration.class)).run((context) -> { - assertThat(((DefaultKafkaProducerFactory) context.getBean(DefaultKafkaProducerFactory.class)) - .getListeners()).hasSize(1).hasOnlyElementsOfTypes(MicrometerProducerListener.class); - assertThat(((DefaultKafkaConsumerFactory) context.getBean(DefaultKafkaConsumerFactory.class)) - .getListeners()).hasSize(1).hasOnlyElementsOfTypes(MicrometerConsumerListener.class); - }); + .withConfiguration(AutoConfigurations.of(KafkaAutoConfiguration.class)) + .run((context) -> { + assertThat(((DefaultKafkaProducerFactory) context.getBean(DefaultKafkaProducerFactory.class)) + .getListeners()).hasSize(1).hasOnlyElementsOfTypes(MicrometerProducerListener.class); + assertThat(((DefaultKafkaConsumerFactory) context.getBean(DefaultKafkaConsumerFactory.class)) + .getListeners()).hasSize(1).hasOnlyElementsOfTypes(MicrometerConsumerListener.class); + }); } @Test void whenThereIsNoMeterRegistryThenListenerCustomizationBacksOff() { this.contextRunner.withConfiguration(AutoConfigurations.of(KafkaAutoConfiguration.class)).run((context) -> { assertThat(((DefaultKafkaProducerFactory) context.getBean(DefaultKafkaProducerFactory.class)) - .getListeners()).isEmpty(); + .getListeners()).isEmpty(); assertThat(((DefaultKafkaConsumerFactory) context.getBean(DefaultKafkaConsumerFactory.class)) - .getListeners()).isEmpty(); + .getListeners()).isEmpty(); }); } @Test void whenKafkaStreamsIsEnabledAndThereIsAMeterRegistryThenMetricsListenersAreAdded() { this.contextRunner.withConfiguration(AutoConfigurations.of(KafkaAutoConfiguration.class)) - .withUserConfiguration(EnableKafkaStreamsConfiguration.class) - .withPropertyValues("spring.application.name=my-test-app").with(MetricsRun.simple()).run((context) -> { - StreamsBuilderFactoryBean streamsBuilderFactoryBean = context - .getBean(StreamsBuilderFactoryBean.class); - assertThat(streamsBuilderFactoryBean.getListeners()).hasSize(1) - .hasOnlyElementsOfTypes(KafkaStreamsMicrometerListener.class); - }); + .withUserConfiguration(EnableKafkaStreamsConfiguration.class) + .withPropertyValues("spring.application.name=my-test-app") + .with(MetricsRun.simple()) + .run((context) -> { + StreamsBuilderFactoryBean streamsBuilderFactoryBean = context.getBean(StreamsBuilderFactoryBean.class); + assertThat(streamsBuilderFactoryBean.getListeners()).hasSize(1) + .hasOnlyElementsOfTypes(KafkaStreamsMicrometerListener.class); + }); } @Test void whenKafkaStreamsIsEnabledAndThereIsNoMeterRegistryThenListenerCustomizationBacksOff() { this.contextRunner.withConfiguration(AutoConfigurations.of(KafkaAutoConfiguration.class)) - .withUserConfiguration(EnableKafkaStreamsConfiguration.class) - .withPropertyValues("spring.application.name=my-test-app").run((context) -> { - StreamsBuilderFactoryBean streamsBuilderFactoryBean = context - .getBean(StreamsBuilderFactoryBean.class); - assertThat(streamsBuilderFactoryBean.getListeners()).isEmpty(); - }); + .withUserConfiguration(EnableKafkaStreamsConfiguration.class) + .withPropertyValues("spring.application.name=my-test-app") + .run((context) -> { + StreamsBuilderFactoryBean streamsBuilderFactoryBean = context.getBean(StreamsBuilderFactoryBean.class); + assertThat(streamsBuilderFactoryBean.getListeners()).isEmpty(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests.java index b89d1b06b8..eb872327d3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,21 +38,21 @@ import static org.assertj.core.api.Assertions.assertThat; class Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(Log4J2MetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(Log4J2MetricsAutoConfiguration.class)); @Test void autoConfiguresLog4J2Metrics() { assertThat(LogManager.getContext().getClass().getName()) - .isEqualTo("org.apache.logging.log4j.core.LoggerContext"); + .isEqualTo("org.apache.logging.log4j.core.LoggerContext"); this.contextRunner.run((context) -> assertThat(context).hasSingleBean(Log4j2Metrics.class)); } @Test void allowsCustomLog4J2MetricsToBeUsed() { assertThat(LogManager.getContext().getClass().getName()) - .isEqualTo("org.apache.logging.log4j.core.LoggerContext"); - this.contextRunner.withUserConfiguration(CustomLog4J2MetricsConfiguration.class).run( - (context) -> assertThat(context).hasSingleBean(Log4j2Metrics.class).hasBean("customLog4J2Metrics")); + .isEqualTo("org.apache.logging.log4j.core.LoggerContext"); + this.contextRunner.withUserConfiguration(CustomLog4J2MetricsConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(Log4j2Metrics.class).hasBean("customLog4J2Metrics")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests.java index 1026186658..4408fddad5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; class Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(Log4J2MetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(Log4J2MetricsAutoConfiguration.class)); @Test void backsOffWhenLoggerContextIsBackedBySlf4j() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationTests.java index b8c3830183..c9b7d63339 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat; class LogbackMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)); @Test void autoConfiguresLogbackMetrics() { @@ -45,8 +45,8 @@ class LogbackMetricsAutoConfigurationTests { @Test void allowsCustomLogbackMetricsToBeUsed() { - this.contextRunner.withUserConfiguration(CustomLogbackMetricsConfiguration.class).run( - (context) -> assertThat(context).hasSingleBean(LogbackMetrics.class).hasBean("customLogbackMetrics")); + this.contextRunner.withUserConfiguration(CustomLogbackMetricsConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(LogbackMetrics.class).hasBean("customLogbackMetrics")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationWithLog4j2AndLogbackTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationWithLog4j2AndLogbackTests.java index a764a32afa..523d9eda47 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationWithLog4j2AndLogbackTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationWithLog4j2AndLogbackTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,8 @@ import static org.assertj.core.api.Assertions.assertThat; class LogbackMetricsAutoConfigurationWithLog4j2AndLogbackTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class, LogbackMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, + SimpleMetricsExportAutoConfiguration.class, LogbackMetricsAutoConfiguration.class)); @Test void doesNotConfigureLogbackMetrics() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerIntegrationTests.java index 29e82b0792..81f123e8c8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,9 +48,9 @@ import static org.assertj.core.api.Assertions.assertThat; class MeterRegistryConfigurerIntegrationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.limitedTo(AtlasMetricsExportAutoConfiguration.class, - PrometheusMetricsExportAutoConfiguration.class)) - .withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class)); + .with(MetricsRun.limitedTo(AtlasMetricsExportAutoConfiguration.class, + PrometheusMetricsExportAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class)); @Test void binderMetricsAreSearchableFromTheComposite() { @@ -58,50 +58,52 @@ class MeterRegistryConfigurerIntegrationTests { CompositeMeterRegistry composite = context.getBean(CompositeMeterRegistry.class); composite.get("jvm.memory.used").gauge(); context.getBeansOfType(MeterRegistry.class) - .forEach((name, registry) -> registry.get("jvm.memory.used").gauge()); + .forEach((name, registry) -> registry.get("jvm.memory.used").gauge()); }); } @Test void customizersAreAppliedBeforeBindersAreCreated() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class)) - .withUserConfiguration(TestConfiguration.class).run((context) -> { + .withConfiguration( + AutoConfigurations.of(MetricsAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class)) + .withUserConfiguration(TestConfiguration.class) + .run((context) -> { - }); + }); } @Test void counterIsIncrementedOncePerEventWithoutCompositeMeterRegistry() { new ApplicationContextRunner().with(MetricsRun.limitedTo(JmxMetricsExportAutoConfiguration.class)) - .withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)).run((context) -> { - Logger logger = ((LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory()) - .getLogger("test-logger"); - logger.error("Error."); - Map registriesByName = context.getBeansOfType(MeterRegistry.class); - assertThat(registriesByName).hasSize(1); - MeterRegistry registry = registriesByName.values().iterator().next(); - assertThat(registry.get("logback.events").tag("level", "error").counter().count()).isEqualTo(1); - }); + .withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)) + .run((context) -> { + Logger logger = ((LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory()) + .getLogger("test-logger"); + logger.error("Error."); + Map registriesByName = context.getBeansOfType(MeterRegistry.class); + assertThat(registriesByName).hasSize(1); + MeterRegistry registry = registriesByName.values().iterator().next(); + assertThat(registry.get("logback.events").tag("level", "error").counter().count()).isEqualTo(1); + }); } @Test void counterIsIncrementedOncePerEventWithCompositeMeterRegistry() { new ApplicationContextRunner() - .with(MetricsRun.limitedTo(JmxMetricsExportAutoConfiguration.class, - PrometheusMetricsExportAutoConfiguration.class)) - .withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)).run((context) -> { - Logger logger = ((LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory()) - .getLogger("test-logger"); - logger.error("Error."); - Map registriesByName = context.getBeansOfType(MeterRegistry.class); - assertThat(registriesByName).hasSize(3); - registriesByName.forEach((name, - registry) -> assertThat( - registry.get("logback.events").tag("level", "error").counter().count()) - .isEqualTo(1)); - }); + .with(MetricsRun.limitedTo(JmxMetricsExportAutoConfiguration.class, + PrometheusMetricsExportAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)) + .run((context) -> { + Logger logger = ((LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory()) + .getLogger("test-logger"); + logger.error("Error."); + Map registriesByName = context.getBeansOfType(MeterRegistry.class); + assertThat(registriesByName).hasSize(3); + registriesByName.forEach((name, + registry) -> assertThat(registry.get("logback.events").tag("level", "error").counter().count()) + .isEqualTo(1)); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryCustomizerTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryCustomizerTests.java index d1d48fdf9b..a24345324b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryCustomizerTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,9 +40,9 @@ import static org.assertj.core.api.Assertions.assertThat; class MeterRegistryCustomizerTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.limitedTo(AtlasMetricsExportAutoConfiguration.class, - PrometheusMetricsExportAutoConfiguration.class)) - .withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class)); + .with(MetricsRun.limitedTo(AtlasMetricsExportAutoConfiguration.class, + PrometheusMetricsExportAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class)); @Test void commonTagsAreAppliedToAutoConfiguredBinders() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValueTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValueTests.java index 316eea078b..baeba52d9a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValueTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValueTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -84,9 +84,11 @@ class MeterValueTests { MockEnvironment environment = new MockEnvironment(); TestPropertyValues.of("duration=10ms", "number=20.42").applyTo(environment); assertThat(Binder.get(environment).bind("duration", Bindable.of(MeterValue.class)).get().getValue(Type.TIMER)) - .isEqualTo(10000000); - assertThat(Binder.get(environment).bind("number", Bindable.of(MeterValue.class)).get() - .getValue(Type.DISTRIBUTION_SUMMARY)).isEqualTo(20.42); + .isEqualTo(10000000); + assertThat(Binder.get(environment) + .bind("number", Bindable.of(MeterValue.class)) + .get() + .getValue(Type.DISTRIBUTION_SUMMARY)).isEqualTo(20.42); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationIntegrationTests.java index 70f28e4f16..0f063c8fdd 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,19 +60,22 @@ class MetricsAutoConfigurationIntegrationTests { @Test void propertyBasedCommonTagsIsAutoConfigured() { this.contextRunner - .withPropertyValues("management.metrics.tags.region=test", "management.metrics.tags.origin=local") - .run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.counter("my.counter", "env", "qa"); - assertThat(registry.find("my.counter").tags("env", "qa").tags("region", "test") - .tags("origin", "local").counter()).isNotNull(); - }); + .withPropertyValues("management.metrics.tags.region=test", "management.metrics.tags.origin=local") + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.counter("my.counter", "env", "qa"); + assertThat(registry.find("my.counter") + .tags("env", "qa") + .tags("region", "test") + .tags("origin", "local") + .counter()).isNotNull(); + }); } @Test void simpleMeterRegistryIsUsedAsAFallback() { - this.contextRunner.run( - (context) -> assertThat(context.getBean(MeterRegistry.class)).isInstanceOf(SimpleMeterRegistry.class)); + this.contextRunner + .run((context) -> assertThat(context.getBean(MeterRegistry.class)).isInstanceOf(SimpleMeterRegistry.class)); } @Test @@ -87,59 +90,64 @@ class MetricsAutoConfigurationIntegrationTests { @Test void noCompositeIsCreatedWhenASingleMeterRegistryIsAutoConfigured() { new ApplicationContextRunner().with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class)) - .run((context) -> assertThat(context.getBean(MeterRegistry.class)) - .isInstanceOf(GraphiteMeterRegistry.class)); + .run((context) -> assertThat(context.getBean(MeterRegistry.class)) + .isInstanceOf(GraphiteMeterRegistry.class)); } @Test void noCompositeIsCreatedWithMultipleRegistriesAndOneThatIsPrimary() { new ApplicationContextRunner() - .with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class, - JmxMetricsExportAutoConfiguration.class)) - .withUserConfiguration(PrimaryMeterRegistryConfiguration.class) - .run((context) -> assertThat(context.getBean(MeterRegistry.class)) - .isInstanceOf(SimpleMeterRegistry.class)); + .with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class, + JmxMetricsExportAutoConfiguration.class)) + .withUserConfiguration(PrimaryMeterRegistryConfiguration.class) + .run((context) -> assertThat(context.getBean(MeterRegistry.class)).isInstanceOf(SimpleMeterRegistry.class)); } @Test void compositeCreatedWithMultipleRegistries() { - new ApplicationContextRunner().with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class, - JmxMetricsExportAutoConfiguration.class)).run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry).isInstanceOf(CompositeMeterRegistry.class); - assertThat(((CompositeMeterRegistry) registry).getRegistries()) - .hasAtLeastOneElementOfType(GraphiteMeterRegistry.class) - .hasAtLeastOneElementOfType(JmxMeterRegistry.class); - }); + new ApplicationContextRunner() + .with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class, + JmxMetricsExportAutoConfiguration.class)) + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry).isInstanceOf(CompositeMeterRegistry.class); + assertThat(((CompositeMeterRegistry) registry).getRegistries()) + .hasAtLeastOneElementOfType(GraphiteMeterRegistry.class) + .hasAtLeastOneElementOfType(JmxMeterRegistry.class); + }); } @Test void autoConfiguredCompositeDoesNotHaveMeterFiltersApplied() { - new ApplicationContextRunner().with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class, - JmxMetricsExportAutoConfiguration.class)).run((context) -> { - MeterRegistry composite = context.getBean(MeterRegistry.class); - assertThat(composite).extracting("filters", InstanceOfAssertFactories.ARRAY).hasSize(0); - assertThat(composite).isInstanceOf(CompositeMeterRegistry.class); - Set registries = ((CompositeMeterRegistry) composite).getRegistries(); - assertThat(registries).hasSize(2); - assertThat(registries).hasAtLeastOneElementOfType(GraphiteMeterRegistry.class) - .hasAtLeastOneElementOfType(JmxMeterRegistry.class); - assertThat(registries).allSatisfy((registry) -> assertThat(registry) - .extracting("filters", InstanceOfAssertFactories.ARRAY).hasSize(1)); - }); + new ApplicationContextRunner() + .with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class, + JmxMetricsExportAutoConfiguration.class)) + .run((context) -> { + MeterRegistry composite = context.getBean(MeterRegistry.class); + assertThat(composite).extracting("filters", InstanceOfAssertFactories.ARRAY).hasSize(0); + assertThat(composite).isInstanceOf(CompositeMeterRegistry.class); + Set registries = ((CompositeMeterRegistry) composite).getRegistries(); + assertThat(registries).hasSize(2); + assertThat(registries).hasAtLeastOneElementOfType(GraphiteMeterRegistry.class) + .hasAtLeastOneElementOfType(JmxMeterRegistry.class); + assertThat(registries).allSatisfy( + (registry) -> assertThat(registry).extracting("filters", InstanceOfAssertFactories.ARRAY) + .hasSize(1)); + }); } @Test void userConfiguredCompositeHasMeterFiltersApplied() { new ApplicationContextRunner().with(MetricsRun.limitedTo()) - .withUserConfiguration(CompositeMeterRegistryConfiguration.class).run((context) -> { - MeterRegistry composite = context.getBean(MeterRegistry.class); - assertThat(composite).extracting("filters", InstanceOfAssertFactories.ARRAY).hasSize(1); - assertThat(composite).isInstanceOf(CompositeMeterRegistry.class); - Set registries = ((CompositeMeterRegistry) composite).getRegistries(); - assertThat(registries).hasSize(2); - assertThat(registries).hasOnlyElementsOfTypes(SimpleMeterRegistry.class); - }); + .withUserConfiguration(CompositeMeterRegistryConfiguration.class) + .run((context) -> { + MeterRegistry composite = context.getBean(MeterRegistry.class); + assertThat(composite).extracting("filters", InstanceOfAssertFactories.ARRAY).hasSize(1); + assertThat(composite).isInstanceOf(CompositeMeterRegistry.class); + Set registries = ((CompositeMeterRegistry) composite).getRegistries(); + assertThat(registries).hasSize(2); + assertThat(registries).hasOnlyElementsOfTypes(SimpleMeterRegistry.class); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationTests.java index fd8f773084..c04c31435a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ import static org.mockito.Mockito.mock; class MetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class)); @Test void autoConfiguresAClock() { @@ -54,7 +54,7 @@ class MetricsAutoConfigurationTests { @Test void allowsACustomClockToBeUsed() { this.contextRunner.withUserConfiguration(CustomClockConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(Clock.class).hasBean("customClock")); + .run((context) -> assertThat(context).hasSingleBean(Clock.class).hasBean("customClock")); } @SuppressWarnings("unchecked") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java index 7c5d733d6e..5db70a5285 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ class PropertiesMeterFilterTests { @Test void createWhenPropertiesIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new PropertiesMeterFilter(null)) - .withMessageContaining("Properties must not be null"); + .withMessageContaining("Properties must not be null"); } @Test @@ -119,7 +119,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring.boot=true")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .isPercentileHistogram()).isTrue(); + .isPercentileHistogram()).isTrue(); } @Test @@ -127,7 +127,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring.boot=false")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .isPercentileHistogram()).isFalse(); + .isPercentileHistogram()).isFalse(); } @Test @@ -135,7 +135,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring=true")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .isPercentileHistogram()).isTrue(); + .isPercentileHistogram()).isTrue(); } @Test @@ -143,7 +143,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring=false")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .isPercentileHistogram()).isFalse(); + .isPercentileHistogram()).isFalse(); } @Test @@ -152,7 +152,7 @@ class PropertiesMeterFilterTests { createProperties("distribution.percentiles-histogram.spring=true", "distribution.percentiles-histogram.spring.boot=false")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .isPercentileHistogram()).isFalse(); + .isPercentileHistogram()).isFalse(); } @Test @@ -161,7 +161,7 @@ class PropertiesMeterFilterTests { createProperties("distribution.percentiles-histogram.spring=false", "distribution.percentiles-histogram.spring.boot=true")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .isPercentileHistogram()).isTrue(); + .isPercentileHistogram()).isTrue(); } @Test @@ -169,7 +169,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.all=true")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .isPercentileHistogram()).isTrue(); + .isPercentileHistogram()).isTrue(); } @Test @@ -177,7 +177,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles.spring.boot=1,1.5,2")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getPercentiles()) - .containsExactly(1, 1.5, 2); + .containsExactly(1, 1.5, 2); } @Test @@ -185,7 +185,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles.spring=1,1.5,2")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getPercentiles()) - .containsExactly(1, 1.5, 2); + .containsExactly(1, 1.5, 2); } @Test @@ -193,7 +193,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties( "distribution.percentiles.spring=1,1.5,2", "distribution.percentiles.spring.boot=3,3.5,4")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getPercentiles()) - .containsExactly(3, 3.5, 4); + .containsExactly(3, 3.5, 4); } @Test @@ -201,7 +201,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles.all=1,1.5,2")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getPercentiles()) - .containsExactly(1, 1.5, 2); + .containsExactly(1, 1.5, 2); } @Test @@ -209,14 +209,14 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.slo.spring.boot=1,2,3")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .getServiceLevelObjectiveBoundaries()).containsExactly(1000000, 2000000, 3000000); + .getServiceLevelObjectiveBoundaries()).containsExactly(1000000, 2000000, 3000000); } @Test void configureWhenHasHigherSloShouldSetPercentilesToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("distribution.slo.spring=1,2,3")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .getServiceLevelObjectiveBoundaries()).containsExactly(1000000, 2000000, 3000000); + .getServiceLevelObjectiveBoundaries()).containsExactly(1000000, 2000000, 3000000); } @Test @@ -224,7 +224,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.slo.spring=1,2,3", "distribution.slo.spring.boot=4,5,6")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .getServiceLevelObjectiveBoundaries()).containsExactly(4000000, 5000000, 6000000); + .getServiceLevelObjectiveBoundaries()).containsExactly(4000000, 5000000, 6000000); } @Test @@ -232,7 +232,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.minimum-expected-value.spring.boot=10")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .getMinimumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(10).toNanos()); + .getMinimumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(10).toNanos()); } @Test @@ -240,7 +240,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.minimum-expected-value.spring=10")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .getMinimumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(10).toNanos()); + .getMinimumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(10).toNanos()); } @Test @@ -248,7 +248,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties( "distribution.minimum-expected-value.spring=10", "distribution.minimum-expected-value.spring.boot=50")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .getMinimumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(50).toNanos()); + .getMinimumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(50).toNanos()); } @Test @@ -256,7 +256,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.maximum-expected-value.spring.boot=5000")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .getMaximumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(5000).toNanos()); + .getMaximumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(5000).toNanos()); } @Test @@ -264,7 +264,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.maximum-expected-value.spring=5000")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .getMaximumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(5000).toNanos()); + .getMaximumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(5000).toNanos()); } @Test @@ -273,7 +273,7 @@ class PropertiesMeterFilterTests { createProperties("distribution.maximum-expected-value.spring=5000", "distribution.maximum-expected-value.spring.boot=10000")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .getMaximumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(10000).toNanos()); + .getMaximumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(10000).toNanos()); } @Test @@ -281,14 +281,14 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.expiry[spring.boot]=5ms")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getExpiry()) - .isEqualTo(Duration.ofMillis(5)); + .isEqualTo(Duration.ofMillis(5)); } @Test void configureWhenHasHigherExpiryShouldSetExpiryToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("distribution.expiry.spring=5ms")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getExpiry()) - .isEqualTo(Duration.ofMillis(5)); + .isEqualTo(Duration.ofMillis(5)); } @Test @@ -296,14 +296,14 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.expiry.spring=5ms", "distribution.expiry[spring.boot]=10ms")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getExpiry()) - .isEqualTo(Duration.ofMillis(10)); + .isEqualTo(Duration.ofMillis(10)); } @Test void configureWhenAllExpirySetShouldSetExpiryToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("distribution.expiry.all=5ms")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getExpiry()) - .isEqualTo(Duration.ofMillis(5)); + .isEqualTo(Duration.ofMillis(5)); } @Test @@ -312,7 +312,7 @@ class PropertiesMeterFilterTests { createProperties("distribution.buffer-length.spring.boot=3")); assertThat( filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getBufferLength()) - .isEqualTo(3); + .isEqualTo(3); } @Test @@ -321,7 +321,7 @@ class PropertiesMeterFilterTests { createProperties("distribution.buffer-length.spring=3")); assertThat( filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getBufferLength()) - .isEqualTo(3); + .isEqualTo(3); } @Test @@ -330,7 +330,7 @@ class PropertiesMeterFilterTests { createProperties("distribution.buffer-length.spring=2", "distribution.buffer-length.spring.boot=3")); assertThat( filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getBufferLength()) - .isEqualTo(3); + .isEqualTo(3); } @Test @@ -338,7 +338,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("distribution.buffer-length.all=3")); assertThat( filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getBufferLength()) - .isEqualTo(3); + .isEqualTo(3); } private Id createMeterId(String name) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/SystemMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/SystemMetricsAutoConfigurationTests.java index cba6e2c355..3a9c1215a8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/SystemMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/SystemMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,7 @@ import static org.assertj.core.api.Assertions.assertThat; class SystemMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(SystemMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SystemMetricsAutoConfiguration.class)); @Test void autoConfiguresUptimeMetrics() { @@ -54,8 +54,8 @@ class SystemMetricsAutoConfigurationTests { @Test void allowsCustomUptimeMetricsToBeUsed() { - this.contextRunner.withUserConfiguration(CustomUptimeMetricsConfiguration.class).run( - (context) -> assertThat(context).hasSingleBean(UptimeMetrics.class).hasBean("customUptimeMetrics")); + this.contextRunner.withUserConfiguration(CustomUptimeMetricsConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(UptimeMetrics.class).hasBean("customUptimeMetrics")); } @Test @@ -66,8 +66,8 @@ class SystemMetricsAutoConfigurationTests { @Test void allowsCustomProcessorMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomProcessorMetricsConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ProcessorMetrics.class) - .hasBean("customProcessorMetrics")); + .run((context) -> assertThat(context).hasSingleBean(ProcessorMetrics.class) + .hasBean("customProcessorMetrics")); } @Test @@ -78,8 +78,8 @@ class SystemMetricsAutoConfigurationTests { @Test void allowsCustomFileDescriptorMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomFileDescriptorMetricsConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(FileDescriptorMetrics.class) - .hasBean("customFileDescriptorMetrics")); + .run((context) -> assertThat(context).hasSingleBean(FileDescriptorMetrics.class) + .hasBean("customFileDescriptorMetrics")); } @Test @@ -90,29 +90,31 @@ class SystemMetricsAutoConfigurationTests { @Test void allowsCustomDiskSpaceMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomDiskSpaceMetricsConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(DiskSpaceMetricsBinder.class) - .hasBean("customDiskSpaceMetrics")); + .run((context) -> assertThat(context).hasSingleBean(DiskSpaceMetricsBinder.class) + .hasBean("customDiskSpaceMetrics")); } @Test void diskSpaceMetricsUsesDefaultPath() { - this.contextRunner - .run((context) -> assertThat(context).hasBean("diskSpaceMetrics").getBean(DiskSpaceMetricsBinder.class) - .hasFieldOrPropertyWithValue("paths", Collections.singletonList(new File(".")))); + this.contextRunner.run((context) -> assertThat(context).hasBean("diskSpaceMetrics") + .getBean(DiskSpaceMetricsBinder.class) + .hasFieldOrPropertyWithValue("paths", Collections.singletonList(new File(".")))); } @Test void allowsDiskSpaceMetricsPathToBeConfiguredWithSinglePath() { this.contextRunner.withPropertyValues("management.metrics.system.diskspace.paths:..") - .run((context) -> assertThat(context).hasBean("diskSpaceMetrics").getBean(DiskSpaceMetricsBinder.class) - .hasFieldOrPropertyWithValue("paths", Collections.singletonList(new File("..")))); + .run((context) -> assertThat(context).hasBean("diskSpaceMetrics") + .getBean(DiskSpaceMetricsBinder.class) + .hasFieldOrPropertyWithValue("paths", Collections.singletonList(new File("..")))); } @Test void allowsDiskSpaceMetricsPathToBeConfiguredWithMultiplePaths() { this.contextRunner.withPropertyValues("management.metrics.system.diskspace.paths:.,..") - .run((context) -> assertThat(context).hasBean("diskSpaceMetrics").getBean(DiskSpaceMetricsBinder.class) - .hasFieldOrPropertyWithValue("paths", Arrays.asList(new File("."), new File("..")))); + .run((context) -> assertThat(context).hasBean("diskSpaceMetrics") + .getBean(DiskSpaceMetricsBinder.class) + .hasFieldOrPropertyWithValue("paths", Arrays.asList(new File("."), new File("..")))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/ValidationFailureAnalyzerTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/ValidationFailureAnalyzerTests.java index 804748c5fc..c71c149dbf 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/ValidationFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/ValidationFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class ValidationFailureAnalyzerTests { @Test void analyzesMissingRequiredConfiguration() { FailureAnalysis analysis = new ValidationFailureAnalyzer() - .analyze(createFailure(MissingAccountIdAndApiKeyConfiguration.class)); + .analyze(createFailure(MissingAccountIdAndApiKeyConfiguration.class)); assertThat(analysis).isNotNull(); assertThat(analysis.getCause().getMessage()).contains("management.metrics.export.newrelic.apiKey was 'null'"); assertThat(analysis.getDescription()).isEqualTo(String.format("Invalid Micrometer configuration detected:%n%n" diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfigurationTests.java index dd2c9931a3..9193d5adda 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; class RabbitMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration( - AutoConfigurations.of(RabbitAutoConfiguration.class, RabbitMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class, RabbitMetricsAutoConfiguration.class)); @Test void autoConfiguredConnectionFactoryIsInstrumented() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfigurationTests.java index 5c16b62c69..1d3894f07f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,49 +36,57 @@ import static org.assertj.core.api.Assertions.assertThat; class CacheMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withUserConfiguration(CachingConfiguration.class).withConfiguration( - AutoConfigurations.of(CacheAutoConfiguration.class, CacheMetricsAutoConfiguration.class)); + .withUserConfiguration(CachingConfiguration.class) + .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class, CacheMetricsAutoConfiguration.class)); @Test void autoConfiguredCache2kIsInstrumented() { this.contextRunner.withPropertyValues("spring.cache.type=cache2k", "spring.cache.cache-names=cache1,cache2") - .run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("cache.gets").tags("name", "cache1").tags("cache.manager", "cacheManager").meter(); - registry.get("cache.gets").tags("name", "cache2").tags("cache.manager", "cacheManager").meter(); - }); + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("cache.gets").tags("name", "cache1").tags("cache.manager", "cacheManager").meter(); + registry.get("cache.gets").tags("name", "cache2").tags("cache.manager", "cacheManager").meter(); + }); } @Test void autoConfiguredCacheManagerIsInstrumented() { this.contextRunner.withPropertyValues("spring.cache.type=caffeine", "spring.cache.cache-names=cache1,cache2") - .run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("cache.gets").tags("name", "cache1").tags("cache.manager", "cacheManager").meter(); - registry.get("cache.gets").tags("name", "cache2").tags("cache.manager", "cacheManager").meter(); - }); + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("cache.gets").tags("name", "cache1").tags("cache.manager", "cacheManager").meter(); + registry.get("cache.gets").tags("name", "cache2").tags("cache.manager", "cacheManager").meter(); + }); } @Test void autoConfiguredNonSupportedCacheManagerIsIgnored() { this.contextRunner.withPropertyValues("spring.cache.type=simple", "spring.cache.cache-names=cache1,cache2") - .run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("cache.gets").tags("name", "cache1").tags("cache.manager", "cacheManager") - .meter()).isNull(); - assertThat(registry.find("cache.gets").tags("name", "cache2").tags("cache.manager", "cacheManager") - .meter()).isNull(); - }); + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("cache.gets") + .tags("name", "cache1") + .tags("cache.manager", "cacheManager") + .meter()).isNull(); + assertThat(registry.find("cache.gets") + .tags("name", "cache2") + .tags("cache.manager", "cacheManager") + .meter()).isNull(); + }); } @Test void cacheInstrumentationCanBeDisabled() { - this.contextRunner.withPropertyValues("management.metrics.enable.cache=false", "spring.cache.type=caffeine", - "spring.cache.cache-names=cache1").run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("cache.requests").tags("name", "cache1") - .tags("cache.manager", "cacheManager").meter()).isNull(); - }); + this.contextRunner + .withPropertyValues("management.metrics.enable.cache=false", "spring.cache.type=caffeine", + "spring.cache.cache-names=cache1") + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("cache.requests") + .tags("name", "cache1") + .tags("cache.manager", "cacheManager") + .meter()).isNull(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/MetricsRepositoryMethodInvocationListenerBeanPostProcessorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/MetricsRepositoryMethodInvocationListenerBeanPostProcessorTests.java index 2077bfeefa..739e351658 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/MetricsRepositoryMethodInvocationListenerBeanPostProcessorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/MetricsRepositoryMethodInvocationListenerBeanPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ class MetricsRepositoryMethodInvocationListenerBeanPostProcessorTests { Object result = this.postProcessor.postProcessBeforeInitialization(bean, "name"); assertThat(result).isSameAs(bean); ArgumentCaptor customizer = ArgumentCaptor - .forClass(RepositoryFactoryCustomizer.class); + .forClass(RepositoryFactoryCustomizer.class); then(bean).should().addRepositoryFactoryCustomizer(customizer.capture()); RepositoryFactorySupport repositoryFactory = mock(RepositoryFactorySupport.class); customizer.getValue().customize(repositoryFactory); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/RepositoryMetricsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/RepositoryMetricsAutoConfigurationIntegrationTests.java index 53c110fdee..e0b176ec7d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/RepositoryMetricsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/RepositoryMetricsAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,25 +43,27 @@ import static org.assertj.core.api.Assertions.assertThat; class RepositoryMetricsAutoConfigurationIntegrationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration( - AutoConfigurations.of(HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, RepositoryMetricsAutoConfiguration.class)) - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, TestConfig.class); + .withConfiguration( + AutoConfigurations.of(HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, RepositoryMetricsAutoConfiguration.class)) + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, TestConfig.class); @Test void repositoryMethodCallRecordsMetrics() { this.contextRunner.run((context) -> { context.getBean(CityRepository.class).count(); MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.get("spring.data.repository.invocations").tag("repository", "CityRepository").timer() - .count()).isEqualTo(1); + assertThat(registry.get("spring.data.repository.invocations") + .tag("repository", "CityRepository") + .timer() + .count()).isEqualTo(1); }); } @Test void doesNotPreventMeterBindersFromDependingUponSpringDataRepositories() { this.contextRunner.withUserConfiguration(SpringDataRepositoryMeterBinderConfiguration.class) - .run((context) -> assertThat(context).hasNotFailed()); + .run((context) -> assertThat(context).hasNotFailed()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/RepositoryMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/RepositoryMetricsAutoConfigurationTests.java index bf461b030f..2d4e21993d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/RepositoryMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/RepositoryMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,13 +58,13 @@ import static org.mockito.Mockito.mock; class RepositoryMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(RepositoryMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RepositoryMetricsAutoConfiguration.class)); @Test void backsOffWhenMeterRegistryIsMissing() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RepositoryMetricsAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(RepositoryTagsProvider.class)); + .withConfiguration(AutoConfigurations.of(RepositoryMetricsAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(RepositoryTagsProvider.class)); } @Test @@ -87,58 +87,60 @@ class RepositoryMetricsAutoConfigurationTests { @Test void metricsRepositoryMethodInvocationListenerBacksOff() { this.contextRunner.withUserConfiguration(MetricsRepositoryMethodInvocationListenerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(MetricsRepositoryMethodInvocationListener.class); - assertThat(context).hasSingleBean(TestMetricsRepositoryMethodInvocationListener.class); - }); + .run((context) -> { + assertThat(context).hasSingleBean(MetricsRepositoryMethodInvocationListener.class); + assertThat(context).hasSingleBean(TestMetricsRepositoryMethodInvocationListener.class); + }); } @Test void metricNameCanBeConfigured() { this.contextRunner.withPropertyValues("management.metrics.data.repository.metric-name=datarepo") - .run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context, ExampleRepository.class); - Timer timer = registry.get("datarepo").timer(); - assertThat(timer).isNotNull(); - }); + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context, ExampleRepository.class); + Timer timer = registry.get("datarepo").timer(); + assertThat(timer).isNotNull(); + }); } @Test void autoTimeRequestsCanBeConfigured() { - this.contextRunner.withPropertyValues("management.metrics.data.repository.autotime.enabled=true", - "management.metrics.data.repository.autotime.percentiles=0.5,0.7").run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context, ExampleRepository.class); - Timer timer = registry.get("spring.data.repository.invocations").timer(); - HistogramSnapshot snapshot = timer.takeSnapshot(); - assertThat(snapshot.percentileValues()).hasSize(2); - assertThat(snapshot.percentileValues()[0].percentile()).isEqualTo(0.5); - assertThat(snapshot.percentileValues()[1].percentile()).isEqualTo(0.7); - }); + this.contextRunner + .withPropertyValues("management.metrics.data.repository.autotime.enabled=true", + "management.metrics.data.repository.autotime.percentiles=0.5,0.7") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context, ExampleRepository.class); + Timer timer = registry.get("spring.data.repository.invocations").timer(); + HistogramSnapshot snapshot = timer.takeSnapshot(); + assertThat(snapshot.percentileValues()).hasSize(2); + assertThat(snapshot.percentileValues()[0].percentile()).isEqualTo(0.5); + assertThat(snapshot.percentileValues()[1].percentile()).isEqualTo(0.7); + }); } @Test void timerWorksWithTimedAnnotationsWhenAutoTimeRequestsIsFalse() { this.contextRunner.withPropertyValues("management.metrics.data.repository.autotime.enabled=false") - .run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context, ExampleAnnotatedRepository.class); - Collection meters = registry.get("spring.data.repository.invocations").meters(); - assertThat(meters).hasSize(1); - Meter meter = meters.iterator().next(); - assertThat(meter.getId().getTag("method")).isEqualTo("count"); - }); + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context, ExampleAnnotatedRepository.class); + Collection meters = registry.get("spring.data.repository.invocations").meters(); + assertThat(meters).hasSize(1); + Meter meter = meters.iterator().next(); + assertThat(meter.getId().getTag("method")).isEqualTo("count"); + }); } @Test void doesNotTriggerEarlyInitializationThatPreventsMeterBindersFromBindingMeters() { this.contextRunner.withUserConfiguration(MeterBinderConfiguration.class) - .run((context) -> assertThat(context.getBean(MeterRegistry.class).find("binder.test").counter()) - .isNotNull()); + .run((context) -> assertThat(context.getBean(MeterRegistry.class).find("binder.test").counter()) + .isNotNull()); } private MeterRegistry getInitializedMeterRegistry(AssertableApplicationContext context, Class repositoryInterface) { MetricsRepositoryMethodInvocationListener listener = context - .getBean(MetricsRepositoryMethodInvocationListener.class); + .getBean(MetricsRepositoryMethodInvocationListener.class); ReflectionUtils.doWithLocalMethods(repositoryInterface, (method) -> { RepositoryMethodInvocationResult result = mock(RepositoryMethodInvocationResult.class); given(result.getState()).willReturn(State.SUCCESS); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ConditionalOnEnabledMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ConditionalOnEnabledMetricsExportAutoConfigurationTests.java index f00365ab08..5632611059 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ConditionalOnEnabledMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ConditionalOnEnabledMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,21 +40,21 @@ class ConditionalOnEnabledMetricsExportAutoConfigurationTests { @Test void exporterCanBeSpecificallyDisabled() { this.contextRunner.withPropertyValues("management.metrics.export.simple.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean("simpleMeterRegistry")); + .run((context) -> assertThat(context).doesNotHaveBean("simpleMeterRegistry")); } @Test void exporterCanBeGloballyDisabled() { this.contextRunner.withPropertyValues("management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean("simpleMeterRegistry")); + .run((context) -> assertThat(context).doesNotHaveBean("simpleMeterRegistry")); } @Test void exporterCanBeGloballyDisabledWithSpecificOverride() { this.contextRunner - .withPropertyValues("management.metrics.export.defaults.enabled=false", - "management.metrics.export.simple.enabled=true") - .run((context) -> assertThat(context).hasBean("simpleMeterRegistry")); + .withPropertyValues("management.metrics.export.defaults.enabled=false", + "management.metrics.export.simple.enabled=true") + .run((context) -> assertThat(context).hasBean("simpleMeterRegistry")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfigurationTests.java index c40f213733..ead0b75421 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class AppOpticsMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AppOpticsMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(AppOpticsMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -47,50 +47,54 @@ class AppOpticsMetricsExportAutoConfigurationTests { @Test void autoConfiguresItsConfigAndMeterRegistry() { this.contextRunner.withPropertyValues("management.metrics.export.appoptics.api-token=abcde") - .withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(AppOpticsMeterRegistry.class).hasSingleBean(AppOpticsConfig.class)); + .withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(AppOpticsMeterRegistry.class) + .hasSingleBean(AppOpticsConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(AppOpticsMeterRegistry.class) - .doesNotHaveBean(AppOpticsConfig.class)); + .withPropertyValues("management.metrics.export.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(AppOpticsMeterRegistry.class) + .doesNotHaveBean(AppOpticsConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.appoptics.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(AppOpticsMeterRegistry.class) - .doesNotHaveBean(AppOpticsConfig.class)); + .withPropertyValues("management.metrics.export.appoptics.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(AppOpticsMeterRegistry.class) + .doesNotHaveBean(AppOpticsConfig.class)); } @Test void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(AppOpticsMeterRegistry.class) - .hasSingleBean(AppOpticsConfig.class).hasBean("customConfig")); + .run((context) -> assertThat(context).hasSingleBean(AppOpticsMeterRegistry.class) + .hasSingleBean(AppOpticsConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { this.contextRunner.withPropertyValues("management.metrics.export.appoptics.api-token=abcde") - .withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(AppOpticsMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(AppOpticsConfig.class)); + .withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(AppOpticsMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(AppOpticsConfig.class)); } @Test void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withPropertyValues("management.metrics.export.appoptics.api-token=abcde") - .withUserConfiguration(BaseConfiguration.class).run((context) -> { - AppOpticsMeterRegistry registry = context.getBean(AppOpticsMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + .withUserConfiguration(BaseConfiguration.class) + .run((context) -> { + AppOpticsMeterRegistry registry = context.getBean(AppOpticsMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfigurationTests.java index f0fdf313f1..ca5423c3f6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class AtlasMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AtlasMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(AtlasMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -46,36 +46,41 @@ class AtlasMetricsExportAutoConfigurationTests { @Test void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(AtlasMeterRegistry.class).hasSingleBean(AtlasConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(AtlasMeterRegistry.class) + .hasSingleBean(AtlasConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(AtlasMeterRegistry.class) - .doesNotHaveBean(AtlasConfig.class)); + .withPropertyValues("management.metrics.export.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(AtlasMeterRegistry.class) + .doesNotHaveBean(AtlasConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.atlas.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(AtlasMeterRegistry.class) - .doesNotHaveBean(AtlasConfig.class)); + .withPropertyValues("management.metrics.export.atlas.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(AtlasMeterRegistry.class) + .doesNotHaveBean(AtlasConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(AtlasMeterRegistry.class).hasSingleBean(AtlasConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(AtlasMeterRegistry.class) + .hasSingleBean(AtlasConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(AtlasMeterRegistry.class).hasBean("customRegistry").hasSingleBean(AtlasConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(AtlasMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(AtlasConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesConfigAdapterTests.java index 48b777c69d..b84575c0f7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesConfigAdapterTests.java @@ -90,7 +90,7 @@ class AtlasPropertiesConfigAdapterTests { AtlasProperties properties = new AtlasProperties(); properties.setConfigRefreshFrequency(Duration.ofMinutes(5)); assertThat(new AtlasPropertiesConfigAdapter(properties).configRefreshFrequency()) - .isEqualTo(Duration.ofMinutes(5)); + .isEqualTo(Duration.ofMinutes(5)); } @Test @@ -105,7 +105,7 @@ class AtlasPropertiesConfigAdapterTests { AtlasProperties properties = new AtlasProperties(); properties.setConfigUri("https://atlas.example.com/config"); assertThat(new AtlasPropertiesConfigAdapter(properties).configUri()) - .isEqualTo("https://atlas.example.com/config"); + .isEqualTo("https://atlas.example.com/config"); } @Test @@ -113,7 +113,7 @@ class AtlasPropertiesConfigAdapterTests { AtlasProperties properties = new AtlasProperties(); properties.setEvalUri("https://atlas.example.com/evaluate"); assertThat(new AtlasPropertiesConfigAdapter(properties).evalUri()) - .isEqualTo("https://atlas.example.com/evaluate"); + .isEqualTo("https://atlas.example.com/evaluate"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfigurationTests.java index abb6192b06..b7392318c8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class DatadogMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DatadogMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(DatadogMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -47,56 +47,60 @@ class DatadogMetricsExportAutoConfigurationTests { @Test void failsWithoutAnApiKey() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context).hasFailed()); + .run((context) -> assertThat(context).hasFailed()); } @Test void autoConfiguresConfigAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.datadog.api-key=abcde") - .run((context) -> assertThat(context).hasSingleBean(DatadogMeterRegistry.class) - .hasSingleBean(DatadogConfig.class)); + .withPropertyValues("management.metrics.export.datadog.api-key=abcde") + .run((context) -> assertThat(context).hasSingleBean(DatadogMeterRegistry.class) + .hasSingleBean(DatadogConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(DatadogMeterRegistry.class) - .doesNotHaveBean(DatadogConfig.class)); + .withPropertyValues("management.metrics.export.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(DatadogMeterRegistry.class) + .doesNotHaveBean(DatadogConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.datadog.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(DatadogMeterRegistry.class) - .doesNotHaveBean(DatadogConfig.class)); + .withPropertyValues("management.metrics.export.datadog.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(DatadogMeterRegistry.class) + .doesNotHaveBean(DatadogConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(DatadogMeterRegistry.class).hasSingleBean(DatadogConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(DatadogMeterRegistry.class) + .hasSingleBean(DatadogConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .withPropertyValues("management.metrics.export.datadog.api-key=abcde") - .run((context) -> assertThat(context).hasSingleBean(DatadogMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(DatadogConfig.class)); + .withPropertyValues("management.metrics.export.datadog.api-key=abcde") + .run((context) -> assertThat(context).hasSingleBean(DatadogMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(DatadogConfig.class)); } @Test void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.datadog.api-key=abcde").run((context) -> { - DatadogMeterRegistry registry = context.getBean(DatadogMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + .withPropertyValues("management.metrics.export.datadog.api-key=abcde") + .run((context) -> { + DatadogMeterRegistry registry = context.getBean(DatadogMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfigurationTests.java index 317b784d67..5ce8acd575 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,7 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat; class DynatraceMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DynatraceMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(DynatraceMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -50,56 +50,61 @@ class DynatraceMetricsExportAutoConfigurationTests { @Test void failsWithADeviceIdWithoutAUri() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.dynatrace.device-id:dev-1") - .run((context) -> assertThat(context).hasFailed()); + .withPropertyValues("management.metrics.export.dynatrace.device-id:dev-1") + .run((context) -> assertThat(context).hasFailed()); } @Test void autoConfiguresConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).with(v1MandatoryProperties()) - .run((context) -> assertThat(context).hasSingleBean(DynatraceMeterRegistry.class) - .hasSingleBean(DynatraceConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .with(v1MandatoryProperties()) + .run((context) -> assertThat(context).hasSingleBean(DynatraceMeterRegistry.class) + .hasSingleBean(DynatraceConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(DynatraceMeterRegistry.class) - .doesNotHaveBean(DynatraceConfig.class)); + .withPropertyValues("management.metrics.export.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(DynatraceMeterRegistry.class) + .doesNotHaveBean(DynatraceConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.dynatrace.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(DynatraceMeterRegistry.class) - .doesNotHaveBean(DynatraceConfig.class)); + .withPropertyValues("management.metrics.export.dynatrace.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(DynatraceMeterRegistry.class) + .doesNotHaveBean(DynatraceConfig.class)); } @Test void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(DynatraceMeterRegistry.class) - .hasSingleBean(DynatraceConfig.class).hasBean("customConfig")); + .run((context) -> assertThat(context).hasSingleBean(DynatraceMeterRegistry.class) + .hasSingleBean(DynatraceConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).with(v1MandatoryProperties()) - .run((context) -> assertThat(context).hasSingleBean(DynatraceMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(DynatraceConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) + .with(v1MandatoryProperties()) + .run((context) -> assertThat(context).hasSingleBean(DynatraceMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(DynatraceConfig.class)); } @Test void stopsMeterRegistryForV1ApiWhenContextIsClosed() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).with(v1MandatoryProperties()) - .run((context) -> { - DynatraceMeterRegistry registry = context.getBean(DynatraceMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .with(v1MandatoryProperties()) + .run((context) -> { + DynatraceMeterRegistry registry = context.getBean(DynatraceMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapterTests.java index 97117ce9ad..b677c826f4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -140,7 +140,7 @@ class DynatracePropertiesConfigAdapterTests { defaultDimensions.put("dim2", "value2"); properties.getV2().setDefaultDimensions(defaultDimensions); assertThat(new DynatracePropertiesConfigAdapter(properties).defaultDimensions()) - .containsExactlyEntriesOf(defaultDimensions); + .containsExactlyEntriesOf(defaultDimensions); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesTests.java index b99e54aa41..05770f5e35 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesTests.java @@ -39,7 +39,7 @@ class DynatracePropertiesTests extends StepRegistryPropertiesTests { assertThat(properties.getTechnologyType()).isEqualTo(config.technologyType()); assertThat(properties.getV1().getTechnologyType()).isEqualTo(config.technologyType()); assertThat(properties.getV2().isUseDynatraceSummaryInstruments()) - .isEqualTo(config.useDynatraceSummaryInstruments()); + .isEqualTo(config.useDynatraceSummaryInstruments()); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfigurationTests.java index 5cc9071bbf..967ebe8e0a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,7 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ElasticMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ElasticMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -47,38 +47,42 @@ class ElasticMetricsExportAutoConfigurationTests { @Test void autoConfiguresConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(ElasticMeterRegistry.class).hasSingleBean(ElasticConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(ElasticMeterRegistry.class) + .hasSingleBean(ElasticConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(ElasticMeterRegistry.class) - .doesNotHaveBean(ElasticConfig.class)); + .withPropertyValues("management.metrics.export.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(ElasticMeterRegistry.class) + .doesNotHaveBean(ElasticConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.elastic.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(ElasticMeterRegistry.class) - .doesNotHaveBean(ElasticConfig.class)); + .withPropertyValues("management.metrics.export.elastic.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(ElasticMeterRegistry.class) + .doesNotHaveBean(ElasticConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(ElasticMeterRegistry.class).hasSingleBean(ElasticConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(ElasticMeterRegistry.class) + .hasSingleBean(ElasticConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ElasticMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(ElasticConfig.class)); + .run((context) -> assertThat(context).hasSingleBean(ElasticMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(ElasticConfig.class)); } @Test @@ -94,19 +98,23 @@ class ElasticMetricsExportAutoConfigurationTests { @Test void apiKeyCredentialsIsMutuallyExclusiveWithUserName() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.elastic.api-key-credentials:secret", - "management.metrics.export.elastic.user-name:alice") - .run((context) -> assertThat(context).hasFailed().getFailure().getRootCause() - .isInstanceOf(MutuallyExclusiveConfigurationPropertiesException.class)); + .withPropertyValues("management.metrics.export.elastic.api-key-credentials:secret", + "management.metrics.export.elastic.user-name:alice") + .run((context) -> assertThat(context).hasFailed() + .getFailure() + .getRootCause() + .isInstanceOf(MutuallyExclusiveConfigurationPropertiesException.class)); } @Test void apiKeyCredentialsIsMutuallyExclusiveWithPassword() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.elastic.api-key-credentials:secret", - "management.metrics.export.elastic.password:secret") - .run((context) -> assertThat(context).hasFailed().getFailure().getRootCause() - .isInstanceOf(MutuallyExclusiveConfigurationPropertiesException.class)); + .withPropertyValues("management.metrics.export.elastic.api-key-credentials:secret", + "management.metrics.export.elastic.password:secret") + .run((context) -> assertThat(context).hasFailed() + .getFailure() + .getRootCause() + .isInstanceOf(MutuallyExclusiveConfigurationPropertiesException.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfigurationTests.java index 8dad0fbfac..0da1a1bcd1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class GangliaMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(GangliaMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(GangliaMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -46,37 +46,41 @@ class GangliaMetricsExportAutoConfigurationTests { @Test void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(GangliaMeterRegistry.class).hasSingleBean(GangliaConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(GangliaMeterRegistry.class) + .hasSingleBean(GangliaConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(GangliaMeterRegistry.class) - .doesNotHaveBean(GangliaConfig.class)); + .withPropertyValues("management.metrics.export.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(GangliaMeterRegistry.class) + .doesNotHaveBean(GangliaConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.ganglia.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(GangliaMeterRegistry.class) - .doesNotHaveBean(GangliaConfig.class)); + .withPropertyValues("management.metrics.export.ganglia.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(GangliaMeterRegistry.class) + .doesNotHaveBean(GangliaConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(GangliaMeterRegistry.class).hasSingleBean(GangliaConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(GangliaMeterRegistry.class) + .hasSingleBean(GangliaConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(GangliaMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(GangliaConfig.class)); + .run((context) -> assertThat(context).hasSingleBean(GangliaMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(GangliaConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaPropertiesConfigAdapterTests.java index 3afd087f8b..d837b00192 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaPropertiesConfigAdapterTests.java @@ -57,7 +57,7 @@ class GangliaPropertiesConfigAdapterTests { GangliaProperties properties = new GangliaProperties(); properties.setAddressingMode(UDPAddressingMode.UNICAST); assertThat(new GangliaPropertiesConfigAdapter(properties).addressingMode()) - .isEqualTo(UDPAddressingMode.UNICAST); + .isEqualTo(UDPAddressingMode.UNICAST); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphiteMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphiteMetricsExportAutoConfigurationTests.java index d2c0bdb55b..727a2e7a13 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphiteMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphiteMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat; class GraphiteMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(GraphiteMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(GraphiteMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -49,61 +49,65 @@ class GraphiteMetricsExportAutoConfigurationTests { @Test void autoConfiguresUseTagsAsPrefix() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.graphite.tags-as-prefix=app").run((context) -> { - assertThat(context).hasSingleBean(GraphiteMeterRegistry.class); - GraphiteMeterRegistry registry = context.getBean(GraphiteMeterRegistry.class); - registry.counter("test.count", Tags.of("app", "myapp")); - assertThat(registry.getDropwizardRegistry().getMeters()).containsOnlyKeys("myapp.testCount"); - }); + .withPropertyValues("management.metrics.export.graphite.tags-as-prefix=app") + .run((context) -> { + assertThat(context).hasSingleBean(GraphiteMeterRegistry.class); + GraphiteMeterRegistry registry = context.getBean(GraphiteMeterRegistry.class); + registry.counter("test.count", Tags.of("app", "myapp")); + assertThat(registry.getDropwizardRegistry().getMeters()).containsOnlyKeys("myapp.testCount"); + }); } @Test void autoConfiguresWithTagsAsPrefixCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.graphite.tags-as-prefix=app", - "management.metrics.export.graphite.graphite-tags-enabled=true") - .run((context) -> { - assertThat(context).hasSingleBean(GraphiteMeterRegistry.class); - GraphiteMeterRegistry registry = context.getBean(GraphiteMeterRegistry.class); - registry.counter("test.count", Tags.of("app", "myapp")); - assertThat(registry.getDropwizardRegistry().getMeters()).containsOnlyKeys("test.count;app=myapp"); - }); + .withPropertyValues("management.metrics.export.graphite.tags-as-prefix=app", + "management.metrics.export.graphite.graphite-tags-enabled=true") + .run((context) -> { + assertThat(context).hasSingleBean(GraphiteMeterRegistry.class); + GraphiteMeterRegistry registry = context.getBean(GraphiteMeterRegistry.class); + registry.counter("test.count", Tags.of("app", "myapp")); + assertThat(registry.getDropwizardRegistry().getMeters()).containsOnlyKeys("test.count;app=myapp"); + }); } @Test void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(GraphiteMeterRegistry.class).hasSingleBean(GraphiteConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(GraphiteMeterRegistry.class) + .hasSingleBean(GraphiteConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(GraphiteMeterRegistry.class) - .doesNotHaveBean(GraphiteConfig.class)); + .withPropertyValues("management.metrics.export.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(GraphiteMeterRegistry.class) + .doesNotHaveBean(GraphiteConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.graphite.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(GraphiteMeterRegistry.class) - .doesNotHaveBean(GraphiteConfig.class)); + .withPropertyValues("management.metrics.export.graphite.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(GraphiteMeterRegistry.class) + .doesNotHaveBean(GraphiteConfig.class)); } @Test void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(GraphiteMeterRegistry.class) - .hasSingleBean(GraphiteConfig.class).hasBean("customConfig")); + .run((context) -> assertThat(context).hasSingleBean(GraphiteMeterRegistry.class) + .hasSingleBean(GraphiteConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(GraphiteMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(GraphiteConfig.class)); + .run((context) -> assertThat(context).hasSingleBean(GraphiteMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(GraphiteConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfigurationTests.java index e15045fc8c..fc4ebad42a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,7 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; class HumioMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HumioMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HumioMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -47,36 +47,41 @@ class HumioMetricsExportAutoConfigurationTests { @Test void autoConfiguresConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(HumioMeterRegistry.class).hasSingleBean(HumioConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(HumioMeterRegistry.class) + .hasSingleBean(HumioConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(HumioMeterRegistry.class) - .doesNotHaveBean(HumioConfig.class)); + .withPropertyValues("management.metrics.export.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(HumioMeterRegistry.class) + .doesNotHaveBean(HumioConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.humio.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(HumioMeterRegistry.class) - .doesNotHaveBean(HumioConfig.class)); + .withPropertyValues("management.metrics.export.humio.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(HumioMeterRegistry.class) + .doesNotHaveBean(HumioConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(HumioMeterRegistry.class).hasSingleBean(HumioConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(HumioMeterRegistry.class) + .hasSingleBean(HumioConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(HumioMeterRegistry.class).hasBean("customRegistry").hasSingleBean(HumioConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(HumioMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(HumioConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesConfigAdapterTests.java index dffce7e8eb..37b99bb9bc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesConfigAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ class HumioPropertiesConfigAdapterTests { HumioProperties properties = new HumioProperties(); properties.setTags(Collections.singletonMap("name", "test")); assertThat(new HumioPropertiesConfigAdapter(properties).tags()) - .isEqualTo(Collections.singletonMap("name", "test")); + .isEqualTo(Collections.singletonMap("name", "test")); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfigurationTests.java index 5b306b7f61..229157cf6e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class InfluxMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(InfluxMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(InfluxMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -46,36 +46,41 @@ class InfluxMetricsExportAutoConfigurationTests { @Test void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(InfluxMeterRegistry.class).hasSingleBean(InfluxConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(InfluxMeterRegistry.class) + .hasSingleBean(InfluxConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(InfluxMeterRegistry.class) - .doesNotHaveBean(InfluxConfig.class)); + .withPropertyValues("management.metrics.export.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(InfluxMeterRegistry.class) + .doesNotHaveBean(InfluxConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.influx.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(InfluxMeterRegistry.class) - .doesNotHaveBean(InfluxConfig.class)); + .withPropertyValues("management.metrics.export.influx.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(InfluxMeterRegistry.class) + .doesNotHaveBean(InfluxConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(InfluxMeterRegistry.class).hasSingleBean(InfluxConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(InfluxMeterRegistry.class) + .hasSingleBean(InfluxConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(InfluxMeterRegistry.class).hasBean("customRegistry").hasSingleBean(InfluxConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(InfluxMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(InfluxConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfigurationTests.java index fc303d940b..31f3ade332 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class JmxMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JmxMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JmxMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -46,35 +46,40 @@ class JmxMetricsExportAutoConfigurationTests { @Test void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run( - (context) -> assertThat(context).hasSingleBean(JmxMeterRegistry.class).hasSingleBean(JmxConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(JmxMeterRegistry.class).hasSingleBean(JmxConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(JmxMeterRegistry.class) - .doesNotHaveBean(JmxConfig.class)); + .withPropertyValues("management.metrics.export.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(JmxMeterRegistry.class) + .doesNotHaveBean(JmxConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.jmx.enabled=false").run((context) -> assertThat(context) - .doesNotHaveBean(JmxMeterRegistry.class).doesNotHaveBean(JmxConfig.class)); + .withPropertyValues("management.metrics.export.jmx.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(JmxMeterRegistry.class) + .doesNotHaveBean(JmxConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(JmxMeterRegistry.class).hasSingleBean(JmxConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(JmxMeterRegistry.class) + .hasSingleBean(JmxConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(JmxMeterRegistry.class).hasBean("customRegistry").hasSingleBean(JmxConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(JmxMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(JmxConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfigurationTests.java index 44d73ac432..02962ca930 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class KairosMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(KairosMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(KairosMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -46,36 +46,41 @@ class KairosMetricsExportAutoConfigurationTests { @Test void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(KairosMeterRegistry.class).hasSingleBean(KairosConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(KairosMeterRegistry.class) + .hasSingleBean(KairosConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(KairosMeterRegistry.class) - .doesNotHaveBean(KairosConfig.class)); + .withPropertyValues("management.metrics.export.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(KairosMeterRegistry.class) + .doesNotHaveBean(KairosConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.kairos.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(KairosMeterRegistry.class) - .doesNotHaveBean(KairosConfig.class)); + .withPropertyValues("management.metrics.export.kairos.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(KairosMeterRegistry.class) + .doesNotHaveBean(KairosConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(KairosMeterRegistry.class).hasSingleBean(KairosConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(KairosMeterRegistry.class) + .hasSingleBean(KairosConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(KairosMeterRegistry.class).hasBean("customRegistry").hasSingleBean(KairosConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(KairosMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(KairosConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapterTests.java index 711069faff..94e6617c26 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,7 @@ class KairosPropertiesConfigAdapterTests KairosProperties properties = createProperties(); properties.setUri("https://kairos.example.com:8080/api/v1/datapoints"); assertThat(createConfigAdapter(properties).uri()) - .isEqualTo("https://kairos.example.com:8080/api/v1/datapoints"); + .isEqualTo("https://kairos.example.com:8080/api/v1/datapoints"); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfigurationTests.java index e0f063cc63..8848cbb5e0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ import static org.mockito.Mockito.mock; class NewRelicMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(NewRelicMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(NewRelicMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -51,112 +51,115 @@ class NewRelicMetricsExportAutoConfigurationTests { @Test void failsWithoutAnApiKey() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.newrelic.account-id=12345") - .run((context) -> assertThat(context).hasFailed()); + .withPropertyValues("management.metrics.export.newrelic.account-id=12345") + .run((context) -> assertThat(context).hasFailed()); } @Test void failsWithoutAnAccountId() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.newrelic.api-key=abcde") - .run((context) -> assertThat(context).hasFailed()); + .withPropertyValues("management.metrics.export.newrelic.api-key=abcde") + .run((context) -> assertThat(context).hasFailed()); } @Test void failsToAutoConfigureWithoutEventType() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", - "management.metrics.export.newrelic.account-id=12345", - "management.metrics.export.newrelic.event-type=") - .run((context) -> assertThat(context).hasFailed()); + .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", + "management.metrics.export.newrelic.account-id=12345", + "management.metrics.export.newrelic.event-type=") + .run((context) -> assertThat(context).hasFailed()); } @Test void autoConfiguresWithEventTypeOverridden() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", - "management.metrics.export.newrelic.account-id=12345", - "management.metrics.export.newrelic.event-type=wxyz") - .run((context) -> assertThat(context).hasSingleBean(NewRelicMeterRegistry.class) - .hasSingleBean(Clock.class).hasSingleBean(NewRelicConfig.class)); + .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", + "management.metrics.export.newrelic.account-id=12345", + "management.metrics.export.newrelic.event-type=wxyz") + .run((context) -> assertThat(context).hasSingleBean(NewRelicMeterRegistry.class) + .hasSingleBean(Clock.class) + .hasSingleBean(NewRelicConfig.class)); } @Test void autoConfiguresWithMeterNameEventTypeEnabledAndWithoutEventType() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", - "management.metrics.export.newrelic.account-id=12345", - "management.metrics.export.newrelic.event-type=", - "management.metrics.export.newrelic.meter-name-event-type-enabled=true") - .run((context) -> assertThat(context).hasSingleBean(NewRelicMeterRegistry.class) - .hasSingleBean(Clock.class).hasSingleBean(NewRelicConfig.class)); + .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", + "management.metrics.export.newrelic.account-id=12345", + "management.metrics.export.newrelic.event-type=", + "management.metrics.export.newrelic.meter-name-event-type-enabled=true") + .run((context) -> assertThat(context).hasSingleBean(NewRelicMeterRegistry.class) + .hasSingleBean(Clock.class) + .hasSingleBean(NewRelicConfig.class)); } @Test void autoConfiguresWithAccountIdAndApiKey() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", - "management.metrics.export.newrelic.account-id=12345") - .run((context) -> assertThat(context).hasSingleBean(NewRelicMeterRegistry.class) - .hasSingleBean(Clock.class).hasSingleBean(NewRelicConfig.class)); + .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", + "management.metrics.export.newrelic.account-id=12345") + .run((context) -> assertThat(context).hasSingleBean(NewRelicMeterRegistry.class) + .hasSingleBean(Clock.class) + .hasSingleBean(NewRelicConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(NewRelicMeterRegistry.class) - .doesNotHaveBean(NewRelicConfig.class)); + .withPropertyValues("management.metrics.export.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(NewRelicMeterRegistry.class) + .doesNotHaveBean(NewRelicConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.newrelic.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(NewRelicMeterRegistry.class) - .doesNotHaveBean(NewRelicConfig.class)); + .withPropertyValues("management.metrics.export.newrelic.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(NewRelicMeterRegistry.class) + .doesNotHaveBean(NewRelicConfig.class)); } @Test void allowsConfigToBeCustomized() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", - "management.metrics.export.newrelic.account-id=12345") - .run((context) -> assertThat(context).hasSingleBean(NewRelicConfig.class).hasBean("customConfig")); + .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", + "management.metrics.export.newrelic.account-id=12345") + .run((context) -> assertThat(context).hasSingleBean(NewRelicConfig.class).hasBean("customConfig")); } @Test void allowsRegistryToBeCustomized() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", - "management.metrics.export.newrelic.account-id=12345") - .run((context) -> assertThat(context).hasSingleBean(NewRelicMeterRegistry.class) - .hasBean("customRegistry")); + .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", + "management.metrics.export.newrelic.account-id=12345") + .run((context) -> assertThat(context).hasSingleBean(NewRelicMeterRegistry.class).hasBean("customRegistry")); } @Test void allowsClientProviderToBeCustomized() { this.contextRunner.withUserConfiguration(CustomClientProviderConfiguration.class) - .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", - "management.metrics.export.newrelic.account-id=12345") - .run((context) -> { - assertThat(context).hasSingleBean(NewRelicMeterRegistry.class); - assertThat(context.getBean(NewRelicMeterRegistry.class)) - .hasFieldOrPropertyWithValue("clientProvider", context.getBean("customClientProvider")); - }); + .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", + "management.metrics.export.newrelic.account-id=12345") + .run((context) -> { + assertThat(context).hasSingleBean(NewRelicMeterRegistry.class); + assertThat(context.getBean(NewRelicMeterRegistry.class)).hasFieldOrPropertyWithValue("clientProvider", + context.getBean("customClientProvider")); + }); } @Test void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner - .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", - "management.metrics.export.newrelic.account-id=abcde") - .withUserConfiguration(BaseConfiguration.class).run((context) -> { - NewRelicMeterRegistry registry = context.getBean(NewRelicMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", + "management.metrics.export.newrelic.account-id=abcde") + .withUserConfiguration(BaseConfiguration.class) + .run((context) -> { + NewRelicMeterRegistry registry = context.getBean(NewRelicMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java index 6e28dace82..df8d38ea55 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,7 +58,7 @@ import static org.assertj.core.api.Assertions.assertThat; class PrometheusMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(PrometheusMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(PrometheusMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -68,150 +68,161 @@ class PrometheusMetricsExportAutoConfigurationTests { @Test void autoConfiguresItsConfigCollectorRegistryAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) - .hasSingleBean(CollectorRegistry.class).hasSingleBean(PrometheusConfig.class)); + .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) + .hasSingleBean(CollectorRegistry.class) + .hasSingleBean(PrometheusConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(PrometheusMeterRegistry.class) - .doesNotHaveBean(CollectorRegistry.class).doesNotHaveBean(PrometheusConfig.class)); + .withPropertyValues("management.metrics.export.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(PrometheusMeterRegistry.class) + .doesNotHaveBean(CollectorRegistry.class) + .doesNotHaveBean(PrometheusConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.prometheus.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(PrometheusMeterRegistry.class) - .doesNotHaveBean(CollectorRegistry.class).doesNotHaveBean(PrometheusConfig.class)); + .withPropertyValues("management.metrics.export.prometheus.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(PrometheusMeterRegistry.class) + .doesNotHaveBean(CollectorRegistry.class) + .doesNotHaveBean(PrometheusConfig.class)); } @Test void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) - .hasSingleBean(CollectorRegistry.class).hasSingleBean(PrometheusConfig.class) - .hasBean("customConfig")); + .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) + .hasSingleBean(CollectorRegistry.class) + .hasSingleBean(PrometheusConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(CollectorRegistry.class) - .hasSingleBean(PrometheusConfig.class)); + .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(CollectorRegistry.class) + .hasSingleBean(PrometheusConfig.class)); } @Test void allowsCustomCollectorRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomCollectorRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) - .hasBean("customCollectorRegistry").hasSingleBean(CollectorRegistry.class) - .hasSingleBean(PrometheusConfig.class)); + .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) + .hasBean("customCollectorRegistry") + .hasSingleBean(CollectorRegistry.class) + .hasSingleBean(PrometheusConfig.class)); } @Test void autoConfiguresExemplarSamplerIfSpanContextSupplierIsPresent() { this.contextRunner.withUserConfiguration(ExemplarsConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(SpanContextSupplier.class) - .hasSingleBean(ExemplarSampler.class).hasSingleBean(PrometheusMeterRegistry.class)); + .run((context) -> assertThat(context).hasSingleBean(SpanContextSupplier.class) + .hasSingleBean(ExemplarSampler.class) + .hasSingleBean(PrometheusMeterRegistry.class)); } @Test void exemplarSamplerIsNotAutoConfiguredIfSpanContextSupplierIsMissing() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(SpanContextSupplier.class) - .doesNotHaveBean(ExemplarSampler.class).hasSingleBean(PrometheusMeterRegistry.class)); + .run((context) -> assertThat(context).doesNotHaveBean(SpanContextSupplier.class) + .doesNotHaveBean(ExemplarSampler.class) + .hasSingleBean(PrometheusMeterRegistry.class)); } @Test void addsScrapeEndpointToManagementContext() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=prometheus") - .run((context) -> assertThat(context).hasSingleBean(PrometheusScrapeEndpoint.class)); + .withUserConfiguration(BaseConfiguration.class) + .withPropertyValues("management.endpoints.web.exposure.include=prometheus") + .run((context) -> assertThat(context).hasSingleBean(PrometheusScrapeEndpoint.class)); } @Test void scrapeEndpointNotAddedToManagementContextWhenNotExposed() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(PrometheusScrapeEndpoint.class)); + .withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(PrometheusScrapeEndpoint.class)); } @Test void scrapeEndpointCanBeDisabled() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withPropertyValues("management.endpoints.web.exposure.include=prometheus") - .withPropertyValues("management.endpoint.prometheus.enabled=false") - .withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(PrometheusScrapeEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=prometheus") + .withPropertyValues("management.endpoint.prometheus.enabled=false") + .withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(PrometheusScrapeEndpoint.class)); } @Test void allowsCustomScrapeEndpointToBeUsed() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withUserConfiguration(CustomEndpointConfiguration.class).run((context) -> assertThat(context) - .hasBean("customEndpoint").hasSingleBean(PrometheusScrapeEndpoint.class)); + .withUserConfiguration(CustomEndpointConfiguration.class) + .run((context) -> assertThat(context).hasBean("customEndpoint") + .hasSingleBean(PrometheusScrapeEndpoint.class)); } @Test void pushGatewayIsNotConfiguredWhenEnabledFlagIsNotSet() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(PrometheusPushGatewayManager.class)); + .run((context) -> assertThat(context).doesNotHaveBean(PrometheusPushGatewayManager.class)); } @Test void withPushGatewayEnabled(CapturedOutput output) { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true") - .withUserConfiguration(BaseConfiguration.class).run((context) -> { - assertThat(output).doesNotContain("Invalid PushGateway base url"); - hasGatewayURL(context, "http://localhost:9091/metrics/"); - }); + .withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true") + .withUserConfiguration(BaseConfiguration.class) + .run((context) -> { + assertThat(output).doesNotContain("Invalid PushGateway base url"); + hasGatewayURL(context, "http://localhost:9091/metrics/"); + }); } @Test void withPushGatewayNoBasicAuth() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true") - .withUserConfiguration(BaseConfiguration.class) - .run(hasHttpConnectionFactory((httpConnectionFactory) -> assertThat(httpConnectionFactory) - .isInstanceOf(DefaultHttpConnectionFactory.class))); + .withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true") + .withUserConfiguration(BaseConfiguration.class) + .run(hasHttpConnectionFactory((httpConnectionFactory) -> assertThat(httpConnectionFactory) + .isInstanceOf(DefaultHttpConnectionFactory.class))); } @Test @Deprecated void withCustomLegacyPushGatewayURL(CapturedOutput output) { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true", - "management.metrics.export.prometheus.pushgateway.base-url=localhost:9090") - .withUserConfiguration(BaseConfiguration.class).run((context) -> { - assertThat(output).contains("Invalid PushGateway base url").contains("localhost:9090"); - hasGatewayURL(context, "http://localhost:9090/metrics/"); - }); + .withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true", + "management.metrics.export.prometheus.pushgateway.base-url=localhost:9090") + .withUserConfiguration(BaseConfiguration.class) + .run((context) -> { + assertThat(output).contains("Invalid PushGateway base url").contains("localhost:9090"); + hasGatewayURL(context, "http://localhost:9090/metrics/"); + }); } @Test void withCustomPushGatewayURL() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true", - "management.metrics.export.prometheus.pushgateway.base-url=https://example.com:8080") - .withUserConfiguration(BaseConfiguration.class) - .run((context) -> hasGatewayURL(context, "https://example.com:8080/metrics/")); + .withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true", + "management.metrics.export.prometheus.pushgateway.base-url=https://example.com:8080") + .withUserConfiguration(BaseConfiguration.class) + .run((context) -> hasGatewayURL(context, "https://example.com:8080/metrics/")); } @Test void withPushGatewayBasicAuth() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true", - "management.metrics.export.prometheus.pushgateway.username=admin", - "management.metrics.export.prometheus.pushgateway.password=secret") - .withUserConfiguration(BaseConfiguration.class) - .run(hasHttpConnectionFactory((httpConnectionFactory) -> assertThat(httpConnectionFactory) - .isInstanceOf(BasicAuthHttpConnectionFactory.class))); + .withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true", + "management.metrics.export.prometheus.pushgateway.username=admin", + "management.metrics.export.prometheus.pushgateway.password=secret") + .withUserConfiguration(BaseConfiguration.class) + .run(hasHttpConnectionFactory((httpConnectionFactory) -> assertThat(httpConnectionFactory) + .isInstanceOf(BasicAuthHttpConnectionFactory.class))); } private void hasGatewayURL(AssertableApplicationContext context, String url) { @@ -223,7 +234,7 @@ class PrometheusMetricsExportAutoConfigurationTests { return (context) -> { PushGateway pushGateway = getPushGateway(context); httpConnectionFactory - .accept((HttpConnectionFactory) ReflectionTestUtils.getField(pushGateway, "connectionFactory")); + .accept((HttpConnectionFactory) ReflectionTestUtils.getField(pushGateway, "connectionFactory")); }; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusPropertiesConfigAdapterTests.java index 66aa5920aa..4fa2176884 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusPropertiesConfigAdapterTests.java @@ -42,7 +42,7 @@ class PrometheusPropertiesConfigAdapterTests { PrometheusProperties properties = new PrometheusProperties(); properties.setHistogramFlavor(HistogramFlavor.VictoriaMetrics); assertThat(new PrometheusPropertiesConfigAdapter(properties).histogramFlavor()) - .isEqualTo(HistogramFlavor.VictoriaMetrics); + .isEqualTo(HistogramFlavor.VictoriaMetrics); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxMetricsExportAutoConfigurationTests.java index c444ab0909..3192ab0eac 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class SignalFxMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SignalFxMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SignalFxMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -47,59 +47,64 @@ class SignalFxMetricsExportAutoConfigurationTests { @Test void failsWithoutAnAccessToken() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context).hasFailed()); + .run((context) -> assertThat(context).hasFailed()); } @Test void autoConfiguresWithAnAccessToken() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.signalfx.access-token=abcde") - .run((context) -> assertThat(context).hasSingleBean(SignalFxMeterRegistry.class) - .hasSingleBean(Clock.class).hasSingleBean(SignalFxConfig.class)); + .withPropertyValues("management.metrics.export.signalfx.access-token=abcde") + .run((context) -> assertThat(context).hasSingleBean(SignalFxMeterRegistry.class) + .hasSingleBean(Clock.class) + .hasSingleBean(SignalFxConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(SignalFxMeterRegistry.class) - .doesNotHaveBean(SignalFxConfig.class)); + .withPropertyValues("management.metrics.export.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(SignalFxMeterRegistry.class) + .doesNotHaveBean(SignalFxConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.signalfx.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(SignalFxMeterRegistry.class) - .doesNotHaveBean(SignalFxConfig.class)); + .withPropertyValues("management.metrics.export.signalfx.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(SignalFxMeterRegistry.class) + .doesNotHaveBean(SignalFxConfig.class)); } @Test void allowsConfigToBeCustomized() { this.contextRunner.withPropertyValues("management.metrics.export.signalfx.access-token=abcde") - .withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(Clock.class) - .hasSingleBean(SignalFxMeterRegistry.class).hasSingleBean(SignalFxConfig.class) - .hasBean("customConfig")); + .withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(Clock.class) + .hasSingleBean(SignalFxMeterRegistry.class) + .hasSingleBean(SignalFxConfig.class) + .hasBean("customConfig")); } @Test void allowsRegistryToBeCustomized() { this.contextRunner.withPropertyValues("management.metrics.export.signalfx.access-token=abcde") - .withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(Clock.class).hasSingleBean(SignalFxConfig.class) - .hasSingleBean(SignalFxMeterRegistry.class).hasBean("customRegistry")); + .withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(Clock.class) + .hasSingleBean(SignalFxConfig.class) + .hasSingleBean(SignalFxMeterRegistry.class) + .hasBean("customRegistry")); } @Test void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withPropertyValues("management.metrics.export.signalfx.access-token=abcde") - .withUserConfiguration(BaseConfiguration.class).run((context) -> { - SignalFxMeterRegistry registry = context.getBean(SignalFxMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + .withUserConfiguration(BaseConfiguration.class) + .run((context) -> { + SignalFxMeterRegistry registry = context.getBean(SignalFxMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfigurationTests.java index 45f37037d0..3050782b5e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,40 +40,44 @@ import static org.mockito.Mockito.mock; class SimpleMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SimpleMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SimpleMetricsExportAutoConfiguration.class)); @Test void autoConfiguresConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(SimpleMeterRegistry.class).hasSingleBean(Clock.class).hasSingleBean(SimpleConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(SimpleMeterRegistry.class) + .hasSingleBean(Clock.class) + .hasSingleBean(SimpleConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(SimpleMeterRegistry.class) - .doesNotHaveBean(SimpleConfig.class)); + .withPropertyValues("management.metrics.export.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(SimpleMeterRegistry.class) + .doesNotHaveBean(SimpleConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.simple.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(SimpleMeterRegistry.class) - .doesNotHaveBean(SimpleConfig.class)); + .withPropertyValues("management.metrics.export.simple.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(SimpleMeterRegistry.class) + .doesNotHaveBean(SimpleConfig.class)); } @Test void allowsConfigToBeCustomized() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(SimpleConfig.class).hasBean("customConfig")); + .run((context) -> assertThat(context).hasSingleBean(SimpleConfig.class).hasBean("customConfig")); } @Test void backsOffEntirelyWithCustomMeterRegistry() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(MeterRegistry.class).hasBean("customRegistry").doesNotHaveBean(SimpleConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(MeterRegistry.class) + .hasBean("customRegistry") + .doesNotHaveBean(SimpleConfig.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/stackdriver/StackdriverMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/stackdriver/StackdriverMetricsExportAutoConfigurationTests.java index fceeebab81..4c3a6c0334 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/stackdriver/StackdriverMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/stackdriver/StackdriverMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class StackdriverMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(StackdriverMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(StackdriverMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -47,57 +47,60 @@ class StackdriverMetricsExportAutoConfigurationTests { @Test void failsWithoutAProjectId() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context).hasFailed()); + .run((context) -> assertThat(context).hasFailed()); } @Test void autoConfiguresConfigAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.stackdriver.project-id=test-project") - .run((context) -> assertThat(context).hasSingleBean(StackdriverMeterRegistry.class) - .hasSingleBean(StackdriverConfig.class)); + .withPropertyValues("management.metrics.export.stackdriver.project-id=test-project") + .run((context) -> assertThat(context).hasSingleBean(StackdriverMeterRegistry.class) + .hasSingleBean(StackdriverConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(StackdriverMeterRegistry.class) - .doesNotHaveBean(StackdriverConfig.class)); + .withPropertyValues("management.metrics.export.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(StackdriverMeterRegistry.class) + .doesNotHaveBean(StackdriverConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.stackdriver.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(StackdriverMeterRegistry.class) - .doesNotHaveBean(StackdriverConfig.class)); + .withPropertyValues("management.metrics.export.stackdriver.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(StackdriverMeterRegistry.class) + .doesNotHaveBean(StackdriverConfig.class)); } @Test void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(StackdriverMeterRegistry.class) - .hasSingleBean(StackdriverConfig.class).hasBean("customConfig")); + .run((context) -> assertThat(context).hasSingleBean(StackdriverMeterRegistry.class) + .hasSingleBean(StackdriverConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .withPropertyValues("management.metrics.export.stackdriver.project-id=test-project") - .run((context) -> assertThat(context).hasSingleBean(StackdriverMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(StackdriverConfig.class)); + .withPropertyValues("management.metrics.export.stackdriver.project-id=test-project") + .run((context) -> assertThat(context).hasSingleBean(StackdriverMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(StackdriverConfig.class)); } @Test void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.stackdriver.project-id=test-project").run((context) -> { - StackdriverMeterRegistry registry = context.getBean(StackdriverMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + .withPropertyValues("management.metrics.export.stackdriver.project-id=test-project") + .run((context) -> { + StackdriverMeterRegistry registry = context.getBean(StackdriverMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/stackdriver/StackdriverPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/stackdriver/StackdriverPropertiesConfigAdapterTests.java index 6018cbc91f..9b2f2fe964 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/stackdriver/StackdriverPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/stackdriver/StackdriverPropertiesConfigAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ class StackdriverPropertiesConfigAdapterTests { StackdriverProperties properties = new StackdriverProperties(); properties.setResourceLabels(labels); assertThat(new StackdriverPropertiesConfigAdapter(properties).resourceLabels()) - .containsExactlyInAnyOrderEntriesOf(labels); + .containsExactlyInAnyOrderEntriesOf(labels); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfigurationTests.java index 59d2495491..2b2ea25d93 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class StatsdMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(StatsdMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(StatsdMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -46,34 +46,39 @@ class StatsdMetricsExportAutoConfigurationTests { @Test void autoConfiguresItsConfigMeterRegistryAndMetrics() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(StatsdMeterRegistry.class).hasSingleBean(StatsdConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(StatsdMeterRegistry.class) + .hasSingleBean(StatsdConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withPropertyValues("management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(StatsdMeterRegistry.class) - .doesNotHaveBean(StatsdConfig.class)); + .run((context) -> assertThat(context).doesNotHaveBean(StatsdMeterRegistry.class) + .doesNotHaveBean(StatsdConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withPropertyValues("management.metrics.export.statsd.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(StatsdMeterRegistry.class) - .doesNotHaveBean(StatsdConfig.class)); + .run((context) -> assertThat(context).doesNotHaveBean(StatsdMeterRegistry.class) + .doesNotHaveBean(StatsdConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(StatsdMeterRegistry.class).hasSingleBean(StatsdConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(StatsdMeterRegistry.class) + .hasSingleBean(StatsdConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(StatsdMeterRegistry.class).hasBean("customRegistry").hasSingleBean(StatsdConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(StatsdMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(StatsdConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesConfigAdapterTests.java index e6bce8be43..9eae3d00dc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesConfigAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,7 +71,7 @@ class StatsdPropertiesConfigAdapterTests { StatsdProperties properties = new StatsdProperties(); properties.setMaxPacketLength(1234); assertThat(new StatsdPropertiesConfigAdapter(properties).maxPacketLength()) - .isEqualTo(properties.getMaxPacketLength()); + .isEqualTo(properties.getMaxPacketLength()); } @Test @@ -79,7 +79,7 @@ class StatsdPropertiesConfigAdapterTests { StatsdProperties properties = new StatsdProperties(); properties.setPollingFrequency(Duration.ofSeconds(1)); assertThat(new StatsdPropertiesConfigAdapter(properties).pollingFrequency()) - .isEqualTo(properties.getPollingFrequency()); + .isEqualTo(properties.getPollingFrequency()); } @Test @@ -94,7 +94,7 @@ class StatsdPropertiesConfigAdapterTests { StatsdProperties properties = new StatsdProperties(); properties.setPublishUnchangedMeters(false); assertThat(new StatsdPropertiesConfigAdapter(properties).publishUnchangedMeters()) - .isEqualTo(properties.isPublishUnchangedMeters()); + .isEqualTo(properties.isPublishUnchangedMeters()); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfigurationTests.java index da870c8446..4d464e8300 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ import static org.mockito.Mockito.mock; class WavefrontMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(WavefrontMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(WavefrontMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -54,93 +54,103 @@ class WavefrontMetricsExportAutoConfigurationTests { @Test void failsWithoutAnApiTokenWhenPublishingDirectly() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context).hasFailed()); + .run((context) -> assertThat(context).hasFailed()); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.wavefront.api-token=abcde", - "management.metrics.export.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(WavefrontMeterRegistry.class) - .doesNotHaveBean(WavefrontConfig.class).doesNotHaveBean(WavefrontSender.class)); + .withPropertyValues("management.metrics.export.wavefront.api-token=abcde", + "management.metrics.export.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(WavefrontMeterRegistry.class) + .doesNotHaveBean(WavefrontConfig.class) + .doesNotHaveBean(WavefrontSender.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.wavefront.api-token=abcde", - "management.metrics.export.wavefront.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(WavefrontMeterRegistry.class) - .doesNotHaveBean(WavefrontConfig.class).doesNotHaveBean(WavefrontSender.class)); + .withPropertyValues("management.metrics.export.wavefront.api-token=abcde", + "management.metrics.export.wavefront.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(WavefrontMeterRegistry.class) + .doesNotHaveBean(WavefrontConfig.class) + .doesNotHaveBean(WavefrontSender.class)); } @Test void allowsConfigToBeCustomized() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(Clock.class) - .hasSingleBean(WavefrontMeterRegistry.class).hasSingleBean(WavefrontConfig.class) - .hasSingleBean(WavefrontSender.class).hasBean("customConfig")); + .run((context) -> assertThat(context).hasSingleBean(Clock.class) + .hasSingleBean(WavefrontMeterRegistry.class) + .hasSingleBean(WavefrontConfig.class) + .hasSingleBean(WavefrontSender.class) + .hasBean("customConfig")); } @Test void defaultWavefrontSenderSettingsAreConsistent() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.wavefront.api-token=abcde").run((context) -> { - WavefrontProperties properties = new WavefrontProperties(); - WavefrontSender sender = context.getBean(WavefrontSender.class); - assertThat(sender) - .extracting("metricsBuffer", as(InstanceOfAssertFactories.type(LinkedBlockingQueue.class))) - .satisfies((queue) -> assertThat(queue.remainingCapacity() + queue.size()) - .isEqualTo(properties.getSender().getMaxQueueSize())); - assertThat(sender).hasFieldOrPropertyWithValue("batchSize", properties.getBatchSize()); - assertThat(sender).hasFieldOrPropertyWithValue("messageSizeBytes", - (int) properties.getSender().getMessageSize().toBytes()); - }); + .withPropertyValues("management.metrics.export.wavefront.api-token=abcde") + .run((context) -> { + WavefrontProperties properties = new WavefrontProperties(); + WavefrontSender sender = context.getBean(WavefrontSender.class); + assertThat(sender) + .extracting("metricsBuffer", as(InstanceOfAssertFactories.type(LinkedBlockingQueue.class))) + .satisfies((queue) -> assertThat(queue.remainingCapacity() + queue.size()) + .isEqualTo(properties.getSender().getMaxQueueSize())); + assertThat(sender).hasFieldOrPropertyWithValue("batchSize", properties.getBatchSize()); + assertThat(sender).hasFieldOrPropertyWithValue("messageSizeBytes", + (int) properties.getSender().getMessageSize().toBytes()); + }); } @Test void configureWavefrontSender() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.wavefront.api-token=abcde", - "management.metrics.export.wavefront.batch-size=50", - "management.metrics.export.wavefront.sender.max-queue-size=100", - "management.metrics.export.wavefront.sender.message-size=1KB") - .run((context) -> { - WavefrontSender sender = context.getBean(WavefrontSender.class); - assertThat(sender).hasFieldOrPropertyWithValue("batchSize", 50); - assertThat(sender) - .extracting("metricsBuffer", as(InstanceOfAssertFactories.type(LinkedBlockingQueue.class))) - .satisfies((queue) -> assertThat(queue.remainingCapacity() + queue.size()).isEqualTo(100)); - assertThat(sender).hasFieldOrPropertyWithValue("messageSizeBytes", 1024); - }); + .withPropertyValues("management.metrics.export.wavefront.api-token=abcde", + "management.metrics.export.wavefront.batch-size=50", + "management.metrics.export.wavefront.sender.max-queue-size=100", + "management.metrics.export.wavefront.sender.message-size=1KB") + .run((context) -> { + WavefrontSender sender = context.getBean(WavefrontSender.class); + assertThat(sender).hasFieldOrPropertyWithValue("batchSize", 50); + assertThat(sender) + .extracting("metricsBuffer", as(InstanceOfAssertFactories.type(LinkedBlockingQueue.class))) + .satisfies((queue) -> assertThat(queue.remainingCapacity() + queue.size()).isEqualTo(100)); + assertThat(sender).hasFieldOrPropertyWithValue("messageSizeBytes", 1024); + }); } @Test void allowsWavefrontSenderToBeCustomized() { this.contextRunner.withUserConfiguration(CustomSenderConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(Clock.class) - .hasSingleBean(WavefrontMeterRegistry.class).hasSingleBean(WavefrontConfig.class) - .hasSingleBean(WavefrontSender.class).hasBean("customSender")); + .run((context) -> assertThat(context).hasSingleBean(Clock.class) + .hasSingleBean(WavefrontMeterRegistry.class) + .hasSingleBean(WavefrontConfig.class) + .hasSingleBean(WavefrontSender.class) + .hasBean("customSender")); } @Test void allowsRegistryToBeCustomized() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .withPropertyValues("management.metrics.export.wavefront.api-token=abcde") - .run((context) -> assertThat(context).hasSingleBean(Clock.class).hasSingleBean(WavefrontConfig.class) - .hasSingleBean(WavefrontMeterRegistry.class).hasBean("customRegistry")); + .withPropertyValues("management.metrics.export.wavefront.api-token=abcde") + .run((context) -> assertThat(context).hasSingleBean(Clock.class) + .hasSingleBean(WavefrontConfig.class) + .hasSingleBean(WavefrontMeterRegistry.class) + .hasBean("customRegistry")); } @Test void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.metrics.export.wavefront.api-token=abcde").run((context) -> { - WavefrontMeterRegistry registry = context.getBean(WavefrontMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + .withPropertyValues("management.metrics.export.wavefront.api-token=abcde") + .run((context) -> { + WavefrontMeterRegistry registry = context.getBean(WavefrontMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/graphql/GraphQlMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/graphql/GraphQlMetricsAutoConfigurationTests.java index 5c7c502dbd..5fb553711f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/graphql/GraphQlMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/graphql/GraphQlMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,25 +43,26 @@ import static org.assertj.core.api.Assertions.assertThat; class GraphQlMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(GraphQlMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(GraphQlMetricsAutoConfiguration.class)); @Test void backsOffWhenMeterRegistryIsMissing() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(GraphQlMetricsAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(DefaultGraphQlTagsProvider.class) - .doesNotHaveBean(GraphQlMetricsInstrumentation.class)); + .run((context) -> assertThat(context).doesNotHaveBean(DefaultGraphQlTagsProvider.class) + .doesNotHaveBean(GraphQlMetricsInstrumentation.class)); } @Test void definesTagsProviderAndInstrumentationWhenMeterRegistryIsPresent() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(DefaultGraphQlTagsProvider.class) - .hasSingleBean(GraphQlMetricsInstrumentation.class)); + .hasSingleBean(GraphQlMetricsInstrumentation.class)); } @Test void tagsProviderBacksOffIfAlreadyPresent() { - this.contextRunner.withUserConfiguration(TagsProviderConfiguration.class).run((context) -> assertThat(context) - .doesNotHaveBean(DefaultGraphQlTagsProvider.class).hasSingleBean(TestGraphQlTagsProvider.class)); + this.contextRunner.withUserConfiguration(TagsProviderConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(DefaultGraphQlTagsProvider.class) + .hasSingleBean(TestGraphQlTagsProvider.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/integration/IntegrationMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/integration/IntegrationMetricsAutoConfigurationTests.java index 8d44c8f133..ff258d7366 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/integration/IntegrationMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/integration/IntegrationMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,9 +36,10 @@ import static org.assertj.core.api.Assertions.assertThat; class IntegrationMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(IntegrationAutoConfiguration.class, - IntegrationGraphEndpointAutoConfiguration.class, IntegrationMetricsAutoConfiguration.class)) - .with(MetricsRun.simple()).withPropertyValues("management.metrics.tags.someTag=someValue"); + .withConfiguration(AutoConfigurations.of(IntegrationAutoConfiguration.class, + IntegrationGraphEndpointAutoConfiguration.class, IntegrationMetricsAutoConfiguration.class)) + .with(MetricsRun.simple()) + .withPropertyValues("management.metrics.tags.someTag=someValue"); @Test void integrationMetersAreInstrumented() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfigurationTests.java index 460232c3bb..0b10930ce3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,157 +55,169 @@ import static org.assertj.core.api.Assertions.assertThat; class DataSourcePoolMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withPropertyValues("spring.datasource.generate-unique-name=true").with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(DataSourcePoolMetricsAutoConfiguration.class)) - .withUserConfiguration(BaseConfiguration.class); + .withPropertyValues("spring.datasource.generate-unique-name=true") + .with(MetricsRun.simple()) + .withConfiguration(AutoConfigurations.of(DataSourcePoolMetricsAutoConfiguration.class)) + .withUserConfiguration(BaseConfiguration.class); @Test void autoConfiguredDataSourceIsInstrumented() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .run((context) -> { - context.getBean(DataSource.class).getConnection().getMetaData(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("jdbc.connections.max").tags("name", "dataSource").meter(); - }); + .run((context) -> { + context.getBean(DataSource.class).getConnection().getMetaData(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("jdbc.connections.max").tags("name", "dataSource").meter(); + }); } @Test void dataSourceInstrumentationCanBeDisabled() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("management.metrics.enable.jdbc=false").run((context) -> { - context.getBean(DataSource.class).getConnection().getMetaData(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("jdbc.connections.max").tags("name", "dataSource").meter()).isNull(); - }); + .withPropertyValues("management.metrics.enable.jdbc=false") + .run((context) -> { + context.getBean(DataSource.class).getConnection().getMetaData(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("jdbc.connections.max").tags("name", "dataSource").meter()).isNull(); + }); } @Test void allDataSourcesCanBeInstrumented() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withUserConfiguration(TwoDataSourcesConfiguration.class).run((context) -> { - context.getBean("firstDataSource", DataSource.class).getConnection().getMetaData(); - context.getBean("secondOne", DataSource.class).getConnection().getMetaData(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("jdbc.connections.max").tags("name", "first").meter(); - registry.get("jdbc.connections.max").tags("name", "secondOne").meter(); - }); + .withUserConfiguration(TwoDataSourcesConfiguration.class) + .run((context) -> { + context.getBean("firstDataSource", DataSource.class).getConnection().getMetaData(); + context.getBean("secondOne", DataSource.class).getConnection().getMetaData(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("jdbc.connections.max").tags("name", "first").meter(); + registry.get("jdbc.connections.max").tags("name", "secondOne").meter(); + }); } @Test void allDataSourcesCanBeInstrumentedWithLazyInitialization() { - this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).withInitializer( - (context) -> context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor())) - .withUserConfiguration(TwoDataSourcesConfiguration.class).run((context) -> { - context.getBean("firstDataSource", DataSource.class).getConnection().getMetaData(); - context.getBean("secondOne", DataSource.class).getConnection().getMetaData(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("jdbc.connections.max").tags("name", "first").meter(); - registry.get("jdbc.connections.max").tags("name", "secondOne").meter(); - }); + this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withInitializer( + (context) -> context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor())) + .withUserConfiguration(TwoDataSourcesConfiguration.class) + .run((context) -> { + context.getBean("firstDataSource", DataSource.class).getConnection().getMetaData(); + context.getBean("secondOne", DataSource.class).getConnection().getMetaData(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("jdbc.connections.max").tags("name", "first").meter(); + registry.get("jdbc.connections.max").tags("name", "secondOne").meter(); + }); } @Test void autoConfiguredHikariDataSourceIsInstrumented() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .run((context) -> { - context.getBean(DataSource.class).getConnection(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hikaricp.connections").meter(); - }); + .run((context) -> { + context.getBean(DataSource.class).getConnection(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("hikaricp.connections").meter(); + }); } @Test @Deprecated void autoConfiguredHikariDataSourceIsInstrumentedWhenUsingDeprecatedDataSourceInitialization() { this.contextRunner.withPropertyValues("spring.datasource.schema:db/create-custom-schema.sql") - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { - context.getBean(DataSource.class).getConnection(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hikaricp.connections").meter(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .run((context) -> { + context.getBean(DataSource.class).getConnection(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("hikaricp.connections").meter(); + }); } @Test void autoConfiguredHikariDataSourceIsInstrumentedWhenUsingDataSourceInitialization() { - this.contextRunner.withPropertyValues("spring.sql.init.schema:db/create-custom-schema.sql").withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class, SqlInitializationAutoConfiguration.class)) - .run((context) -> { - context.getBean(DataSource.class).getConnection(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hikaricp.connections").meter(); - }); + this.contextRunner.withPropertyValues("spring.sql.init.schema:db/create-custom-schema.sql") + .withConfiguration( + AutoConfigurations.of(DataSourceAutoConfiguration.class, SqlInitializationAutoConfiguration.class)) + .run((context) -> { + context.getBean(DataSource.class).getConnection(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("hikaricp.connections").meter(); + }); } @Test void hikariCanBeInstrumentedAfterThePoolHasBeenSealed() { this.contextRunner.withUserConfiguration(HikariSealingConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { - assertThat(context).hasNotFailed(); - context.getBean(DataSource.class).getConnection(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("hikaricp.connections").meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasNotFailed(); + context.getBean(DataSource.class).getConnection(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("hikaricp.connections").meter()).isNotNull(); + }); } @Test void hikariDataSourceInstrumentationCanBeDisabled() { this.contextRunner.withPropertyValues("management.metrics.enable.hikaricp=false") - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { - context.getBean(DataSource.class).getConnection(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("hikaricp.connections").meter()).isNull(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .run((context) -> { + context.getBean(DataSource.class).getConnection(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("hikaricp.connections").meter()).isNull(); + }); } @Test void allHikariDataSourcesCanBeInstrumented() { this.contextRunner.withUserConfiguration(TwoHikariDataSourcesConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { - context.getBean("firstDataSource", DataSource.class).getConnection(); - context.getBean("secondOne", DataSource.class).getConnection(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hikaricp.connections").tags("pool", "firstDataSource").meter(); - registry.get("hikaricp.connections").tags("pool", "secondOne").meter(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .run((context) -> { + context.getBean("firstDataSource", DataSource.class).getConnection(); + context.getBean("secondOne", DataSource.class).getConnection(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("hikaricp.connections").tags("pool", "firstDataSource").meter(); + registry.get("hikaricp.connections").tags("pool", "secondOne").meter(); + }); } @Test void someHikariDataSourcesCanBeInstrumented() { this.contextRunner.withUserConfiguration(MixedDataSourcesConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { - context.getBean("firstDataSource", DataSource.class).getConnection(); - context.getBean("secondOne", DataSource.class).getConnection(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.get("hikaricp.connections").meter().getId().getTags()) - .containsExactly(Tag.of("pool", "firstDataSource")); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .run((context) -> { + context.getBean("firstDataSource", DataSource.class).getConnection(); + context.getBean("secondOne", DataSource.class).getConnection(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.get("hikaricp.connections").meter().getId().getTags()) + .containsExactly(Tag.of("pool", "firstDataSource")); + }); } @Test void allHikariDataSourcesCanBeInstrumentedWhenUsingLazyInitialization() { this.contextRunner.withUserConfiguration(TwoHikariDataSourcesConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withInitializer((context) -> context - .addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor())) - .run((context) -> { - context.getBean("firstDataSource", DataSource.class).getConnection(); - context.getBean("secondOne", DataSource.class).getConnection(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hikaricp.connections").tags("pool", "firstDataSource").meter(); - registry.get("hikaricp.connections").tags("pool", "secondOne").meter(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withInitializer( + (context) -> context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor())) + .run((context) -> { + context.getBean("firstDataSource", DataSource.class).getConnection(); + context.getBean("secondOne", DataSource.class).getConnection(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("hikaricp.connections").tags("pool", "firstDataSource").meter(); + registry.get("hikaricp.connections").tags("pool", "secondOne").meter(); + }); } @Test void hikariProxiedDataSourceCanBeInstrumented() { this.contextRunner.withUserConfiguration(ProxiedHikariDataSourcesConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { - context.getBean("proxiedDataSource", DataSource.class).getConnection(); - context.getBean("delegateDataSource", DataSource.class).getConnection(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hikaricp.connections").tags("pool", "firstDataSource").meter(); - registry.get("hikaricp.connections").tags("pool", "secondOne").meter(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .run((context) -> { + context.getBean("proxiedDataSource", DataSource.class).getConnection(); + context.getBean("delegateDataSource", DataSource.class).getConnection(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("hikaricp.connections").tags("pool", "firstDataSource").meter(); + registry.get("hikaricp.connections").tags("pool", "secondOne").meter(); + }); } @Test @@ -215,7 +227,7 @@ class DataSourcePoolMetricsAutoConfigurationTests { context.getBean("hikariDataSource", DataSource.class).getConnection(); MeterRegistry registry = context.getBean(MeterRegistry.class); assertThat(registry.get("hikaricp.connections").meter().getId().getTags()) - .containsExactly(Tag.of("pool", "hikariDataSource")); + .containsExactly(Tag.of("pool", "hikariDataSource")); }); } @@ -311,8 +323,10 @@ class DataSourcePoolMetricsAutoConfigurationTests { private HikariDataSource createHikariDataSource(String poolName) { String url = "jdbc:hsqldb:mem:test-" + UUID.randomUUID(); - HikariDataSource hikariDataSource = DataSourceBuilder.create().url(url).type(HikariDataSource.class) - .build(); + HikariDataSource hikariDataSource = DataSourceBuilder.create() + .url(url) + .type(HikariDataSource.class) + .build(); hikariDataSource.setPoolName(poolName); return hikariDataSource; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfigurationTests.java index 243076f6a7..0ac4b8f76a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,14 +59,15 @@ import static org.assertj.core.api.Assertions.assertThat; class JerseyServerMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(JerseyServerMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JerseyServerMetricsAutoConfiguration.class)); private final WebApplicationContextRunner webContextRunner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JerseyAutoConfiguration.class, - JerseyServerMetricsAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class, MetricsAutoConfiguration.class)) - .withUserConfiguration(ResourceConfiguration.class).withPropertyValues("server.port:0"); + .withConfiguration(AutoConfigurations.of(JerseyAutoConfiguration.class, + JerseyServerMetricsAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, + SimpleMetricsExportAutoConfiguration.class, MetricsAutoConfiguration.class)) + .withUserConfiguration(ResourceConfiguration.class) + .withPropertyValues("server.port:0"); @Test void shouldOnlyBeActiveInWebApplicationContext() { @@ -76,13 +77,13 @@ class JerseyServerMetricsAutoConfigurationTests { @Test void shouldProvideAllNecessaryBeans() { this.webContextRunner.run((context) -> assertThat(context).hasSingleBean(DefaultJerseyTagsProvider.class) - .hasSingleBean(ResourceConfigCustomizer.class)); + .hasSingleBean(ResourceConfigCustomizer.class)); } @Test void shouldHonorExistingTagProvider() { this.webContextRunner.withUserConfiguration(CustomJerseyTagsProviderConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(CustomJerseyTagsProvider.class)); + .run((context) -> assertThat(context).hasSingleBean(CustomJerseyTagsProvider.class)); } @Test @@ -98,17 +99,18 @@ class JerseyServerMetricsAutoConfigurationTests { @Test void noHttpRequestsTimedWhenJerseyInstrumentationMissingFromClasspath() { this.webContextRunner.withClassLoader(new FilteredClassLoader(MetricsApplicationEventListener.class)) - .run((context) -> { - doRequest(context); + .run((context) -> { + doRequest(context); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("http.server.requests").timer()).isNull(); - }); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("http.server.requests").timer()).isNull(); + }); } private static void doRequest(AssertableWebApplicationContext context) { int port = context.getSourceApplicationContext(AnnotationConfigServletWebServerApplicationContext.class) - .getWebServer().getPort(); + .getWebServer() + .getPort(); RestTemplate restTemplate = new RestTemplate(); restTemplate.getForEntity(URI.create("http://localhost:" + port + "/users/3"), String.class); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/mongo/MongoMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/mongo/MongoMetricsAutoConfigurationTests.java index 43d96561b7..c70353aa7f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/mongo/MongoMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/mongo/MongoMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,119 +52,124 @@ import static org.mockito.Mockito.mock; class MongoMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoMetricsAutoConfiguration.class)); @Test void whenThereIsAMeterRegistryThenMetricsCommandListenerIsAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)).run((context) -> { - assertThat(context).hasSingleBean(MongoMetricsCommandListener.class); - assertThat(getActualMongoClientSettingsUsedToConstructClient(context)).isNotNull() - .extracting(MongoClientSettings::getCommandListeners).asList() - .containsExactly(context.getBean(MongoMetricsCommandListener.class)); - assertThat(getMongoCommandTagsProviderUsedToConstructListener(context)) - .isInstanceOf(DefaultMongoCommandTagsProvider.class); - }); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasSingleBean(MongoMetricsCommandListener.class); + assertThat(getActualMongoClientSettingsUsedToConstructClient(context)).isNotNull() + .extracting(MongoClientSettings::getCommandListeners) + .asList() + .containsExactly(context.getBean(MongoMetricsCommandListener.class)); + assertThat(getMongoCommandTagsProviderUsedToConstructListener(context)) + .isInstanceOf(DefaultMongoCommandTagsProvider.class); + }); } @Test void whenThereIsAMeterRegistryThenMetricsConnectionPoolListenerIsAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)).run((context) -> { - assertThat(context).hasSingleBean(MongoMetricsConnectionPoolListener.class); - assertThat(getConnectionPoolListenersFromClient(context)) - .containsExactly(context.getBean(MongoMetricsConnectionPoolListener.class)); - assertThat(getMongoConnectionPoolTagsProviderUsedToConstructListener(context)) - .isInstanceOf(DefaultMongoConnectionPoolTagsProvider.class); - }); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasSingleBean(MongoMetricsConnectionPoolListener.class); + assertThat(getConnectionPoolListenersFromClient(context)) + .containsExactly(context.getBean(MongoMetricsConnectionPoolListener.class)); + assertThat(getMongoConnectionPoolTagsProviderUsedToConstructListener(context)) + .isInstanceOf(DefaultMongoConnectionPoolTagsProvider.class); + }); } @Test void whenThereIsNoMeterRegistryThenNoMetricsCommandListenerIsAdded() { this.contextRunner.withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .run(assertThatMetricsCommandListenerNotAdded()); + .run(assertThatMetricsCommandListenerNotAdded()); } @Test void whenThereIsNoMeterRegistryThenNoMetricsConnectionPoolListenerIsAdded() { this.contextRunner.withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .run(assertThatMetricsConnectionPoolListenerNotAdded()); + .run(assertThatMetricsConnectionPoolListenerNotAdded()); } @Test void whenThereIsACustomMetricsCommandTagsProviderItIsUsed() { final MongoCommandTagsProvider customTagsProvider = mock(MongoCommandTagsProvider.class); this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .withBean("customMongoCommandTagsProvider", MongoCommandTagsProvider.class, () -> customTagsProvider) - .run((context) -> assertThat(getMongoCommandTagsProviderUsedToConstructListener(context)) - .isSameAs(customTagsProvider)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .withBean("customMongoCommandTagsProvider", MongoCommandTagsProvider.class, () -> customTagsProvider) + .run((context) -> assertThat(getMongoCommandTagsProviderUsedToConstructListener(context)) + .isSameAs(customTagsProvider)); } @Test void whenThereIsACustomMetricsConnectionPoolTagsProviderItIsUsed() { final MongoConnectionPoolTagsProvider customTagsProvider = mock(MongoConnectionPoolTagsProvider.class); this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .withBean("customMongoConnectionPoolTagsProvider", MongoConnectionPoolTagsProvider.class, - () -> customTagsProvider) - .run((context) -> assertThat(getMongoConnectionPoolTagsProviderUsedToConstructListener(context)) - .isSameAs(customTagsProvider)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .withBean("customMongoConnectionPoolTagsProvider", MongoConnectionPoolTagsProvider.class, + () -> customTagsProvider) + .run((context) -> assertThat(getMongoConnectionPoolTagsProviderUsedToConstructListener(context)) + .isSameAs(customTagsProvider)); } @Test void whenThereIsNoMongoClientSettingsOnClasspathThenNoMetricsCommandListenerIsAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(MongoClientSettings.class)) - .run(assertThatMetricsCommandListenerNotAdded()); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(MongoClientSettings.class)) + .run(assertThatMetricsCommandListenerNotAdded()); } @Test void whenThereIsNoMongoClientSettingsOnClasspathThenNoMetricsConnectionPoolListenerIsAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(MongoClientSettings.class)) - .run(assertThatMetricsConnectionPoolListenerNotAdded()); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(MongoClientSettings.class)) + .run(assertThatMetricsConnectionPoolListenerNotAdded()); } @Test void whenThereIsNoMongoMetricsCommandListenerOnClasspathThenNoMetricsCommandListenerIsAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(MongoMetricsCommandListener.class)) - .run(assertThatMetricsCommandListenerNotAdded()); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(MongoMetricsCommandListener.class)) + .run(assertThatMetricsCommandListenerNotAdded()); } @Test void whenThereIsNoMongoMetricsConnectionPoolListenerOnClasspathThenNoMetricsConnectionPoolListenerIsAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(MongoMetricsConnectionPoolListener.class)) - .run(assertThatMetricsConnectionPoolListenerNotAdded()); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(MongoMetricsConnectionPoolListener.class)) + .run(assertThatMetricsConnectionPoolListenerNotAdded()); } @Test void whenMetricsCommandListenerEnabledPropertyFalseThenNoMetricsCommandListenerIsAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .withPropertyValues("management.metrics.mongo.command.enabled:false") - .run(assertThatMetricsCommandListenerNotAdded()); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .withPropertyValues("management.metrics.mongo.command.enabled:false") + .run(assertThatMetricsCommandListenerNotAdded()); } @Test void whenMetricsConnectionPoolListenerEnabledPropertyFalseThenNoMetricsConnectionPoolListenerIsAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .withPropertyValues("management.metrics.mongo.connectionpool.enabled:false") - .run(assertThatMetricsConnectionPoolListenerNotAdded()); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .withPropertyValues("management.metrics.mongo.connectionpool.enabled:false") + .run(assertThatMetricsConnectionPoolListenerNotAdded()); } private ContextConsumer assertThatMetricsCommandListenerNotAdded() { return (context) -> { assertThat(context).doesNotHaveBean(MongoMetricsCommandListener.class); assertThat(getActualMongoClientSettingsUsedToConstructClient(context)).isNotNull() - .extracting(MongoClientSettings::getCommandListeners).asList().isEmpty(); + .extracting(MongoClientSettings::getCommandListeners) + .asList() + .isEmpty(); }; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfigurationTests.java index 2f372877b9..40ba974dc9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,87 +63,92 @@ import static org.mockito.Mockito.mock; class HibernateMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class, HibernateMetricsAutoConfiguration.class)) - .withUserConfiguration(BaseConfiguration.class); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, + HibernateMetricsAutoConfiguration.class)) + .withUserConfiguration(BaseConfiguration.class); @Test void autoConfiguredEntityManagerFactoryWithStatsIsInstrumented() { this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:true") - .run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hibernate.statements").tags("entityManagerFactory", "entityManagerFactory").meter(); - }); + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("hibernate.statements").tags("entityManagerFactory", "entityManagerFactory").meter(); + }); } @Test void autoConfiguredEntityManagerFactoryWithoutStatsIsNotInstrumented() { this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:false") - .run((context) -> { - context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("hibernate.statements").meter()).isNull(); - }); + .run((context) -> { + context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("hibernate.statements").meter()).isNull(); + }); } @Test void entityManagerFactoryInstrumentationCanBeDisabled() { - this.contextRunner.withPropertyValues("management.metrics.enable.hibernate=false", - "spring.jpa.properties.hibernate.generate_statistics:true").run((context) -> { - context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("hibernate.statements").meter()).isNull(); - }); + this.contextRunner + .withPropertyValues("management.metrics.enable.hibernate=false", + "spring.jpa.properties.hibernate.generate_statistics:true") + .run((context) -> { + context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("hibernate.statements").meter()).isNull(); + }); } @Test void allEntityManagerFactoriesCanBeInstrumented() { this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:true") - .withUserConfiguration(TwoEntityManagerFactoriesConfiguration.class).run((context) -> { - context.getBean("firstEntityManagerFactory", EntityManagerFactory.class) - .unwrap(SessionFactory.class); - context.getBean("secondOne", EntityManagerFactory.class).unwrap(SessionFactory.class); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hibernate.statements").tags("entityManagerFactory", "first").meter(); - registry.get("hibernate.statements").tags("entityManagerFactory", "secondOne").meter(); - }); + .withUserConfiguration(TwoEntityManagerFactoriesConfiguration.class) + .run((context) -> { + context.getBean("firstEntityManagerFactory", EntityManagerFactory.class).unwrap(SessionFactory.class); + context.getBean("secondOne", EntityManagerFactory.class).unwrap(SessionFactory.class); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("hibernate.statements").tags("entityManagerFactory", "first").meter(); + registry.get("hibernate.statements").tags("entityManagerFactory", "secondOne").meter(); + }); } @Test void entityManagerFactoryInstrumentationIsDisabledIfNotHibernateSessionFactory() { this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:true") - .withUserConfiguration(NonHibernateEntityManagerFactoryConfiguration.class).run((context) -> { - // ensure EntityManagerFactory is not a Hibernate SessionFactory - assertThatThrownBy(() -> context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class)) - .isInstanceOf(PersistenceException.class); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("hibernate.statements").meter()).isNull(); - }); + .withUserConfiguration(NonHibernateEntityManagerFactoryConfiguration.class) + .run((context) -> { + // ensure EntityManagerFactory is not a Hibernate SessionFactory + assertThatThrownBy(() -> context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class)) + .isInstanceOf(PersistenceException.class); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("hibernate.statements").meter()).isNull(); + }); } @Test void entityManagerFactoryInstrumentationIsDisabledIfHibernateIsNotAvailable() { this.contextRunner.withClassLoader(new FilteredClassLoader(SessionFactory.class)) - .withUserConfiguration(NonHibernateEntityManagerFactoryConfiguration.class).run((context) -> { - assertThat(context).doesNotHaveBean(HibernateMetricsAutoConfiguration.class); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("hibernate.statements").meter()).isNull(); - }); + .withUserConfiguration(NonHibernateEntityManagerFactoryConfiguration.class) + .run((context) -> { + assertThat(context).doesNotHaveBean(HibernateMetricsAutoConfiguration.class); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("hibernate.statements").meter()).isNull(); + }); } @Test void entityManagerFactoryInstrumentationDoesNotDeadlockWithDeferredInitialization() { - this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:true", - "spring.sql.init.schema-locations:city-schema.sql", "spring.sql.init.data-locations=city-data.sql") - .withConfiguration(AutoConfigurations.of(SqlInitializationAutoConfiguration.class)) - .withBean(EntityManagerFactoryBuilderCustomizer.class, - () -> (builder) -> builder.setBootstrapExecutor(new SimpleAsyncTaskExecutor())) - .run((context) -> { - JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getBean(DataSource.class)); - assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) from CITY", Integer.class)).isEqualTo(1); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hibernate.statements").tags("entityManagerFactory", "entityManagerFactory").meter(); - }); + this.contextRunner + .withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:true", + "spring.sql.init.schema-locations:city-schema.sql", "spring.sql.init.data-locations=city-data.sql") + .withConfiguration(AutoConfigurations.of(SqlInitializationAutoConfiguration.class)) + .withBean(EntityManagerFactoryBuilderCustomizer.class, + () -> (builder) -> builder.setBootstrapExecutor(new SimpleAsyncTaskExecutor())) + .run((context) -> { + JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getBean(DataSource.class)); + assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) from CITY", Integer.class)).isEqualTo(1); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("hibernate.statements").tags("entityManagerFactory", "entityManagerFactory").meter(); + }); } @Configuration(proxyBeanMethods = false) @@ -185,7 +190,8 @@ class HibernateMetricsAutoConfigurationTests { Map jpaProperties = new HashMap<>(); jpaProperties.put("hibernate.generate_statistics", "true"); return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), jpaProperties, null).dataSource(ds) - .packages(PACKAGE_CLASSES).build(); + .packages(PACKAGE_CLASSES) + .build(); } } @@ -198,7 +204,7 @@ class HibernateMetricsAutoConfigurationTests { EntityManagerFactory mockedFactory = mock(EntityManagerFactory.class); // enforces JPA contract given(mockedFactory.unwrap(ArgumentMatchers.>any())) - .willThrow(PersistenceException.class); + .willThrow(PersistenceException.class); return mockedFactory; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/r2dbc/ConnectionPoolMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/r2dbc/ConnectionPoolMetricsAutoConfigurationTests.java index 41137e5b98..de32507ba3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/r2dbc/ConnectionPoolMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/r2dbc/ConnectionPoolMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,9 +52,10 @@ import static org.assertj.core.api.Assertions.assertThat; class ConnectionPoolMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withPropertyValues("spring.r2dbc.generate-unique-name=true").with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(ConnectionPoolMetricsAutoConfiguration.class)) - .withUserConfiguration(BaseConfiguration.class); + .withPropertyValues("spring.r2dbc.generate-unique-name=true") + .with(MetricsRun.simple()) + .withConfiguration(AutoConfigurations.of(ConnectionPoolMetricsAutoConfiguration.class)) + .withUserConfiguration(BaseConfiguration.class); @Test void autoConfiguredDataSourceIsInstrumented() { @@ -67,21 +68,23 @@ class ConnectionPoolMetricsAutoConfigurationTests { @Test void autoConfiguredDataSourceExposedAsConnectionFactoryTypeIsInstrumented() { this.contextRunner - .withPropertyValues( - "spring.r2dbc.url:r2dbc:pool:h2:mem:///name?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") - .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)).run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("r2dbc.pool.acquired").gauges()).hasSize(1); - }); + .withPropertyValues( + "spring.r2dbc.url:r2dbc:pool:h2:mem:///name?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") + .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("r2dbc.pool.acquired").gauges()).hasSize(1); + }); } @Test void connectionPoolInstrumentationCanBeDisabled() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .withPropertyValues("management.metrics.enable.r2dbc=false").run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("r2dbc.pool.acquired").gauge()).isNull(); - }); + .withPropertyValues("management.metrics.enable.r2dbc=false") + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("r2dbc.pool.acquired").gauge()).isNull(); + }); } @Test @@ -89,7 +92,8 @@ class ConnectionPoolMetricsAutoConfigurationTests { this.contextRunner.withUserConfiguration(ConnectionFactoryConfiguration.class).run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); assertThat(registry.find("r2dbc.pool.acquired").gauges()).extracting(Meter::getId) - .extracting((id) -> id.getTag("name")).containsExactly("testConnectionPool"); + .extracting((id) -> id.getTag("name")) + .containsExactly("testConnectionPool"); }); } @@ -98,7 +102,8 @@ class ConnectionPoolMetricsAutoConfigurationTests { this.contextRunner.withUserConfiguration(WrappedConnectionPoolConfiguration.class).run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); assertThat(registry.find("r2dbc.pool.acquired").gauges()).extracting(Meter::getId) - .extracting((id) -> id.getTag("name")).containsExactly("wrappedConnectionPool"); + .extracting((id) -> id.getTag("name")) + .containsExactly("wrappedConnectionPool"); }); } @@ -107,7 +112,8 @@ class ConnectionPoolMetricsAutoConfigurationTests { this.contextRunner.withUserConfiguration(TwoConnectionPoolsConfiguration.class).run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); assertThat(registry.find("r2dbc.pool.acquired").gauges()).extracting(Meter::getId) - .extracting((id) -> id.getTag("name")).containsExactlyInAnyOrder("firstPool", "secondPool"); + .extracting((id) -> id.getTag("name")) + .containsExactlyInAnyOrder("firstPool", "secondPool"); }); } @@ -128,7 +134,8 @@ class ConnectionPoolMetricsAutoConfigurationTests { ConnectionFactory testConnectionPool() { return new ConnectionPool( ConnectionPoolConfiguration.builder(H2ConnectionFactory.inMemory("db-" + UUID.randomUUID(), "sa", - "", Collections.singletonMap(H2ConnectionOption.DB_CLOSE_DELAY, "-1"))).build()); + "", Collections.singletonMap(H2ConnectionOption.DB_CLOSE_DELAY, "-1"))) + .build()); } } @@ -138,12 +145,10 @@ class ConnectionPoolMetricsAutoConfigurationTests { @Bean ConnectionFactory wrappedConnectionPool() { - return new Wrapper( - new ConnectionPool( - ConnectionPoolConfiguration - .builder(H2ConnectionFactory.inMemory("db-" + UUID.randomUUID(), "sa", "", - Collections.singletonMap(H2ConnectionOption.DB_CLOSE_DELAY, "-1"))) - .build())); + return new Wrapper(new ConnectionPool( + ConnectionPoolConfiguration.builder(H2ConnectionFactory.inMemory("db-" + UUID.randomUUID(), "sa", + "", Collections.singletonMap(H2ConnectionOption.DB_CLOSE_DELAY, "-1"))) + .build())); } static class Wrapper implements ConnectionFactory, Wrapped { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/redis/LettuceMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/redis/LettuceMetricsAutoConfigurationTests.java index df06304e69..6d16b0fa69 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/redis/LettuceMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/redis/LettuceMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,31 +39,31 @@ import static org.assertj.core.api.Assertions.assertThat; class LettuceMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(LettuceMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(LettuceMetricsAutoConfiguration.class)); @Test void whenThereIsAMeterRegistryThenCommandLatencyRecorderIsAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)).run((context) -> { - ClientResources clientResources = context.getBean(LettuceConnectionFactory.class) - .getClientResources(); - assertThat(clientResources.commandLatencyRecorder()) - .isInstanceOf(MicrometerCommandLatencyRecorder.class); - }); + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) + .run((context) -> { + ClientResources clientResources = context.getBean(LettuceConnectionFactory.class).getClientResources(); + assertThat(clientResources.commandLatencyRecorder()) + .isInstanceOf(MicrometerCommandLatencyRecorder.class); + }); } @Test void whenUserDefinesAMicrometerOptionsBeanThenCommandLatencyRecorderUsesIt() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .withUserConfiguration(CustomMicrometerOptionsConfiguration.class).run((context) -> { - ClientResources clientResources = context.getBean(LettuceConnectionFactory.class) - .getClientResources(); - assertThat(clientResources.commandLatencyRecorder()) - .isInstanceOf(MicrometerCommandLatencyRecorder.class); - assertThat(clientResources.commandLatencyRecorder()).hasFieldOrPropertyWithValue("options", - context.getBean("customMicrometerOptions")); - }); + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) + .withUserConfiguration(CustomMicrometerOptionsConfiguration.class) + .run((context) -> { + ClientResources clientResources = context.getBean(LettuceConnectionFactory.class).getClientResources(); + assertThat(clientResources.commandLatencyRecorder()) + .isInstanceOf(MicrometerCommandLatencyRecorder.class); + assertThat(clientResources.commandLatencyRecorder()).hasFieldOrPropertyWithValue("options", + context.getBean("customMicrometerOptions")); + }); } @Test @@ -71,7 +71,7 @@ class LettuceMetricsAutoConfigurationTests { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)).run((context) -> { ClientResources clientResources = context.getBean(LettuceConnectionFactory.class).getClientResources(); assertThat(clientResources.commandLatencyRecorder()) - .isNotInstanceOf(MicrometerCommandLatencyRecorder.class); + .isNotInstanceOf(MicrometerCommandLatencyRecorder.class); }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/startup/StartupTimeMetricsListenerAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/startup/StartupTimeMetricsListenerAutoConfigurationTests.java index dae7409542..f68265f387 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/startup/StartupTimeMetricsListenerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/startup/StartupTimeMetricsListenerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ import static org.mockito.Mockito.mock; class StartupTimeMetricsListenerAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(StartupTimeMetricsListenerAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(StartupTimeMetricsListenerAutoConfiguration.class)); @Test void startupTimeMetricsAreRecorded() { @@ -65,25 +65,27 @@ class StartupTimeMetricsListenerAutoConfigurationTests { @Test void startupTimeMetricsCanBeDisabled() { - this.contextRunner.withPropertyValues("management.metrics.enable.application.started.time:false", - "management.metrics.enable.application.ready.time:false").run((context) -> { - context.publishEvent(new ApplicationStartedEvent(new SpringApplication(), null, - context.getSourceApplicationContext(), Duration.ofMillis(2500))); - context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), null, - context.getSourceApplicationContext(), Duration.ofMillis(3000))); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("application.started.time").timeGauge()).isNull(); - assertThat(registry.find("application.ready.time").timeGauge()).isNull(); - }); + this.contextRunner + .withPropertyValues("management.metrics.enable.application.started.time:false", + "management.metrics.enable.application.ready.time:false") + .run((context) -> { + context.publishEvent(new ApplicationStartedEvent(new SpringApplication(), null, + context.getSourceApplicationContext(), Duration.ofMillis(2500))); + context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), null, + context.getSourceApplicationContext(), Duration.ofMillis(3000))); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("application.started.time").timeGauge()).isNull(); + assertThat(registry.find("application.ready.time").timeGauge()).isNull(); + }); } @Test void customStartupTimeMetricsAreRespected() { this.contextRunner - .withBean("customStartupTimeMetrics", StartupTimeMetricsListener.class, - () -> mock(StartupTimeMetricsListener.class)) - .run((context) -> assertThat(context).hasSingleBean(StartupTimeMetricsListener.class) - .hasBean("customStartupTimeMetrics")); + .withBean("customStartupTimeMetrics", StartupTimeMetricsListener.class, + () -> mock(StartupTimeMetricsListener.class)) + .run((context) -> assertThat(context).hasSingleBean(StartupTimeMetricsListener.class) + .hasBean("customStartupTimeMetrics")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/task/TaskExecutorMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/task/TaskExecutorMetricsAutoConfigurationTests.java index 53093101b1..35087e1e40 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/task/TaskExecutorMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/task/TaskExecutorMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,30 +48,32 @@ import static org.mockito.Mockito.mock; class TaskExecutorMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(TaskExecutorMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(TaskExecutorMetricsAutoConfiguration.class)); @Test void taskExecutorUsingAutoConfigurationIsInstrumented() { this.contextRunner.withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class)) - .run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - Collection meters = registry.get("executor.completed").functionCounters(); - assertThat(meters).singleElement().satisfies( + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + Collection meters = registry.get("executor.completed").functionCounters(); + assertThat(meters).singleElement() + .satisfies( (meter) -> assertThat(meter.getId().getTag("name")).isEqualTo("applicationTaskExecutor")); - assertThatExceptionOfType(MeterNotFoundException.class) - .isThrownBy(() -> registry.get("executor").timer()); - }); + assertThatExceptionOfType(MeterNotFoundException.class) + .isThrownBy(() -> registry.get("executor").timer()); + }); } @Test void taskExecutorsWithCustomNamesAreInstrumented() { this.contextRunner.withBean("firstTaskExecutor", Executor.class, ThreadPoolTaskExecutor::new) - .withBean("customName", ThreadPoolTaskExecutor.class, ThreadPoolTaskExecutor::new).run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - Collection meters = registry.get("executor.completed").functionCounters(); - assertThat(meters).map((meter) -> meter.getId().getTag("name")) - .containsExactlyInAnyOrder("firstTaskExecutor", "customName"); - }); + .withBean("customName", ThreadPoolTaskExecutor.class, ThreadPoolTaskExecutor::new) + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + Collection meters = registry.get("executor.completed").functionCounters(); + assertThat(meters).map((meter) -> meter.getId().getTag("name")) + .containsExactlyInAnyOrder("firstTaskExecutor", "customName"); + }); } @Test @@ -79,46 +81,51 @@ class TaskExecutorMetricsAutoConfigurationTests { ThreadPoolTaskExecutor unavailableTaskExecutor = mock(ThreadPoolTaskExecutor.class); given(unavailableTaskExecutor.getThreadPoolExecutor()).willThrow(new IllegalStateException("Test")); this.contextRunner.withBean("firstTaskExecutor", ThreadPoolTaskExecutor.class, ThreadPoolTaskExecutor::new) - .withBean("customName", ThreadPoolTaskExecutor.class, () -> unavailableTaskExecutor).run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - Collection meters = registry.get("executor.completed").functionCounters(); - assertThat(meters).singleElement().satisfies( - (meter) -> assertThat(meter.getId().getTag("name")).isEqualTo("firstTaskExecutor")); - }); + .withBean("customName", ThreadPoolTaskExecutor.class, () -> unavailableTaskExecutor) + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + Collection meters = registry.get("executor.completed").functionCounters(); + assertThat(meters).singleElement() + .satisfies((meter) -> assertThat(meter.getId().getTag("name")).isEqualTo("firstTaskExecutor")); + }); } @Test void taskExecutorInstrumentationCanBeDisabled() { this.contextRunner.withPropertyValues("management.metrics.enable.executor=false") - .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class)).run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("executor.completed").tags("name", "applicationTaskExecutor") - .functionCounter()).isNull(); - }); + .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class)) + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat( + registry.find("executor.completed").tags("name", "applicationTaskExecutor").functionCounter()) + .isNull(); + }); } @Test void taskSchedulerUsingAutoConfigurationIsInstrumented() { this.contextRunner.withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) - .withUserConfiguration(SchedulingTestConfiguration.class).run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - Collection meters = registry.get("executor.completed").functionCounters(); - assertThat(meters).singleElement() - .satisfies((meter) -> assertThat(meter.getId().getTag("name")).isEqualTo("taskScheduler")); - assertThatExceptionOfType(MeterNotFoundException.class) - .isThrownBy(() -> registry.get("executor").timer()); - }); + .withUserConfiguration(SchedulingTestConfiguration.class) + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + Collection meters = registry.get("executor.completed").functionCounters(); + assertThat(meters).singleElement() + .satisfies((meter) -> assertThat(meter.getId().getTag("name")).isEqualTo("taskScheduler")); + assertThatExceptionOfType(MeterNotFoundException.class) + .isThrownBy(() -> registry.get("executor").timer()); + }); } @Test void taskSchedulersWithCustomNamesAreInstrumented() { this.contextRunner.withBean("firstTaskScheduler", Executor.class, ThreadPoolTaskScheduler::new) - .withBean("customName", ThreadPoolTaskScheduler.class, ThreadPoolTaskScheduler::new).run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - Collection meters = registry.get("executor.completed").functionCounters(); - assertThat(meters).map((meter) -> meter.getId().getTag("name")) - .containsExactlyInAnyOrder("firstTaskScheduler", "customName"); - }); + .withBean("customName", ThreadPoolTaskScheduler.class, ThreadPoolTaskScheduler::new) + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + Collection meters = registry.get("executor.completed").functionCounters(); + assertThat(meters).map((meter) -> meter.getId().getTag("name")) + .containsExactlyInAnyOrder("firstTaskScheduler", "customName"); + }); } @Test @@ -126,23 +133,25 @@ class TaskExecutorMetricsAutoConfigurationTests { ThreadPoolTaskScheduler unavailableTaskExecutor = mock(ThreadPoolTaskScheduler.class); given(unavailableTaskExecutor.getScheduledThreadPoolExecutor()).willThrow(new IllegalStateException("Test")); this.contextRunner.withBean("firstTaskScheduler", ThreadPoolTaskScheduler.class, ThreadPoolTaskScheduler::new) - .withBean("customName", ThreadPoolTaskScheduler.class, () -> unavailableTaskExecutor).run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - Collection meters = registry.get("executor.completed").functionCounters(); - assertThat(meters).singleElement().satisfies( - (meter) -> assertThat(meter.getId().getTag("name")).isEqualTo("firstTaskScheduler")); - }); + .withBean("customName", ThreadPoolTaskScheduler.class, () -> unavailableTaskExecutor) + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + Collection meters = registry.get("executor.completed").functionCounters(); + assertThat(meters).singleElement() + .satisfies((meter) -> assertThat(meter.getId().getTag("name")).isEqualTo("firstTaskScheduler")); + }); } @Test void taskSchedulerInstrumentationCanBeDisabled() { this.contextRunner.withPropertyValues("management.metrics.enable.executor=false") - .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) - .withUserConfiguration(SchedulingTestConfiguration.class).run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("executor.completed").tags("name", "taskScheduler").functionCounter()) - .isNull(); - }); + .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) + .withUserConfiguration(SchedulingTestConfiguration.class) + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("executor.completed").tags("name", "taskScheduler").functionCounter()) + .isNull(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsIntegrationTests.java index b5837f6495..453097e690 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -103,8 +103,9 @@ class MetricsIntegrationTests { @Test void restTemplateIsInstrumented() { MockRestServiceServer server = MockRestServiceServer.bindTo(this.external).build(); - server.expect(once(), requestTo("/api/external")).andExpect(method(HttpMethod.GET)) - .andRespond(withSuccess("{\"message\": \"hello\"}", MediaType.APPLICATION_JSON)); + server.expect(once(), requestTo("/api/external")) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess("{\"message\": \"hello\"}", MediaType.APPLICATION_JSON)); assertThat(this.external.getForObject("/api/external", Map.class)).containsKey("message"); assertThat(this.registry.get("http.client.requests").timer().count()).isEqualTo(1); } @@ -112,27 +113,28 @@ class MetricsIntegrationTests { @Test void requestMappingIsInstrumented() { this.loopback.getForObject("/api/people", Set.class); - waitAtMost(Duration.ofSeconds(5)).untilAsserted( - () -> assertThat(this.registry.get("http.server.requests").timer().count()).isEqualTo(1)); + waitAtMost(Duration.ofSeconds(5)) + .untilAsserted(() -> assertThat(this.registry.get("http.server.requests").timer().count()).isEqualTo(1)); } @Test void automaticallyRegisteredBinders() { assertThat(this.context.getBeansOfType(MeterBinder.class).values()) - .hasAtLeastOneElementOfType(LogbackMetrics.class).hasAtLeastOneElementOfType(JvmMemoryMetrics.class); + .hasAtLeastOneElementOfType(LogbackMetrics.class) + .hasAtLeastOneElementOfType(JvmMemoryMetrics.class); } @Test @SuppressWarnings({ "rawtypes", "unchecked" }) void metricsFilterRegisteredForAsyncDispatches() { Map filterRegistrations = this.context - .getBeansOfType(FilterRegistrationBean.class); + .getBeansOfType(FilterRegistrationBean.class); assertThat(filterRegistrations).containsKey("webMvcMetricsFilter"); FilterRegistrationBean registration = filterRegistrations.get("webMvcMetricsFilter"); assertThat(registration.getFilter()).isInstanceOf(WebMvcMetricsFilter.class); assertThat((Set) ReflectionTestUtils.getField(registration, "dispatcherTypes")) - .containsExactlyInAnyOrder(DispatcherType.REQUEST, DispatcherType.ASYNC); + .containsExactlyInAnyOrder(DispatcherType.REQUEST, DispatcherType.ASYNC); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsRun.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsRun.java index 8df509ddb3..9aa6a3fc0f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsRun.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsRun.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -100,8 +100,8 @@ public final class MetricsRun { () -> "Unknown export auto-configuration " + configuration.getName()); } return (T) contextRunner.withPropertyValues("management.metrics.use-global-registry=false") - .withConfiguration(AUTO_CONFIGURATIONS) - .withConfiguration(AutoConfigurations.of(exportAutoConfigurations)); + .withConfiguration(AUTO_CONFIGURATIONS) + .withConfiguration(AutoConfigurations.of(exportAutoConfigurations)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsConfigurationTests.java index 69232dafe1..f4e6e7f97d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,8 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat class RestTemplateMetricsConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class, - HttpClientMetricsAutoConfiguration.class)); + .withConfiguration( + AutoConfigurations.of(RestTemplateAutoConfiguration.class, HttpClientMetricsAutoConfiguration.class)); @Test void restTemplateCreatedWithBuilderIsInstrumented() { @@ -78,7 +78,7 @@ class RestTemplateMetricsConfigurationTests { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(MetricsRestTemplateCustomizer.class); RestTemplateBuilder customBuilder = new RestTemplateBuilder() - .customizers(context.getBean(MetricsRestTemplateCustomizer.class)); + .customizers(context.getBean(MetricsRestTemplateCustomizer.class)); MeterRegistry registry = context.getBean(MeterRegistry.class); validateRestTemplate(customBuilder, registry); }); @@ -90,7 +90,7 @@ class RestTemplateMetricsConfigurationTests { MeterRegistry registry = getInitializedMeterRegistry(context); assertThat(registry.get("http.client.requests").meters()).hasSize(2); assertThat(output).contains("Reached the maximum number of URI tags for 'http.client.requests'.") - .contains("Are you using 'uriVariables'?"); + .contains("Are you using 'uriVariables'?"); }); } @@ -100,30 +100,32 @@ class RestTemplateMetricsConfigurationTests { MeterRegistry registry = getInitializedMeterRegistry(context); assertThat(registry.get("http.client.requests").meters()).hasSize(3); assertThat(output).doesNotContain("Reached the maximum number of URI tags for 'http.client.requests'.") - .doesNotContain("Are you using 'uriVariables'?"); + .doesNotContain("Are you using 'uriVariables'?"); }); } @Test void autoTimeRequestsCanBeConfigured() { - this.contextRunner.withPropertyValues("management.metrics.web.client.request.autotime.enabled=true", - "management.metrics.web.client.request.autotime.percentiles=0.5,0.7", - "management.metrics.web.client.request.autotime.percentiles-histogram=true").run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - Timer timer = registry.get("http.client.requests").timer(); - HistogramSnapshot snapshot = timer.takeSnapshot(); - assertThat(snapshot.percentileValues()).hasSize(2); - assertThat(snapshot.percentileValues()[0].percentile()).isEqualTo(0.5); - assertThat(snapshot.percentileValues()[1].percentile()).isEqualTo(0.7); - }); + this.contextRunner + .withPropertyValues("management.metrics.web.client.request.autotime.enabled=true", + "management.metrics.web.client.request.autotime.percentiles=0.5,0.7", + "management.metrics.web.client.request.autotime.percentiles-histogram=true") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + Timer timer = registry.get("http.client.requests").timer(); + HistogramSnapshot snapshot = timer.takeSnapshot(); + assertThat(snapshot.percentileValues()).hasSize(2); + assertThat(snapshot.percentileValues()[0].percentile()).isEqualTo(0.5); + assertThat(snapshot.percentileValues()[1].percentile()).isEqualTo(0.7); + }); } @Test void backsOffWhenRestTemplateBuilderIsMissing() { new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(HttpClientMetricsAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(DefaultRestTemplateExchangeTagsProvider.class) - .doesNotHaveBean(MetricsRestTemplateCustomizer.class)); + .withConfiguration(AutoConfigurations.of(HttpClientMetricsAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(DefaultRestTemplateExchangeTagsProvider.class) + .doesNotHaveBean(MetricsRestTemplateCustomizer.class)); } private MeterRegistry getInitializedMeterRegistry(AssertableApplicationContext context) { @@ -147,9 +149,9 @@ class RestTemplateMetricsConfigurationTests { RestTemplate restTemplate = mockRestTemplate(builder, rootUri); assertThat(registry.find("http.client.requests").meter()).isNull(); assertThat(restTemplate.getForEntity("/projects/{project}", Void.class, "spring-boot").getStatusCode()) - .isEqualTo(HttpStatus.OK); + .isEqualTo(HttpStatus.OK); assertThat(registry.get("http.client.requests").tags("uri", rootUri + "/projects/{project}").meter()) - .isNotNull(); + .isNotNull(); } private RestTemplate mockRestTemplate(RestTemplateBuilder builder, String rootUri) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/WebClientMetricsConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/WebClientMetricsConfigurationTests.java index 6e91ddaa16..f1b0d2cb60 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/WebClientMetricsConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/WebClientMetricsConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,8 +55,8 @@ import static org.mockito.Mockito.mock; class WebClientMetricsConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration( - AutoConfigurations.of(WebClientAutoConfiguration.class, HttpClientMetricsAutoConfiguration.class)); + .withConfiguration( + AutoConfigurations.of(WebClientAutoConfiguration.class, HttpClientMetricsAutoConfiguration.class)); @Test void webClientCreatedWithBuilderIsInstrumented() { @@ -69,8 +69,10 @@ class WebClientMetricsConfigurationTests { @Test void shouldNotOverrideCustomTagsProvider() { - this.contextRunner.withUserConfiguration(CustomTagsProviderConfig.class).run((context) -> assertThat(context) - .getBeans(WebClientExchangeTagsProvider.class).hasSize(1).containsKey("customTagsProvider")); + this.contextRunner.withUserConfiguration(CustomTagsProviderConfig.class) + .run((context) -> assertThat(context).getBeans(WebClientExchangeTagsProvider.class) + .hasSize(1) + .containsKey("customTagsProvider")); } @Test @@ -79,7 +81,7 @@ class WebClientMetricsConfigurationTests { MeterRegistry registry = getInitializedMeterRegistry(context); assertThat(registry.get("http.client.requests").meters()).hasSize(2); assertThat(output).contains("Reached the maximum number of URI tags for 'http.client.requests'.") - .contains("Are you using 'uriVariables'?"); + .contains("Are you using 'uriVariables'?"); }); } @@ -89,30 +91,35 @@ class WebClientMetricsConfigurationTests { MeterRegistry registry = getInitializedMeterRegistry(context); assertThat(registry.get("http.client.requests").meters()).hasSize(3); assertThat(output).doesNotContain("Reached the maximum number of URI tags for 'http.client.requests'.") - .doesNotContain("Are you using 'uriVariables'?"); + .doesNotContain("Are you using 'uriVariables'?"); }); } @Test void autoTimeRequestsCanBeConfigured() { - this.contextRunner.withPropertyValues("management.metrics.web.client.request.autotime.enabled=true", - "management.metrics.web.client.request.autotime.percentiles=0.5,0.7", - "management.metrics.web.client.request.autotime.percentiles-histogram=true").run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - Timer timer = registry.get("http.client.requests").timer(); - HistogramSnapshot snapshot = timer.takeSnapshot(); - assertThat(snapshot.percentileValues()).hasSize(2); - assertThat(snapshot.percentileValues()[0].percentile()).isEqualTo(0.5); - assertThat(snapshot.percentileValues()[1].percentile()).isEqualTo(0.7); - }); + this.contextRunner + .withPropertyValues("management.metrics.web.client.request.autotime.enabled=true", + "management.metrics.web.client.request.autotime.percentiles=0.5,0.7", + "management.metrics.web.client.request.autotime.percentiles-histogram=true") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + Timer timer = registry.get("http.client.requests").timer(); + HistogramSnapshot snapshot = timer.takeSnapshot(); + assertThat(snapshot.percentileValues()).hasSize(2); + assertThat(snapshot.percentileValues()[0].percentile()).isEqualTo(0.5); + assertThat(snapshot.percentileValues()[1].percentile()).isEqualTo(0.7); + }); } private MeterRegistry getInitializedMeterRegistry(AssertableApplicationContext context) { WebClient webClient = mockWebClient(context.getBean(WebClient.Builder.class)); MeterRegistry registry = context.getBean(MeterRegistry.class); for (int i = 0; i < 3; i++) { - webClient.get().uri("https://example.org/projects/" + i).retrieve().toBodilessEntity() - .block(Duration.ofSeconds(30)); + webClient.get() + .uri("https://example.org/projects/" + i) + .retrieve() + .toBodilessEntity() + .block(Duration.ofSeconds(30)); } return registry; } @@ -120,8 +127,11 @@ class WebClientMetricsConfigurationTests { private void validateWebClient(WebClient.Builder builder, MeterRegistry registry) { WebClient webClient = mockWebClient(builder); assertThat(registry.find("http.client.requests").meter()).isNull(); - webClient.get().uri("https://example.org/projects/{project}", "spring-boot").retrieve().toBodilessEntity() - .block(Duration.ofSeconds(30)); + webClient.get() + .uri("https://example.org/projects/{project}", "spring-boot") + .retrieve() + .toBodilessEntity() + .block(Duration.ofSeconds(30)); assertThat(registry.find("http.client.requests").tags("uri", "/projects/{project}").meter()).isNotNull(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfigurationTests.java index cc2e1e5c1b..0e8437a192 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,156 +54,157 @@ class JettyMetricsAutoConfigurationTests { @Test void autoConfiguresThreadPoolMetricsWithEmbeddedServletJetty() { new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) - .run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - assertThat(context).hasSingleBean(JettyServerThreadPoolMetricsBinder.class); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("jetty.threads.config.min").meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + assertThat(context).hasSingleBean(JettyServerThreadPoolMetricsBinder.class); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("jetty.threads.config.min").meter()).isNotNull(); + }); } @Test void autoConfiguresThreadPoolMetricsWithEmbeddedReactiveJetty() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ReactiveWebServerConfiguration.class, MeterRegistryConfiguration.class) - .run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("jetty.threads.config.min").meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ReactiveWebServerConfiguration.class, MeterRegistryConfiguration.class) + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("jetty.threads.config.min").meter()).isNotNull(); + }); } @Test void allowsCustomJettyServerThreadPoolMetricsBinderToBeUsed() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class)) - .withUserConfiguration(CustomJettyServerThreadPoolMetricsBinder.class, MeterRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(JettyServerThreadPoolMetricsBinder.class) - .hasBean("customJettyServerThreadPoolMetricsBinder")); + .withUserConfiguration(CustomJettyServerThreadPoolMetricsBinder.class, MeterRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(JettyServerThreadPoolMetricsBinder.class) + .hasBean("customJettyServerThreadPoolMetricsBinder")); } @Test void autoConfiguresConnectionMetricsWithEmbeddedServletJetty() { new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) - .run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - assertThat(context).hasSingleBean(JettyConnectionMetricsBinder.class); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("jetty.connections.messages.in").meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + assertThat(context).hasSingleBean(JettyConnectionMetricsBinder.class); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("jetty.connections.messages.in").meter()).isNotNull(); + }); } @Test void autoConfiguresConnectionMetricsWithEmbeddedReactiveJetty() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ReactiveWebServerConfiguration.class, MeterRegistryConfiguration.class) - .run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("jetty.connections.messages.in").meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ReactiveWebServerConfiguration.class, MeterRegistryConfiguration.class) + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("jetty.connections.messages.in").meter()).isNotNull(); + }); } @Test void allowsCustomJettyConnectionMetricsBinderToBeUsed() { new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, CustomJettyConnectionMetricsBinder.class, - MeterRegistryConfiguration.class) - .run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - assertThat(context).hasSingleBean(JettyConnectionMetricsBinder.class) - .hasBean("customJettyConnectionMetricsBinder"); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("jetty.connections.messages.in").tag("custom-tag-name", "custom-tag-value") - .meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ServletWebServerConfiguration.class, CustomJettyConnectionMetricsBinder.class, + MeterRegistryConfiguration.class) + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + assertThat(context).hasSingleBean(JettyConnectionMetricsBinder.class) + .hasBean("customJettyConnectionMetricsBinder"); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("jetty.connections.messages.in") + .tag("custom-tag-name", "custom-tag-value") + .meter()).isNotNull(); + }); } @Test void autoConfiguresSslHandshakeMetricsWithEmbeddedServletJetty() { new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) - .withPropertyValues("server.ssl.enabled: true", "server.ssl.key-store: src/test/resources/test.jks", - "server.ssl.key-store-password: secret", "server.ssl.key-password: password") - .run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - assertThat(context).hasSingleBean(JettySslHandshakeMetricsBinder.class); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("jetty.ssl.handshakes").meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) + .withPropertyValues("server.ssl.enabled: true", "server.ssl.key-store: src/test/resources/test.jks", + "server.ssl.key-store-password: secret", "server.ssl.key-password: password") + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + assertThat(context).hasSingleBean(JettySslHandshakeMetricsBinder.class); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("jetty.ssl.handshakes").meter()).isNotNull(); + }); } @Test void autoConfiguresSslHandshakeMetricsWithEmbeddedReactiveJetty() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ReactiveWebServerConfiguration.class, MeterRegistryConfiguration.class) - .withPropertyValues("server.ssl.enabled: true", "server.ssl.key-store: src/test/resources/test.jks", - "server.ssl.key-store-password: secret", "server.ssl.key-password: password") - .run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("jetty.ssl.handshakes").meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ReactiveWebServerConfiguration.class, MeterRegistryConfiguration.class) + .withPropertyValues("server.ssl.enabled: true", "server.ssl.key-store: src/test/resources/test.jks", + "server.ssl.key-store-password: secret", "server.ssl.key-password: password") + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("jetty.ssl.handshakes").meter()).isNotNull(); + }); } @Test void allowsCustomJettySslHandshakeMetricsBinderToBeUsed() { new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, CustomJettySslHandshakeMetricsBinder.class, - MeterRegistryConfiguration.class) - .withPropertyValues("server.ssl.enabled: true", "server.ssl.key-store: src/test/resources/test.jks", - "server.ssl.key-store-password: secret", "server.ssl.key-password: password") - .run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - assertThat(context).hasSingleBean(JettySslHandshakeMetricsBinder.class) - .hasBean("customJettySslHandshakeMetricsBinder"); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("jetty.ssl.handshakes").tag("custom-tag-name", "custom-tag-value").meter()) - .isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ServletWebServerConfiguration.class, CustomJettySslHandshakeMetricsBinder.class, + MeterRegistryConfiguration.class) + .withPropertyValues("server.ssl.enabled: true", "server.ssl.key-store: src/test/resources/test.jks", + "server.ssl.key-store-password: secret", "server.ssl.key-password: password") + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + assertThat(context).hasSingleBean(JettySslHandshakeMetricsBinder.class) + .hasBean("customJettySslHandshakeMetricsBinder"); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("jetty.ssl.handshakes").tag("custom-tag-name", "custom-tag-value").meter()) + .isNotNull(); + }); new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class)) - .withUserConfiguration(CustomJettySslHandshakeMetricsBinder.class, MeterRegistryConfiguration.class) - .withPropertyValues("server.ssl.enabled: true", "server.ssl.key-store: src/test/resources/test.jks", - "server.ssl.key-store-password: secret", "server.ssl.key-password: password") - .run((context) -> assertThat(context).hasSingleBean(JettySslHandshakeMetricsBinder.class) - .hasBean("customJettySslHandshakeMetricsBinder")); + .withUserConfiguration(CustomJettySslHandshakeMetricsBinder.class, MeterRegistryConfiguration.class) + .withPropertyValues("server.ssl.enabled: true", "server.ssl.key-store: src/test/resources/test.jks", + "server.ssl.key-store-password: secret", "server.ssl.key-password: password") + .run((context) -> assertThat(context).hasSingleBean(JettySslHandshakeMetricsBinder.class) + .hasBean("customJettySslHandshakeMetricsBinder")); } @Test void doesNotAutoConfigureSslHandshakeMetricsWhenSslEnabledPropertyNotSpecified() { new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(JettySslHandshakeMetricsBinder.class)); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(JettySslHandshakeMetricsBinder.class)); } @Test void doesNotAutoConfigureSslHandshakeMetricsWhenSslEnabledPropertySetToFalse() { new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) - .withPropertyValues("server.ssl.enabled: false") - .run((context) -> assertThat(context).doesNotHaveBean(JettySslHandshakeMetricsBinder.class)); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) + .withPropertyValues("server.ssl.enabled: false") + .run((context) -> assertThat(context).doesNotHaveBean(JettySslHandshakeMetricsBinder.class)); } private ApplicationStartedEvent createApplicationStartedEvent(ConfigurableApplicationContext context) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/reactive/WebFluxMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/reactive/WebFluxMetricsAutoConfigurationTests.java index 45352944a9..64f2bb3491 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/reactive/WebFluxMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/reactive/WebFluxMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,8 @@ import static org.mockito.Mockito.mock; class WebFluxMetricsAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .with(MetricsRun.simple()).withConfiguration(AutoConfigurations.of(WebFluxMetricsAutoConfiguration.class)); + .with(MetricsRun.simple()) + .withConfiguration(AutoConfigurations.of(WebFluxMetricsAutoConfiguration.class)); @Test void shouldProvideWebFluxMetricsBeans() { @@ -58,66 +59,70 @@ class WebFluxMetricsAutoConfigurationTests { assertThat(context).getBeans(MetricsWebFilter.class).hasSize(1); assertThat(context).getBeans(DefaultWebFluxTagsProvider.class).hasSize(1); assertThat(context.getBean(DefaultWebFluxTagsProvider.class)).extracting("ignoreTrailingSlash") - .isEqualTo(true); + .isEqualTo(true); }); } @Test void tagsProviderWhenIgnoreTrailingSlashIsFalse() { this.contextRunner.withPropertyValues("management.metrics.web.server.request.ignore-trailing-slash=false") - .run((context) -> { - assertThat(context).hasSingleBean(DefaultWebFluxTagsProvider.class); - assertThat(context.getBean(DefaultWebFluxTagsProvider.class)).extracting("ignoreTrailingSlash") - .isEqualTo(false); - }); + .run((context) -> { + assertThat(context).hasSingleBean(DefaultWebFluxTagsProvider.class); + assertThat(context.getBean(DefaultWebFluxTagsProvider.class)).extracting("ignoreTrailingSlash") + .isEqualTo(false); + }); } @Test void shouldNotOverrideCustomTagsProvider() { this.contextRunner.withUserConfiguration(CustomWebFluxTagsProviderConfig.class) - .run((context) -> assertThat(context).getBeans(WebFluxTagsProvider.class).hasSize(1) - .containsKey("customWebFluxTagsProvider")); + .run((context) -> assertThat(context).getBeans(WebFluxTagsProvider.class) + .hasSize(1) + .containsKey("customWebFluxTagsProvider")); } @Test void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput output) { this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) - .withUserConfiguration(TestController.class) - .withPropertyValues("management.metrics.web.server.max-uri-tags=2").run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - assertThat(registry.get("http.server.requests").meters()).hasSize(2); - assertThat(output).contains("Reached the maximum number of URI tags for 'http.server.requests'"); - }); + .withUserConfiguration(TestController.class) + .withPropertyValues("management.metrics.web.server.max-uri-tags=2") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + assertThat(registry.get("http.server.requests").meters()).hasSize(2); + assertThat(output).contains("Reached the maximum number of URI tags for 'http.server.requests'"); + }); } @Test void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput output) { this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) - .withUserConfiguration(TestController.class) - .withPropertyValues("management.metrics.web.server.max-uri-tags=5").run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - assertThat(registry.get("http.server.requests").meters()).hasSize(3); - assertThat(output) - .doesNotContain("Reached the maximum number of URI tags for 'http.server.requests'"); - }); + .withUserConfiguration(TestController.class) + .withPropertyValues("management.metrics.web.server.max-uri-tags=5") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + assertThat(registry.get("http.server.requests").meters()).hasSize(3); + assertThat(output).doesNotContain("Reached the maximum number of URI tags for 'http.server.requests'"); + }); } @Test void metricsAreNotRecordedIfAutoTimeRequestsIsDisabled() { this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) - .withUserConfiguration(TestController.class) - .withPropertyValues("management.metrics.web.server.request.autotime.enabled=false").run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - assertThat(registry.find("http.server.requests").meter()).isNull(); - }); + .withUserConfiguration(TestController.class) + .withPropertyValues("management.metrics.web.server.request.autotime.enabled=false") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + assertThat(registry.find("http.server.requests").meter()).isNull(); + }); } @Test void whenTagContributorsAreDefinedThenTagsProviderUsesThem() { this.contextRunner.withUserConfiguration(TagsContributorsConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(DefaultWebFluxTagsProvider.class); - assertThat(context.getBean(DefaultWebFluxTagsProvider.class)).extracting("contributors").asList() - .hasSize(2); + assertThat(context.getBean(DefaultWebFluxTagsProvider.class)).extracting("contributors") + .asList() + .hasSize(2); }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfigurationTests.java index 5eb2d5c56f..d6a06ae220 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,12 +73,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. class WebMvcMetricsAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .with(MetricsRun.simple()).withConfiguration(AutoConfigurations.of(WebMvcMetricsAutoConfiguration.class)); + .with(MetricsRun.simple()) + .withConfiguration(AutoConfigurations.of(WebMvcMetricsAutoConfiguration.class)); @Test void backsOffWhenMeterRegistryIsMissing() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(WebMvcMetricsAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(WebMvcTagsProvider.class)); + .run((context) -> assertThat(context).doesNotHaveBean(WebMvcTagsProvider.class)); } @Test @@ -86,21 +87,21 @@ class WebMvcMetricsAutoConfigurationTests { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(DefaultWebMvcTagsProvider.class); assertThat(context.getBean(DefaultWebMvcTagsProvider.class)).extracting("ignoreTrailingSlash") - .isEqualTo(true); + .isEqualTo(true); assertThat(context).hasSingleBean(FilterRegistrationBean.class); assertThat(context.getBean(FilterRegistrationBean.class).getFilter()) - .isInstanceOf(WebMvcMetricsFilter.class); + .isInstanceOf(WebMvcMetricsFilter.class); }); } @Test void tagsProviderWhenIgnoreTrailingSlashIsFalse() { this.contextRunner.withPropertyValues("management.metrics.web.server.request.ignore-trailing-slash=false") - .run((context) -> { - assertThat(context).hasSingleBean(DefaultWebMvcTagsProvider.class); - assertThat(context.getBean(DefaultWebMvcTagsProvider.class)).extracting("ignoreTrailingSlash") - .isEqualTo(false); - }); + .run((context) -> { + assertThat(context).hasSingleBean(DefaultWebMvcTagsProvider.class); + assertThat(context.getBean(DefaultWebMvcTagsProvider.class)).extracting("ignoreTrailingSlash") + .isEqualTo(false); + }); } @Test @@ -124,93 +125,96 @@ class WebMvcMetricsAutoConfigurationTests { @Test void filterRegistrationBacksOffWithAnotherWebMvcMetricsFilterRegistration() { this.contextRunner.withUserConfiguration(TestWebMvcMetricsFilterRegistrationConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(FilterRegistrationBean.class); - assertThat(context.getBean(FilterRegistrationBean.class)) - .isSameAs(context.getBean("testWebMvcMetricsFilter")); - }); + .run((context) -> { + assertThat(context).hasSingleBean(FilterRegistrationBean.class); + assertThat(context.getBean(FilterRegistrationBean.class)) + .isSameAs(context.getBean("testWebMvcMetricsFilter")); + }); } @Test void filterRegistrationBacksOffWithAnotherWebMvcMetricsFilter() { this.contextRunner.withUserConfiguration(TestWebMvcMetricsFilterConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(FilterRegistrationBean.class) - .hasSingleBean(WebMvcMetricsFilter.class)); + .run((context) -> assertThat(context).doesNotHaveBean(FilterRegistrationBean.class) + .hasSingleBean(WebMvcMetricsFilter.class)); } @Test void filterRegistrationDoesNotBackOffWithOtherFilterRegistration() { this.contextRunner.withUserConfiguration(TestFilterRegistrationConfiguration.class) - .run((context) -> assertThat(context).hasBean("testFilter").hasBean("webMvcMetricsFilter")); + .run((context) -> assertThat(context).hasBean("testFilter").hasBean("webMvcMetricsFilter")); } @Test void filterRegistrationDoesNotBackOffWithOtherFilter() { this.contextRunner.withUserConfiguration(TestFilterConfiguration.class) - .run((context) -> assertThat(context).hasBean("testFilter").hasBean("webMvcMetricsFilter")); + .run((context) -> assertThat(context).hasBean("testFilter").hasBean("webMvcMetricsFilter")); } @Test void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput output) { this.contextRunner.withUserConfiguration(TestController.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) - .withPropertyValues("management.metrics.web.server.max-uri-tags=2").run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - assertThat(registry.get("http.server.requests").meters()).hasSize(2); - assertThat(output).contains("Reached the maximum number of URI tags for 'http.server.requests'"); - }); + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) + .withPropertyValues("management.metrics.web.server.max-uri-tags=2") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + assertThat(registry.get("http.server.requests").meters()).hasSize(2); + assertThat(output).contains("Reached the maximum number of URI tags for 'http.server.requests'"); + }); } @Test void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput output) { this.contextRunner.withUserConfiguration(TestController.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) - .withPropertyValues("management.metrics.web.server.max-uri-tags=5").run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - assertThat(registry.get("http.server.requests").meters()).hasSize(3); - assertThat(output) - .doesNotContain("Reached the maximum number of URI tags for 'http.server.requests'"); - }); + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) + .withPropertyValues("management.metrics.web.server.max-uri-tags=5") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + assertThat(registry.get("http.server.requests").meters()).hasSize(3); + assertThat(output).doesNotContain("Reached the maximum number of URI tags for 'http.server.requests'"); + }); } @Test void autoTimeRequestsCanBeConfigured() { this.contextRunner.withUserConfiguration(TestController.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) - .withPropertyValues("management.metrics.web.server.request.autotime.enabled=true", - "management.metrics.web.server.request.autotime.percentiles=0.5,0.7", - "management.metrics.web.server.request.autotime.percentiles-histogram=true") - .run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - Timer timer = registry.get("http.server.requests").timer(); - HistogramSnapshot snapshot = timer.takeSnapshot(); - assertThat(snapshot.percentileValues()).hasSize(2); - assertThat(snapshot.percentileValues()[0].percentile()).isEqualTo(0.5); - assertThat(snapshot.percentileValues()[1].percentile()).isEqualTo(0.7); - }); + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) + .withPropertyValues("management.metrics.web.server.request.autotime.enabled=true", + "management.metrics.web.server.request.autotime.percentiles=0.5,0.7", + "management.metrics.web.server.request.autotime.percentiles-histogram=true") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + Timer timer = registry.get("http.server.requests").timer(); + HistogramSnapshot snapshot = timer.takeSnapshot(); + assertThat(snapshot.percentileValues()).hasSize(2); + assertThat(snapshot.percentileValues()[0].percentile()).isEqualTo(0.5); + assertThat(snapshot.percentileValues()[1].percentile()).isEqualTo(0.7); + }); } @Test void timerWorksWithTimedAnnotationsWhenAutoTimeRequestsIsFalse() { this.contextRunner.withUserConfiguration(TestController.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) - .withPropertyValues("management.metrics.web.server.request.autotime.enabled=false").run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context, "/test3"); - Collection meters = registry.get("http.server.requests").meters(); - assertThat(meters).hasSize(1); - Meter meter = meters.iterator().next(); - assertThat(meter.getId().getTag("uri")).isEqualTo("/test3"); - }); + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) + .withPropertyValues("management.metrics.web.server.request.autotime.enabled=false") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context, "/test3"); + Collection meters = registry.get("http.server.requests").meters(); + assertThat(meters).hasSize(1); + Meter meter = meters.iterator().next(); + assertThat(meter.getId().getTag("uri")).isEqualTo("/test3"); + }); } @Test @SuppressWarnings("rawtypes") void longTaskTimingInterceptorIsRegistered() { this.contextRunner.withUserConfiguration(TestController.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) - .run((context) -> assertThat(context.getBean(RequestMappingHandlerMapping.class)) - .extracting("interceptors").asList().extracting((item) -> (Class) item.getClass()) - .contains(LongTaskTimingHandlerInterceptor.class)); + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) + .run((context) -> assertThat(context.getBean(RequestMappingHandlerMapping.class)).extracting("interceptors") + .asList() + .extracting((item) -> (Class) item.getClass()) + .contains(LongTaskTimingHandlerInterceptor.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfigurationTests.java index 1356e9ab5a..0fe2d3c39e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,54 +58,56 @@ class TomcatMetricsAutoConfigurationTests { void autoConfiguresTomcatMetricsWithEmbeddedServletTomcat() { resetTomcatState(); new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) - .withPropertyValues("server.tomcat.mbeanregistry.enabled=true").run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - assertThat(context).hasSingleBean(TomcatMetricsBinder.class); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("tomcat.sessions.active.max").meter()).isNotNull(); - assertThat(registry.find("tomcat.threads.current").meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) + .withPropertyValues("server.tomcat.mbeanregistry.enabled=true") + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + assertThat(context).hasSingleBean(TomcatMetricsBinder.class); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("tomcat.sessions.active.max").meter()).isNotNull(); + assertThat(registry.find("tomcat.threads.current").meter()).isNotNull(); + }); } @Test void autoConfiguresTomcatMetricsWithEmbeddedReactiveTomcat() { resetTomcatState(); new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class, - ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ReactiveWebServerConfiguration.class, MeterRegistryConfiguration.class) - .withPropertyValues("server.tomcat.mbeanregistry.enabled=true").run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("tomcat.sessions.active.max").meter()).isNotNull(); - assertThat(registry.find("tomcat.threads.current").meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class, + ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ReactiveWebServerConfiguration.class, MeterRegistryConfiguration.class) + .withPropertyValues("server.tomcat.mbeanregistry.enabled=true") + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("tomcat.sessions.active.max").meter()).isNotNull(); + assertThat(registry.find("tomcat.threads.current").meter()).isNotNull(); + }); } @Test void autoConfiguresTomcatMetricsWithStandaloneTomcat() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class)) - .withUserConfiguration(MeterRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(TomcatMetricsBinder.class)); + .withUserConfiguration(MeterRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(TomcatMetricsBinder.class)); } @Test void allowsCustomTomcatMetricsBinderToBeUsed() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class)) - .withUserConfiguration(MeterRegistryConfiguration.class, CustomTomcatMetricsBinder.class) - .run((context) -> assertThat(context).hasSingleBean(TomcatMetricsBinder.class) - .hasBean("customTomcatMetricsBinder")); + .withUserConfiguration(MeterRegistryConfiguration.class, CustomTomcatMetricsBinder.class) + .run((context) -> assertThat(context).hasSingleBean(TomcatMetricsBinder.class) + .hasBean("customTomcatMetricsBinder")); } @Test void allowsCustomTomcatMetricsToBeUsed() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class)) - .withUserConfiguration(MeterRegistryConfiguration.class, CustomTomcatMetrics.class) - .run((context) -> assertThat(context).doesNotHaveBean(TomcatMetricsBinder.class) - .hasBean("customTomcatMetrics")); + .withUserConfiguration(MeterRegistryConfiguration.class, CustomTomcatMetrics.class) + .run((context) -> assertThat(context).doesNotHaveBean(TomcatMetricsBinder.class) + .hasBean("customTomcatMetrics")); } private ApplicationStartedEvent createApplicationStartedEvent(ConfigurableApplicationContext context) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthContributorAutoConfigurationTests.java index 02a763d734..df3c7ea772 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,8 @@ import static org.assertj.core.api.Assertions.assertThat; class MongoHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - MongoHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { @@ -46,7 +46,7 @@ class MongoHealthContributorAutoConfigurationTests { @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.mongo.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(MongoHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(MongoHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthContributorAutoConfigurationTests.java index 7b37b22711..3730f89c6e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,28 +38,29 @@ import static org.assertj.core.api.Assertions.assertThat; class MongoReactiveHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, - MongoReactiveHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, + MongoReactiveHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MongoReactiveHealthIndicator.class) - .hasBean("mongoHealthContributor")); + .hasBean("mongoHealthContributor")); } @Test void runWithRegularIndicatorShouldOnlyCreateReactiveIndicator() { this.contextRunner.withConfiguration(AutoConfigurations.of(MongoHealthContributorAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(MongoReactiveHealthIndicator.class) - .hasBean("mongoHealthContributor").doesNotHaveBean(MongoHealthIndicator.class)); + .run((context) -> assertThat(context).hasSingleBean(MongoReactiveHealthIndicator.class) + .hasBean("mongoHealthContributor") + .doesNotHaveBean(MongoHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.mongo.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(MongoReactiveHealthIndicator.class) - .doesNotHaveBean("mongoHealthContributor")); + .run((context) -> assertThat(context).doesNotHaveBean(MongoReactiveHealthIndicator.class) + .doesNotHaveBean("mongoHealthContributor")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthContributorAutoConfigurationTests.java index c47a0d0e39..5135660ba8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,44 +46,46 @@ import static org.mockito.Mockito.mock; class Neo4jHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, - Neo4jHealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, + Neo4jHealthContributorAutoConfiguration.class)); @Test void runShouldCreateHealthIndicator() { - this.contextRunner.withUserConfiguration(Neo4jConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(Neo4jReactiveHealthIndicator.class).doesNotHaveBean(Neo4jHealthIndicator.class)); + this.contextRunner.withUserConfiguration(Neo4jConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(Neo4jReactiveHealthIndicator.class) + .doesNotHaveBean(Neo4jHealthIndicator.class)); } @Test void runWithoutReactorShouldCreateHealthIndicator() { this.contextRunner.withUserConfiguration(Neo4jConfiguration.class) - .withClassLoader(new FilteredClassLoader(Flux.class)).run((context) -> assertThat(context) - .hasSingleBean(Neo4jHealthIndicator.class).doesNotHaveBean(Neo4jReactiveHealthIndicator.class)); + .withClassLoader(new FilteredClassLoader(Flux.class)) + .run((context) -> assertThat(context).hasSingleBean(Neo4jHealthIndicator.class) + .doesNotHaveBean(Neo4jReactiveHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withUserConfiguration(Neo4jConfiguration.class) - .withPropertyValues("management.health.neo4j.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(Neo4jHealthIndicator.class) - .doesNotHaveBean(Neo4jReactiveHealthIndicator.class)); + .withPropertyValues("management.health.neo4j.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(Neo4jHealthIndicator.class) + .doesNotHaveBean(Neo4jReactiveHealthIndicator.class)); } @Test void defaultIndicatorCanBeReplaced() { this.contextRunner.withUserConfiguration(Neo4jConfiguration.class, CustomIndicatorConfiguration.class) - .run((context) -> { - assertThat(context).hasBean("neo4jHealthIndicator"); - Health health = context.getBean("neo4jHealthIndicator", HealthIndicator.class).health(); - assertThat(health.getDetails()).containsOnly(entry("test", true)); - }); + .run((context) -> { + assertThat(context).hasBean("neo4jHealthIndicator"); + Health health = context.getBean("neo4jHealthIndicator", HealthIndicator.class).health(); + assertThat(health.getDetails()).containsOnly(entry("test", true)); + }); } @Test void shouldRequireDriverBean() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(Neo4jHealthIndicator.class) - .doesNotHaveBean(Neo4jReactiveHealthIndicator.class)); + .doesNotHaveBean(Neo4jReactiveHealthIndicator.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/quartz/QuartzEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/quartz/QuartzEndpointAutoConfigurationTests.java index 4b6cb39180..f373bdd2bf 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/quartz/QuartzEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/quartz/QuartzEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,47 +38,47 @@ import static org.mockito.Mockito.mock; class QuartzEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(QuartzEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(QuartzEndpointAutoConfiguration.class)); @Test void endpointIsAutoConfigured() { this.contextRunner.withBean(Scheduler.class, () -> mock(Scheduler.class)) - .withPropertyValues("management.endpoints.web.exposure.include=quartz") - .run((context) -> assertThat(context).hasSingleBean(QuartzEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=quartz") + .run((context) -> assertThat(context).hasSingleBean(QuartzEndpoint.class)); } @Test void endpointIsNotAutoConfiguredIfSchedulerIsNotAvailable() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=quartz") - .run((context) -> assertThat(context).doesNotHaveBean(QuartzEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(QuartzEndpoint.class)); } @Test void endpointNotAutoConfiguredWhenNotExposed() { this.contextRunner.withBean(Scheduler.class, () -> mock(Scheduler.class)) - .run((context) -> assertThat(context).doesNotHaveBean(QuartzEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(QuartzEndpoint.class)); } @Test void endpointCanBeDisabled() { this.contextRunner.withBean(Scheduler.class, () -> mock(Scheduler.class)) - .withPropertyValues("management.endpoint.quartz.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(QuartzEndpoint.class)); + .withPropertyValues("management.endpoint.quartz.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(QuartzEndpoint.class)); } @Test void endpointBacksOffWhenUserProvidedEndpointIsPresent() { this.contextRunner.withUserConfiguration(CustomEndpointConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(QuartzEndpoint.class).hasBean("customEndpoint")); + .run((context) -> assertThat(context).hasSingleBean(QuartzEndpoint.class).hasBean("customEndpoint")); } @Test void runWhenOnlyExposedOverJmxShouldHaveEndpointBeanWithoutWebExtension() { this.contextRunner.withBean(Scheduler.class, () -> mock(Scheduler.class)) - .withPropertyValues("management.endpoints.web.exposure.include=info", "spring.jmx.enabled=true", - "management.endpoints.jmx.exposure.include=quartz") - .run((context) -> assertThat(context).hasSingleBean(QuartzEndpoint.class) - .doesNotHaveBean(QuartzEndpointWebExtension.class)); + .withPropertyValues("management.endpoints.web.exposure.include=info", "spring.jmx.enabled=true", + "management.endpoints.jmx.exposure.include=quartz") + .run((context) -> assertThat(context).hasSingleBean(QuartzEndpoint.class) + .doesNotHaveBean(QuartzEndpointWebExtension.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/r2dbc/ConnectionFactoryHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/r2dbc/ConnectionFactoryHealthContributorAutoConfigurationTests.java index d10344b5e2..570103dd97 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/r2dbc/ConnectionFactoryHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/r2dbc/ConnectionFactoryHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,26 +34,26 @@ import static org.assertj.core.api.Assertions.assertThat; class ConnectionFactoryHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ConnectionFactoryHealthContributorAutoConfiguration.class, - HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ConnectionFactoryHealthContributorAutoConfiguration.class, + HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(ConnectionFactoryHealthIndicator.class)); + .run((context) -> assertThat(context).hasSingleBean(ConnectionFactoryHealthIndicator.class)); } @Test void runWithNoConnectionFactoryShouldNotCreateIndicator() { this.contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(ConnectionFactoryHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ConnectionFactoryHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .withPropertyValues("management.health.r2dbc.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(ConnectionFactoryHealthIndicator.class)); + .withPropertyValues("management.health.r2dbc.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(ConnectionFactoryHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthContributorAutoConfigurationTests.java index ff100f4359..f40519ce80 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,20 +37,20 @@ import static org.assertj.core.api.Assertions.assertThat; class RedisHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, - RedisHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, + RedisHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(RedisHealthIndicator.class) - .doesNotHaveBean(RedisReactiveHealthIndicator.class)); + .doesNotHaveBean(RedisReactiveHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.redis.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(RedisHealthIndicator.class) - .doesNotHaveBean(RedisReactiveHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(RedisHealthIndicator.class) + .doesNotHaveBean(RedisReactiveHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthContributorAutoConfigurationTests.java index 846fff6dce..d4fc8b2cff 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,27 +35,28 @@ import static org.assertj.core.api.Assertions.assertThat; class RedisReactiveHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, - RedisReactiveHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, + RedisReactiveHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(RedisReactiveHealthIndicator.class) - .hasBean("redisHealthContributor")); + .hasBean("redisHealthContributor")); } @Test void runWithRegularIndicatorShouldOnlyCreateReactiveIndicator() { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisHealthContributorAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(RedisReactiveHealthIndicator.class) - .hasBean("redisHealthContributor").doesNotHaveBean(RedisHealthIndicator.class)); + .run((context) -> assertThat(context).hasSingleBean(RedisReactiveHealthIndicator.class) + .hasBean("redisHealthContributor") + .doesNotHaveBean(RedisHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.redis.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(RedisReactiveHealthIndicator.class) - .doesNotHaveBean("redisHealthContributor")); + .run((context) -> assertThat(context).doesNotHaveBean(RedisReactiveHealthIndicator.class) + .doesNotHaveBean("redisHealthContributor")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfigurationTests.java index e24e69d421..b1c8ed48b8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,12 +36,12 @@ import static org.assertj.core.api.Assertions.assertThat; class ScheduledTasksEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ScheduledTasksEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ScheduledTasksEndpointAutoConfiguration.class)); @Test void endpointIsAutoConfigured() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=scheduledtasks") - .run((context) -> assertThat(context).hasSingleBean(ScheduledTasksEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(ScheduledTasksEndpoint.class)); } @Test @@ -52,13 +52,14 @@ class ScheduledTasksEndpointAutoConfigurationTests { @Test void endpointCanBeDisabled() { this.contextRunner.withPropertyValues("management.endpoint.scheduledtasks.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(ScheduledTasksEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ScheduledTasksEndpoint.class)); } @Test void endpointBacksOffWhenUserProvidedEndpointIsPresent() { - this.contextRunner.withUserConfiguration(CustomEndpointConfiguration.class).run( - (context) -> assertThat(context).hasSingleBean(ScheduledTasksEndpoint.class).hasBean("customEndpoint")); + this.contextRunner.withUserConfiguration(CustomEndpointConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(ScheduledTasksEndpoint.class) + .hasBean("customEndpoint")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequestTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequestTests.java index a3dce33bb2..6d8a50ae8a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequestTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequestTests.java @@ -128,8 +128,8 @@ class EndpointRequestTests { @Test void excludeByClassShouldNotMatchExcluded() { - ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint().excluding(FooEndpoint.class, - BazServletEndpoint.class); + ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint() + .excluding(FooEndpoint.class, BazServletEndpoint.class); List> endpoints = new ArrayList<>(); endpoints.add(mockEndpoint(EndpointId.of("foo"), "foo")); endpoints.add(mockEndpoint(EndpointId.of("bar"), "bar")); @@ -143,8 +143,9 @@ class EndpointRequestTests { @Test void excludeByClassShouldNotMatchLinksIfExcluded() { - ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks() - .excluding(FooEndpoint.class); + ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint() + .excludingLinks() + .excluding(FooEndpoint.class); assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).doesNotMatch("/actuator"); } @@ -267,7 +268,8 @@ class EndpointRequestTests { private void matches(ServerWebExchange exchange) { assertThat(this.matcher.matches(exchange).block(Duration.ofSeconds(30)).isMatch()) - .as("Matches " + getRequestPath(exchange)).isTrue(); + .as("Matches " + getRequestPath(exchange)) + .isTrue(); } void doesNotMatch(String path) { @@ -278,7 +280,8 @@ class EndpointRequestTests { private void doesNotMatch(ServerWebExchange exchange) { assertThat(this.matcher.matches(exchange).block(Duration.ofSeconds(30)).isMatch()) - .as("Does not match " + getRequestPath(exchange)).isFalse(); + .as("Does not match " + getRequestPath(exchange)) + .isFalse(); } private TestHttpWebHandlerAdapter webHandler() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfigurationTests.java index 9355cabce0..48fa6e6263 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,12 +66,12 @@ import static org.mockito.Mockito.mock; class ReactiveManagementWebSecurityAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, InfoEndpointAutoConfiguration.class, - WebFluxAutoConfiguration.class, EnvironmentEndpointAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - ReactiveSecurityAutoConfiguration.class, ReactiveUserDetailsServiceAutoConfiguration.class, - ReactiveManagementWebSecurityAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, + HealthEndpointAutoConfiguration.class, InfoEndpointAutoConfiguration.class, + WebFluxAutoConfiguration.class, EnvironmentEndpointAutoConfiguration.class, + EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + ReactiveSecurityAutoConfiguration.class, ReactiveUserDetailsServiceAutoConfiguration.class, + ReactiveManagementWebSecurityAutoConfiguration.class)); @Test void permitAllForHealth() { @@ -105,9 +105,9 @@ class ReactiveManagementWebSecurityAutoConfigurationTests { @Test void backOffIfReactiveOAuth2ResourceServerAutoConfigurationPresent() { this.contextRunner.withConfiguration(AutoConfigurations.of(ReactiveOAuth2ResourceServerAutoConfiguration.class)) - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://authserver") - .run((context) -> assertThat(context) - .doesNotHaveBean(ReactiveManagementWebSecurityAutoConfiguration.class)); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://authserver") + .run((context) -> assertThat(context) + .doesNotHaveBean(ReactiveManagementWebSecurityAutoConfiguration.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/AbstractEndpointRequestIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/AbstractEndpointRequestIntegrationTests.java index 9d9e26e41b..f004f0e7e6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/AbstractEndpointRequestIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/AbstractEndpointRequestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,8 +62,12 @@ abstract class AbstractEndpointRequestIntegrationTests { getContextRunner().withPropertyValues("spring.security.user.password=password").run((context) -> { WebTestClient webTestClient = getWebTestClient(context); webTestClient.get().uri("/actuator/e2").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/actuator/e2").header("Authorization", getBasicAuth()).exchange().expectStatus() - .isOk(); + webTestClient.get() + .uri("/actuator/e2") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); }); } @@ -78,10 +82,10 @@ abstract class AbstractEndpointRequestIntegrationTests { protected final WebApplicationContextRunner getContextRunner() { return createContextRunner().withPropertyValues("management.endpoints.web.exposure.include=*") - .withUserConfiguration(BaseConfiguration.class, SecurityConfiguration.class).withConfiguration( - AutoConfigurations.of(JacksonAutoConfiguration.class, SecurityAutoConfiguration.class, - UserDetailsServiceAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class)); + .withUserConfiguration(BaseConfiguration.class, SecurityConfiguration.class) + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, SecurityAutoConfiguration.class, + UserDetailsServiceAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class)); } @@ -89,9 +93,12 @@ abstract class AbstractEndpointRequestIntegrationTests { protected WebTestClient getWebTestClient(AssertableWebApplicationContext context) { int port = context.getSourceApplicationContext(AnnotationConfigServletWebServerApplicationContext.class) - .getWebServer().getPort(); - return WebTestClient.bindToServer().baseUrl("http://localhost:" + port).responseTimeout(Duration.ofMinutes(5)) - .build(); + .getWebServer() + .getPort(); + return WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port) + .responseTimeout(Duration.ofMinutes(5)) + .build(); } String getBasicAuth() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/JerseyEndpointRequestIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/JerseyEndpointRequestIntegrationTests.java index 1e06f70cb5..75bea2a95f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/JerseyEndpointRequestIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/JerseyEndpointRequestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,50 +58,73 @@ class JerseyEndpointRequestIntegrationTests extends AbstractEndpointRequestInteg @Test void toAnyEndpointWhenApplicationPathSetShouldMatch() { getContextRunner() - .withPropertyValues("spring.jersey.application-path=/admin", "spring.security.user.password=password") - .run((context) -> { - WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/admin/actuator/e2").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/admin/actuator/e2").header("Authorization", getBasicAuth()).exchange() - .expectStatus().isOk(); - }); + .withPropertyValues("spring.jersey.application-path=/admin", "spring.security.user.password=password") + .run((context) -> { + WebTestClient webTestClient = getWebTestClient(context); + webTestClient.get().uri("/admin/actuator/e2").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/admin/actuator/e2") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + }); } @Test void toAnyEndpointShouldMatchServletEndpoint() { - getContextRunner().withPropertyValues("spring.security.user.password=password", - "management.endpoints.web.exposure.include=se1").run((context) -> { - WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/actuator/se1").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/actuator/se1").header("Authorization", getBasicAuth()).exchange() - .expectStatus().isOk(); - webTestClient.get().uri("/actuator/se1/list").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/actuator/se1/list").header("Authorization", getBasicAuth()).exchange() - .expectStatus().isOk(); - }); + getContextRunner() + .withPropertyValues("spring.security.user.password=password", + "management.endpoints.web.exposure.include=se1") + .run((context) -> { + WebTestClient webTestClient = getWebTestClient(context); + webTestClient.get().uri("/actuator/se1").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/actuator/se1") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + webTestClient.get().uri("/actuator/se1/list").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/actuator/se1/list") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + }); } @Test void toAnyEndpointWhenApplicationPathSetShouldMatchServletEndpoint() { - getContextRunner().withPropertyValues("spring.jersey.application-path=/admin", - "spring.security.user.password=password", "management.endpoints.web.exposure.include=se1") - .run((context) -> { - WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/admin/actuator/se1").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/admin/actuator/se1").header("Authorization", getBasicAuth()).exchange() - .expectStatus().isOk(); - webTestClient.get().uri("/admin/actuator/se1/list").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/admin/actuator/se1/list").header("Authorization", getBasicAuth()) - .exchange().expectStatus().isOk(); - }); + getContextRunner() + .withPropertyValues("spring.jersey.application-path=/admin", "spring.security.user.password=password", + "management.endpoints.web.exposure.include=se1") + .run((context) -> { + WebTestClient webTestClient = getWebTestClient(context); + webTestClient.get().uri("/admin/actuator/se1").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/admin/actuator/se1") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + webTestClient.get().uri("/admin/actuator/se1/list").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/admin/actuator/se1/list") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + }); } @Override protected WebApplicationContextRunner createContextRunner() { return new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) - .withUserConfiguration(JerseyEndpointConfiguration.class) - .withConfiguration(AutoConfigurations.of(JerseyAutoConfiguration.class)); + .withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) + .withUserConfiguration(JerseyEndpointConfiguration.class) + .withConfiguration(AutoConfigurations.of(JerseyAutoConfiguration.class)); } @Configuration diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfigurationTests.java index f1c3df7acf..88da5e3147 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -127,34 +127,34 @@ class ManagementWebSecurityAutoConfigurationTests { @Test void backOffIfOAuth2ResourceServerAutoConfigurationPresent() { this.contextRunner.withConfiguration(AutoConfigurations.of(OAuth2ResourceServerAutoConfiguration.class)) - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://authserver") - .run((context) -> assertThat(context).doesNotHaveBean(ManagementWebSecurityAutoConfiguration.class) - .doesNotHaveBean(MANAGEMENT_SECURITY_FILTER_CHAIN_BEAN)); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://authserver") + .run((context) -> assertThat(context).doesNotHaveBean(ManagementWebSecurityAutoConfiguration.class) + .doesNotHaveBean(MANAGEMENT_SECURITY_FILTER_CHAIN_BEAN)); } @Test void backOffIfSaml2RelyingPartyAutoConfigurationPresent() { this.contextRunner.withConfiguration(AutoConfigurations.of(Saml2RelyingPartyAutoConfiguration.class)) - .withPropertyValues( - "spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.single-sign-on.url=https://simplesaml-for-spring-saml/SSOService.php", - "spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.single-sign-on.sign-request=false", - "spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.entity-id=https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/metadata.php", - "spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.verification.credentials[0].certificate-location=classpath:saml/certificate-location") - .run((context) -> assertThat(context).doesNotHaveBean(ManagementWebSecurityAutoConfiguration.class) - .doesNotHaveBean(MANAGEMENT_SECURITY_FILTER_CHAIN_BEAN)); + .withPropertyValues( + "spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.single-sign-on.url=https://simplesaml-for-spring-saml/SSOService.php", + "spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.single-sign-on.sign-request=false", + "spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.entity-id=https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/metadata.php", + "spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.verification.credentials[0].certificate-location=classpath:saml/certificate-location") + .run((context) -> assertThat(context).doesNotHaveBean(ManagementWebSecurityAutoConfiguration.class) + .doesNotHaveBean(MANAGEMENT_SECURITY_FILTER_CHAIN_BEAN)); } @Test @Deprecated void backOffIfSaml2RelyingPartyAutoConfigurationPresentDeprecated() { this.contextRunner.withConfiguration(AutoConfigurations.of(Saml2RelyingPartyAutoConfiguration.class)) - .withPropertyValues( - "spring.security.saml2.relyingparty.registration.simplesamlphp.identityprovider.single-sign-on.url=https://simplesaml-for-spring-saml/SSOService.php", - "spring.security.saml2.relyingparty.registration.simplesamlphp.identityprovider.single-sign-on.sign-request=false", - "spring.security.saml2.relyingparty.registration.simplesamlphp.identityprovider.entity-id=https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/metadata.php", - "spring.security.saml2.relyingparty.registration.simplesamlphp.identityprovider.verification.credentials[0].certificate-location=classpath:saml/certificate-location") - .run((context) -> assertThat(context).doesNotHaveBean(ManagementWebSecurityAutoConfiguration.class) - .doesNotHaveBean(MANAGEMENT_SECURITY_FILTER_CHAIN_BEAN)); + .withPropertyValues( + "spring.security.saml2.relyingparty.registration.simplesamlphp.identityprovider.single-sign-on.url=https://simplesaml-for-spring-saml/SSOService.php", + "spring.security.saml2.relyingparty.registration.simplesamlphp.identityprovider.single-sign-on.sign-request=false", + "spring.security.saml2.relyingparty.registration.simplesamlphp.identityprovider.entity-id=https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/metadata.php", + "spring.security.saml2.relyingparty.registration.simplesamlphp.identityprovider.verification.credentials[0].certificate-location=classpath:saml/certificate-location") + .run((context) -> assertThat(context).doesNotHaveBean(ManagementWebSecurityAutoConfiguration.class) + .doesNotHaveBean(MANAGEMENT_SECURITY_FILTER_CHAIN_BEAN)); } @Test @@ -163,9 +163,10 @@ class ManagementWebSecurityAutoConfigurationTests { SecurityFilterChain testSecurityFilterChain = context.getBean("testSecurityFilterChain", SecurityFilterChain.class); SecurityFilterChain testRemoteDevToolsSecurityFilterChain = context - .getBean("testRemoteDevToolsSecurityFilterChain", SecurityFilterChain.class); + .getBean("testRemoteDevToolsSecurityFilterChain", SecurityFilterChain.class); List orderedSecurityFilterChains = context.getBeanProvider(SecurityFilterChain.class) - .orderedStream().collect(Collectors.toList()); + .orderedStream() + .collect(Collectors.toList()); assertThat(orderedSecurityFilterChains).containsExactly(testRemoteDevToolsSecurityFilterChain, testSecurityFilterChain); assertThat(context).doesNotHaveBean(ManagementWebSecurityAutoConfiguration.class); @@ -207,8 +208,9 @@ class ManagementWebSecurityAutoConfigurationTests { @Bean SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception { - return http.antMatcher("/**").authorizeRequests((authorize) -> authorize.anyRequest().authenticated()) - .build(); + return http.antMatcher("/**") + .authorizeRequests((authorize) -> authorize.anyRequest().authenticated()) + .build(); } } @@ -219,8 +221,14 @@ class ManagementWebSecurityAutoConfigurationTests { @Bean @Order(SecurityProperties.BASIC_AUTH_ORDER - 1) SecurityFilterChain testRemoteDevToolsSecurityFilterChain(HttpSecurity http) throws Exception { - return http.requestMatcher(new AntPathRequestMatcher("/**")).authorizeRequests().anyRequest().anonymous() - .and().csrf().disable().build(); + return http.requestMatcher(new AntPathRequestMatcher("/**")) + .authorizeRequests() + .anyRequest() + .anonymous() + .and() + .csrf() + .disable() + .build(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/MvcEndpointRequestIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/MvcEndpointRequestIntegrationTests.java index 86722ba93d..2af3d5a81d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/MvcEndpointRequestIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/MvcEndpointRequestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,50 +58,73 @@ class MvcEndpointRequestIntegrationTests extends AbstractEndpointRequestIntegrat @Test void toAnyEndpointWhenServletPathSetShouldMatch() { getContextRunner() - .withPropertyValues("spring.mvc.servlet.path=/admin", "spring.security.user.password=password") - .run((context) -> { - WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/admin/actuator/e2").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/admin/actuator/e2").header("Authorization", getBasicAuth()).exchange() - .expectStatus().isOk(); - }); + .withPropertyValues("spring.mvc.servlet.path=/admin", "spring.security.user.password=password") + .run((context) -> { + WebTestClient webTestClient = getWebTestClient(context); + webTestClient.get().uri("/admin/actuator/e2").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/admin/actuator/e2") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + }); } @Test void toAnyEndpointShouldMatchServletEndpoint() { - getContextRunner().withPropertyValues("spring.security.user.password=password", - "management.endpoints.web.exposure.include=se1").run((context) -> { - WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/actuator/se1").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/actuator/se1").header("Authorization", getBasicAuth()).exchange() - .expectStatus().isOk(); - webTestClient.get().uri("/actuator/se1/list").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/actuator/se1/list").header("Authorization", getBasicAuth()).exchange() - .expectStatus().isOk(); - }); + getContextRunner() + .withPropertyValues("spring.security.user.password=password", + "management.endpoints.web.exposure.include=se1") + .run((context) -> { + WebTestClient webTestClient = getWebTestClient(context); + webTestClient.get().uri("/actuator/se1").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/actuator/se1") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + webTestClient.get().uri("/actuator/se1/list").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/actuator/se1/list") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + }); } @Test void toAnyEndpointWhenServletPathSetShouldMatchServletEndpoint() { - getContextRunner().withPropertyValues("spring.mvc.servlet.path=/admin", - "spring.security.user.password=password", "management.endpoints.web.exposure.include=se1") - .run((context) -> { - WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/admin/actuator/se1").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/admin/actuator/se1").header("Authorization", getBasicAuth()).exchange() - .expectStatus().isOk(); - webTestClient.get().uri("/admin/actuator/se1/list").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/admin/actuator/se1/list").header("Authorization", getBasicAuth()) - .exchange().expectStatus().isOk(); - }); + getContextRunner() + .withPropertyValues("spring.mvc.servlet.path=/admin", "spring.security.user.password=password", + "management.endpoints.web.exposure.include=se1") + .run((context) -> { + WebTestClient webTestClient = getWebTestClient(context); + webTestClient.get().uri("/admin/actuator/se1").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/admin/actuator/se1") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + webTestClient.get().uri("/admin/actuator/se1/list").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/admin/actuator/se1/list") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + }); } @Override protected WebApplicationContextRunner createContextRunner() { return new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withUserConfiguration(WebMvcEndpointConfiguration.class) - .withConfiguration(AutoConfigurations.of(DispatcherServletAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class)); + .withUserConfiguration(WebMvcEndpointConfiguration.class) + .withConfiguration(AutoConfigurations.of(DispatcherServletAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/SecurityRequestMatchersManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/SecurityRequestMatchersManagementContextConfigurationTests.java index 951d4b5ba9..c10a3c24a7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/SecurityRequestMatchersManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/SecurityRequestMatchersManagementContextConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,22 +40,21 @@ import static org.assertj.core.api.Assertions.assertThat; class SecurityRequestMatchersManagementContextConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SecurityRequestMatchersManagementContextConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SecurityRequestMatchersManagementContextConfiguration.class)); @Test void configurationConditionalOnWebApplication() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SecurityRequestMatchersManagementContextConfiguration.class)) - .withUserConfiguration(TestMvcConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(RequestMatcherProvider.class)); + .withConfiguration(AutoConfigurations.of(SecurityRequestMatchersManagementContextConfiguration.class)) + .withUserConfiguration(TestMvcConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(RequestMatcherProvider.class)); } @Test void configurationConditionalOnRequestMatcherClass() { this.contextRunner - .withClassLoader( - new FilteredClassLoader("org.springframework.security.web.util.matcher.RequestMatcher")) - .run((context) -> assertThat(context).doesNotHaveBean(RequestMatcherProvider.class)); + .withClassLoader(new FilteredClassLoader("org.springframework.security.web.util.matcher.RequestMatcher")) + .run((context) -> assertThat(context).doesNotHaveBean(RequestMatcherProvider.class)); } @Test @@ -70,39 +69,39 @@ class SecurityRequestMatchersManagementContextConfigurationTests { @Test void registersRequestMatcherForJerseyProviderIfJerseyPresentAndMvcAbsent() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) - .withUserConfiguration(TestJerseyConfiguration.class).run((context) -> { - AntPathRequestMatcherProvider matcherProvider = context - .getBean(AntPathRequestMatcherProvider.class); - RequestMatcher requestMatcher = matcherProvider.getRequestMatcher("/example"); - assertThat(requestMatcher).extracting("pattern").isEqualTo("/admin/example"); - }); + .withUserConfiguration(TestJerseyConfiguration.class) + .run((context) -> { + AntPathRequestMatcherProvider matcherProvider = context.getBean(AntPathRequestMatcherProvider.class); + RequestMatcher requestMatcher = matcherProvider.getRequestMatcher("/example"); + assertThat(requestMatcher).extracting("pattern").isEqualTo("/admin/example"); + }); } @Test void mvcRequestMatcherProviderConditionalOnDispatcherServletClass() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) - .run((context) -> assertThat(context).doesNotHaveBean(AntPathRequestMatcherProvider.class)); + .run((context) -> assertThat(context).doesNotHaveBean(AntPathRequestMatcherProvider.class)); } @Test void mvcRequestMatcherProviderConditionalOnDispatcherServletPathBean() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SecurityRequestMatchersManagementContextConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(AntPathRequestMatcherProvider.class)); + .withConfiguration(AutoConfigurations.of(SecurityRequestMatchersManagementContextConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(AntPathRequestMatcherProvider.class)); } @Test void jerseyRequestMatcherProviderConditionalOnResourceConfigClass() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.glassfish.jersey.server.ResourceConfig")) - .run((context) -> assertThat(context).doesNotHaveBean(AntPathRequestMatcherProvider.class)); + .run((context) -> assertThat(context).doesNotHaveBean(AntPathRequestMatcherProvider.class)); } @Test void jerseyRequestMatcherProviderConditionalOnJerseyApplicationPathBean() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SecurityRequestMatchersManagementContextConfiguration.class)) - .withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) - .run((context) -> assertThat(context).doesNotHaveBean(AntPathRequestMatcherProvider.class)); + .withConfiguration(AutoConfigurations.of(SecurityRequestMatchersManagementContextConfiguration.class)) + .withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) + .run((context) -> assertThat(context).doesNotHaveBean(AntPathRequestMatcherProvider.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfigurationTests.java index 6f30148711..576fe6bbae 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,13 +36,13 @@ import static org.mockito.Mockito.mock; class SessionsEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SessionsEndpointAutoConfiguration.class)) - .withUserConfiguration(SessionConfiguration.class); + .withConfiguration(AutoConfigurations.of(SessionsEndpointAutoConfiguration.class)) + .withUserConfiguration(SessionConfiguration.class); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=sessions") - .run((context) -> assertThat(context).hasSingleBean(SessionsEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(SessionsEndpoint.class)); } @Test @@ -53,7 +53,7 @@ class SessionsEndpointAutoConfigurationTests { @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.sessions.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(SessionsEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(SessionsEndpoint.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/solr/SolrHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/solr/SolrHealthContributorAutoConfigurationTests.java index 562568ea59..0104bc6d2a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/solr/SolrHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/solr/SolrHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,8 @@ import static org.assertj.core.api.Assertions.assertThat; class SolrHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SolrAutoConfiguration.class, - SolrHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SolrAutoConfiguration.class, + SolrHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { @@ -45,7 +45,7 @@ class SolrHealthContributorAutoConfigurationTests { @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.solr.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(SolrHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(SolrHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/startup/StartupEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/startup/StartupEndpointAutoConfigurationTests.java index 163731311d..a7a15a1ccc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/startup/StartupEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/startup/StartupEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat; class StartupEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(StartupEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(StartupEndpointAutoConfiguration.class)); @Test void runShouldNotHaveStartupEndpoint() { @@ -44,7 +44,7 @@ class StartupEndpointAutoConfigurationTests { @Test void runWhenMissingAppStartupShouldNotHaveStartupEndpoint() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=startup") - .run((context) -> assertThat(context).doesNotHaveBean(StartupEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(StartupEndpoint.class)); } @Test @@ -54,8 +54,8 @@ class StartupEndpointAutoConfigurationTests { context.setApplicationStartup(new BufferingApplicationStartup(1)); return context; }).withConfiguration(AutoConfigurations.of(StartupEndpointAutoConfiguration.class)) - .withPropertyValues("management.endpoints.web.exposure.include=startup") - .run((context) -> assertThat(context).hasSingleBean(StartupEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=startup") + .run((context) -> assertThat(context).hasSingleBean(StartupEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthContributorAutoConfigurationTests.java index 1e5ac554b8..b71c7a2c72 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,8 @@ import static org.assertj.core.api.Assertions.assertThat; class DiskSpaceHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DiskSpaceHealthContributorAutoConfiguration.class, - HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(DiskSpaceHealthContributorAutoConfiguration.class, + HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { @@ -46,8 +46,9 @@ class DiskSpaceHealthContributorAutoConfigurationTests { @Test void thresholdMustBePositive() { this.contextRunner.withPropertyValues("management.health.diskspace.threshold=-10MB") - .run((context) -> assertThat(context).hasFailed().getFailure() - .hasMessageContaining("Failed to bind properties under 'management.health.diskspace'")); + .run((context) -> assertThat(context).hasFailed() + .getFailure() + .hasMessageContaining("Failed to bind properties under 'management.health.diskspace'")); } @Test @@ -62,13 +63,13 @@ class DiskSpaceHealthContributorAutoConfigurationTests { @Test void runWhenPathDoesNotExistShouldCreateIndicator() { this.contextRunner.withPropertyValues("management.health.diskspace.path=does/not/exist") - .run((context) -> assertThat(context).hasSingleBean(DiskSpaceHealthIndicator.class)); + .run((context) -> assertThat(context).hasSingleBean(DiskSpaceHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.diskspace.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(DiskSpaceHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(DiskSpaceHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextConfigurationTests.java index 53a99bd89f..d9e867e387 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ class ManagementContextConfigurationTests { @Test void proxyBeanMethodsIsEnabledByDefault() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(DefaultManagementContextConfiguration.class, Configuration.class); + .getMergedAnnotationAttributes(DefaultManagementContextConfiguration.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(true); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyChildManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyChildManagementContextConfigurationTests.java index cca272741d..92a0704cff 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyChildManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyChildManagementContextConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,20 +44,20 @@ import static org.mockito.Mockito.mock; class JerseyChildManagementContextConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withUserConfiguration(JerseyChildManagementContextConfiguration.class); + .withUserConfiguration(JerseyChildManagementContextConfiguration.class); @Test void autoConfigurationIsConditionalOnServletWebApplication() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test void autoConfigurationIsConditionalOnClassResourceConfig() { this.contextRunner.withClassLoader(new FilteredClassLoader(ResourceConfig.class)) - .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test @@ -88,7 +88,7 @@ class JerseyChildManagementContextConfigurationTests { assertThat(context).hasSingleBean(ResourceConfig.class); ResourceConfig config = context.getBean(ResourceConfig.class); ManagementContextResourceConfigCustomizer customizer = context - .getBean(ManagementContextResourceConfigCustomizer.class); + .getBean(ManagementContextResourceConfigCustomizer.class); then(customizer).should().customize(config); }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfigurationTests.java index e8c8120d35..a9f28fd75e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,20 +44,20 @@ import static org.mockito.Mockito.mock; class JerseySameManagementContextConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); @Test void autoConfigurationIsConditionalOnServletWebApplication() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test void autoConfigurationIsConditionalOnClassResourceConfig() { this.contextRunner.withClassLoader(new FilteredClassLoader(ResourceConfig.class)) - .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test @@ -98,7 +98,7 @@ class JerseySameManagementContextConfigurationTests { assertThat(context).hasSingleBean(ResourceConfig.class); ResourceConfig config = context.getBean(ResourceConfig.class); ManagementContextResourceConfigCustomizer customizer = context - .getBean(ManagementContextResourceConfigCustomizer.class); + .getBean(ManagementContextResourceConfigCustomizer.class); then(customizer).should().customize(config); }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/mappings/MappingsEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/mappings/MappingsEndpointAutoConfigurationTests.java index 36f70d28a6..eec4f9671b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/mappings/MappingsEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/mappings/MappingsEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,30 +43,31 @@ class MappingsEndpointAutoConfigurationTests { @Test void whenEndpointIsUnavailableThenEndpointAndDescriptionProvidersAreNotCreated() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MappingsEndpointAutoConfiguration.class, - JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - WebMvcEndpointManagementContextConfiguration.class, PropertyPlaceholderAutoConfiguration.class)) - .run((context) -> { - assertThat(context).doesNotHaveBean(MappingsEndpoint.class); - assertThat(context).doesNotHaveBean(MappingDescriptionProvider.class); - }); + .withConfiguration(AutoConfigurations.of(MappingsEndpointAutoConfiguration.class, + JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + WebMvcEndpointManagementContextConfiguration.class, PropertyPlaceholderAutoConfiguration.class)) + .run((context) -> { + assertThat(context).doesNotHaveBean(MappingsEndpoint.class); + assertThat(context).doesNotHaveBean(MappingDescriptionProvider.class); + }); } @Test void whenEndpointIsAvailableThenEndpointAndDescriptionProvidersAreCreated() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MappingsEndpointAutoConfiguration.class, - JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - WebMvcEndpointManagementContextConfiguration.class, PropertyPlaceholderAutoConfiguration.class)) - .withPropertyValues("management.endpoints.web.exposure.include=mappings").run((context) -> { - assertThat(context).hasSingleBean(MappingsEndpoint.class); - assertThat(context.getBeansOfType(MappingDescriptionProvider.class)).hasSize(3); - }); + .withConfiguration(AutoConfigurations.of(MappingsEndpointAutoConfiguration.class, + JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + WebMvcEndpointManagementContextConfiguration.class, PropertyPlaceholderAutoConfiguration.class)) + .withPropertyValues("management.endpoints.web.exposure.include=mappings") + .run((context) -> { + assertThat(context).hasSingleBean(MappingsEndpoint.class); + assertThat(context.getBeansOfType(MappingDescriptionProvider.class)).hasSize(3); + }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementChildContextConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementChildContextConfigurationIntegrationTests.java index e785ca9d56..3f656f517c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementChildContextConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementChildContextConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,14 +57,13 @@ class ReactiveManagementChildContextConfigurationIntegrationTests { private final ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, - ReactiveWebServerFactoryAutoConfiguration.class, - ReactiveManagementContextAutoConfiguration.class, WebEndpointAutoConfiguration.class, - EndpointAutoConfiguration.class, HttpHandlerAutoConfiguration.class, - WebFluxAutoConfiguration.class)) - .withUserConfiguration(SucceedingEndpoint.class) - .withInitializer(new ServerPortInfoApplicationContextInitializer()).withPropertyValues( - "server.port=0", "management.server.port=0", "management.endpoints.web.exposure.include=*"); + .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, + ReactiveWebServerFactoryAutoConfiguration.class, ReactiveManagementContextAutoConfiguration.class, + WebEndpointAutoConfiguration.class, EndpointAutoConfiguration.class, HttpHandlerAutoConfiguration.class, + WebFluxAutoConfiguration.class)) + .withUserConfiguration(SucceedingEndpoint.class) + .withInitializer(new ServerPortInfoApplicationContextInitializer()) + .withPropertyValues("server.port=0", "management.server.port=0", "management.endpoints.web.exposure.include=*"); @TempDir Path temp; @@ -72,8 +71,11 @@ class ReactiveManagementChildContextConfigurationIntegrationTests { @Test void endpointsAreBeneathActuatorByDefault() { this.runner.withPropertyValues("management.server.port:0").run(withWebTestClient((client) -> { - String body = client.get().uri("actuator/success").accept(MediaType.APPLICATION_JSON) - .exchangeToMono((response) -> response.bodyToMono(String.class)).block(); + String body = client.get() + .uri("actuator/success") + .accept(MediaType.APPLICATION_JSON) + .exchangeToMono((response) -> response.bodyToMono(String.class)) + .block(); assertThat(body).isEqualTo("Success"); })); } @@ -81,23 +83,26 @@ class ReactiveManagementChildContextConfigurationIntegrationTests { @Test void whenManagementServerBasePathIsConfiguredThenEndpointsAreBeneathThatPath() { this.runner.withPropertyValues("management.server.port:0", "management.server.base-path:/manage") - .run(withWebTestClient((client) -> { - String body = client.get().uri("manage/actuator/success").accept(MediaType.APPLICATION_JSON) - .exchangeToMono((response) -> response.bodyToMono(String.class)).block(); - assertThat(body).isEqualTo("Success"); - })); + .run(withWebTestClient((client) -> { + String body = client.get() + .uri("manage/actuator/success") + .accept(MediaType.APPLICATION_JSON) + .exchangeToMono((response) -> response.bodyToMono(String.class)) + .block(); + assertThat(body).isEqualTo("Success"); + })); } @Test // gh-32941 void whenManagementServerPortLoadedFromConfigTree() { this.runner.withInitializer(this::addConfigTreePropertySource) - .run((context) -> assertThat(context).hasNotFailed()); + .run((context) -> assertThat(context).hasNotFailed()); } private void addConfigTreePropertySource(ConfigurableApplicationContext applicationContext) { try { - applicationContext.getEnvironment().setConversionService( - (ConfigurableConversionService) ApplicationConversionService.getSharedInstance()); + applicationContext.getEnvironment() + .setConversionService((ConfigurableConversionService) ApplicationConversionService.getSharedInstance()); Path configtree = this.temp.resolve("configtree"); Path file = configtree.resolve("management/server/port"); file.toFile().getParentFile().mkdirs(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactoryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactoryTests.java index 2d5aeee541..318391ea51 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,7 @@ class ReactiveManagementContextFactoryTests { this.parent.register(ParentConfiguration.class); this.parent.refresh(); AnnotationConfigReactiveWebServerApplicationContext childContext = (AnnotationConfigReactiveWebServerApplicationContext) this.factory - .createManagementContext(this.parent, TestConfiguration1.class, TestConfiguration2.class); + .createManagementContext(this.parent, TestConfiguration1.class, TestConfiguration2.class); childContext.refresh(); assertThat(childContext.getBean(TestConfiguration1.class)).isNotNull(); assertThat(childContext.getBean(TestConfiguration2.class)).isNotNull(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfigurationTests.java index 6f920fe9ff..1d4e7c7319 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,25 +48,24 @@ class ManagementContextAutoConfigurationTests { void childManagementContextShouldStartForEmbeddedServer(CapturedOutput output) { WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, WebEndpointAutoConfiguration.class, - EndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, + WebEndpointAutoConfiguration.class, EndpointAutoConfiguration.class)); contextRunner.withPropertyValues("server.port=0", "management.server.port=0") - .run((context) -> assertThat(output).satisfies(numberOfOccurrences("Tomcat started on port", 2))); + .run((context) -> assertThat(output).satisfies(numberOfOccurrences("Tomcat started on port", 2))); } @Test void givenSamePortManagementServerWhenManagementServerAddressIsConfiguredThenContextRefreshFails() { WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, WebEndpointAutoConfiguration.class, - EndpointAutoConfiguration.class, DispatcherServletAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, + WebEndpointAutoConfiguration.class, EndpointAutoConfiguration.class, + DispatcherServletAutoConfiguration.class)); contextRunner.withPropertyValues("server.port=0", "management.server.address=127.0.0.1") - .run((context) -> assertThat(context).getFailure() - .hasMessageStartingWith("Management-specific server address cannot be configured")); + .run((context) -> assertThat(context).getFailure() + .hasMessageStartingWith("Management-specific server address cannot be configured")); } private Consumer numberOfOccurrences(String substring, int expectedCount) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelectorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelectorTests.java index 6da00e7953..c1892a0169 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelectorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,33 +43,35 @@ class ManagementContextConfigurationImportSelectorTests { @Test void selectImportsShouldOrderResult() { String[] imports = new TestManagementContextConfigurationsImportSelector(C.class, A.class, D.class, B.class) - .selectImports(AnnotationMetadata.introspect(EnableChildContext.class)); + .selectImports(AnnotationMetadata.introspect(EnableChildContext.class)); assertThat(imports).containsExactly(A.class.getName(), B.class.getName(), C.class.getName(), D.class.getName()); } @Test void selectImportsFiltersChildOnlyConfigurationWhenUsingSameContext() { String[] imports = new TestManagementContextConfigurationsImportSelector(ChildOnly.class, SameOnly.class, - A.class).selectImports(AnnotationMetadata.introspect(EnableSameContext.class)); + A.class) + .selectImports(AnnotationMetadata.introspect(EnableSameContext.class)); assertThat(imports).containsExactlyInAnyOrder(SameOnly.class.getName(), A.class.getName()); } @Test void selectImportsFiltersSameOnlyConfigurationWhenUsingChildContext() { String[] imports = new TestManagementContextConfigurationsImportSelector(ChildOnly.class, SameOnly.class, - A.class).selectImports(AnnotationMetadata.introspect(EnableChildContext.class)); + A.class) + .selectImports(AnnotationMetadata.introspect(EnableChildContext.class)); assertThat(imports).containsExactlyInAnyOrder(ChildOnly.class.getName(), A.class.getName()); } @Test void selectImportsLoadsFromResources() { String[] imports = new ManagementContextConfigurationImportSelector() - .selectImports(AnnotationMetadata.introspect(EnableChildContext.class)); + .selectImports(AnnotationMetadata.introspect(EnableChildContext.class)); Set expected = new HashSet<>(); ImportCandidates - .load(ManagementContextConfiguration.class, - ManagementContextConfigurationImportSelectorTests.class.getClassLoader()) - .forEach(expected::add); + .load(ManagementContextConfiguration.class, + ManagementContextConfigurationImportSelectorTests.class.getClassLoader()) + .forEach(expected::add); // Remove JerseySameManagementContextConfiguration, as it specifies // ManagementContextType.SAME and we asked for ManagementContextType.CHILD expected.remove( diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolverTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolverTests.java index f78843a96e..a84ceac2e1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolverTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ class CompositeHandlerExceptionResolverTests { void resolverShouldDelegateToOtherResolversInContext() { load(TestConfiguration.class); CompositeHandlerExceptionResolver resolver = (CompositeHandlerExceptionResolver) this.context - .getBean(DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME); + .getBean(DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME); ModelAndView resolved = resolver.resolveException(this.request, this.response, null, new HttpRequestMethodNotSupportedException("POST")); assertThat(resolved.getViewName()).isEqualTo("test-view"); @@ -62,7 +62,7 @@ class CompositeHandlerExceptionResolverTests { void resolverShouldAddDefaultResolverIfNonePresent() { load(BaseConfiguration.class); CompositeHandlerExceptionResolver resolver = (CompositeHandlerExceptionResolver) this.context - .getBean(DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME); + .getBean(DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME); HttpRequestMethodNotSupportedException exception = new HttpRequestMethodNotSupportedException("POST"); ModelAndView resolved = resolver.resolveException(this.request, this.response, null, exception); assertThat(resolved).isNotNull(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/MockServletWebServerFactory.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/MockServletWebServerFactory.java index 20325894bf..2ab77028ca 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/MockServletWebServerFactory.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/MockServletWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,8 +65,9 @@ public class MockServletWebServerFactory extends AbstractServletWebServerFactory implements WebServer { MockServletWebServer(ServletContextInitializer[] initializers, int port) { - super(Arrays.stream(initializers).map((initializer) -> (Initializer) initializer::onStartup) - .toArray(Initializer[]::new), port); + super(Arrays.stream(initializers) + .map((initializer) -> (Initializer) initializer::onStartup) + .toArray(Initializer[]::new), port); } @Override diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationIntegrationTests.java index 4aa64c4fc8..e3d3dd8154 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,17 +72,15 @@ class WebMvcEndpointChildContextConfigurationIntegrationTests { private final WebApplicationContextRunner runner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, WebEndpointAutoConfiguration.class, - EndpointAutoConfiguration.class, DispatcherServletAutoConfiguration.class, - ErrorMvcAutoConfiguration.class)) - .withUserConfiguration(SucceedingEndpoint.class, FailingEndpoint.class, - FailingControllerEndpoint.class) - .withInitializer(new ServerPortInfoApplicationContextInitializer()) - .withPropertyValues("server.port=0", "management.server.port=0", - "management.endpoints.web.exposure.include=*", "server.error.include-exception=true", - "server.error.include-message=always", "server.error.include-binding-errors=always"); + .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, + WebEndpointAutoConfiguration.class, EndpointAutoConfiguration.class, + DispatcherServletAutoConfiguration.class, ErrorMvcAutoConfiguration.class)) + .withUserConfiguration(SucceedingEndpoint.class, FailingEndpoint.class, FailingControllerEndpoint.class) + .withInitializer(new ServerPortInfoApplicationContextInitializer()) + .withPropertyValues("server.port=0", "management.server.port=0", "management.endpoints.web.exposure.include=*", + "server.error.include-exception=true", "server.error.include-message=always", + "server.error.include-binding-errors=always"); @TempDir Path temp; @@ -90,8 +88,11 @@ class WebMvcEndpointChildContextConfigurationIntegrationTests { @Test // gh-17938 void errorEndpointIsUsedWithEndpoint() { this.runner.run(withWebTestClient((client) -> { - Map body = client.get().uri("actuator/fail").accept(MediaType.APPLICATION_JSON) - .exchangeToMono(toResponseBody()).block(); + Map body = client.get() + .uri("actuator/fail") + .accept(MediaType.APPLICATION_JSON) + .exchangeToMono(toResponseBody()) + .block(); assertThat(body).hasEntrySatisfying("exception", (value) -> assertThat(value).asString().contains("IllegalStateException")); assertThat(body).hasEntrySatisfying("message", @@ -102,21 +103,27 @@ class WebMvcEndpointChildContextConfigurationIntegrationTests { @Test void errorPageAndErrorControllerIncludeDetails() { this.runner.withPropertyValues("server.error.include-stacktrace=always", "server.error.include-message=always") - .run(withWebTestClient((client) -> { - Map body = client.get().uri("actuator/fail").accept(MediaType.APPLICATION_JSON) - .exchangeToMono(toResponseBody()).block(); - assertThat(body).hasEntrySatisfying("message", - (value) -> assertThat(value).asString().contains("Epic Fail")); - assertThat(body).hasEntrySatisfying("trace", (value) -> assertThat(value).asString() - .contains("java.lang.IllegalStateException: Epic Fail")); - })); + .run(withWebTestClient((client) -> { + Map body = client.get() + .uri("actuator/fail") + .accept(MediaType.APPLICATION_JSON) + .exchangeToMono(toResponseBody()) + .block(); + assertThat(body).hasEntrySatisfying("message", + (value) -> assertThat(value).asString().contains("Epic Fail")); + assertThat(body).hasEntrySatisfying("trace", + (value) -> assertThat(value).asString().contains("java.lang.IllegalStateException: Epic Fail")); + })); } @Test void errorEndpointIsUsedWithRestControllerEndpoint() { this.runner.run(withWebTestClient((client) -> { - Map body = client.get().uri("actuator/failController").accept(MediaType.APPLICATION_JSON) - .exchangeToMono(toResponseBody()).block(); + Map body = client.get() + .uri("actuator/failController") + .accept(MediaType.APPLICATION_JSON) + .exchangeToMono(toResponseBody()) + .block(); assertThat(body).hasEntrySatisfying("exception", (value) -> assertThat(value).asString().contains("IllegalStateException")); assertThat(body).hasEntrySatisfying("message", @@ -127,9 +134,12 @@ class WebMvcEndpointChildContextConfigurationIntegrationTests { @Test void errorEndpointIsUsedWithRestControllerEndpointOnBindingError() { this.runner.run(withWebTestClient((client) -> { - Map body = client.post().uri("actuator/failController") - .bodyValue(Collections.singletonMap("content", "")).accept(MediaType.APPLICATION_JSON) - .exchangeToMono(toResponseBody()).block(); + Map body = client.post() + .uri("actuator/failController") + .bodyValue(Collections.singletonMap("content", "")) + .accept(MediaType.APPLICATION_JSON) + .exchangeToMono(toResponseBody()) + .block(); assertThat(body).hasEntrySatisfying("exception", (value) -> assertThat(value).asString().contains("MethodArgumentNotValidException")); assertThat(body).hasEntrySatisfying("message", @@ -141,8 +151,11 @@ class WebMvcEndpointChildContextConfigurationIntegrationTests { @Test void whenManagementServerBasePathIsConfiguredThenEndpointsAreBeneathThatPath() { this.runner.withPropertyValues("management.server.base-path:/manage").run(withWebTestClient((client) -> { - String body = client.get().uri("manage/actuator/success").accept(MediaType.APPLICATION_JSON) - .exchangeToMono((response) -> response.bodyToMono(String.class)).block(); + String body = client.get() + .uri("manage/actuator/success") + .accept(MediaType.APPLICATION_JSON) + .exchangeToMono((response) -> response.bodyToMono(String.class)) + .block(); assertThat(body).isEqualTo("Success"); })); } @@ -150,13 +163,13 @@ class WebMvcEndpointChildContextConfigurationIntegrationTests { @Test // gh-32941 void whenManagementServerPortLoadedFromConfigTree() { this.runner.withInitializer(this::addConfigTreePropertySource) - .run((context) -> assertThat(context).hasNotFailed()); + .run((context) -> assertThat(context).hasNotFailed()); } private void addConfigTreePropertySource(ConfigurableApplicationContext applicationContext) { try { - applicationContext.getEnvironment().setConversionService( - (ConfigurableConversionService) ApplicationConversionService.getSharedInstance()); + applicationContext.getEnvironment() + .setConversionService((ConfigurableConversionService) ApplicationConversionService.getSharedInstance()); Path configtree = this.temp.resolve("configtree"); Path file = configtree.resolve("management/server/port"); file.toFile().getParentFile().mkdirs(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationTests.java index a4e8a30864..0eaf303edf 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,36 +36,37 @@ import static org.assertj.core.api.Assertions.assertThat; class WebMvcEndpointChildContextConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withAllowBeanDefinitionOverriding(true); + .withAllowBeanDefinitionOverriding(true); @Test void contextShouldConfigureRequestContextFilter() { this.contextRunner.withUserConfiguration(WebMvcEndpointChildContextConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(OrderedRequestContextFilter.class)); + .run((context) -> assertThat(context).hasSingleBean(OrderedRequestContextFilter.class)); } @Test void contextShouldNotConfigureRequestContextFilterWhenPresent() { this.contextRunner.withUserConfiguration(ExistingConfig.class, WebMvcEndpointChildContextConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(RequestContextFilter.class); - assertThat(context).hasBean("testRequestContextFilter"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(RequestContextFilter.class); + assertThat(context).hasBean("testRequestContextFilter"); + }); } @Test void contextShouldNotConfigureRequestContextFilterWhenRequestContextListenerPresent() { - this.contextRunner.withUserConfiguration(RequestContextListenerConfig.class, - WebMvcEndpointChildContextConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(RequestContextListener.class); - assertThat(context).doesNotHaveBean(OrderedRequestContextFilter.class); - }); + this.contextRunner + .withUserConfiguration(RequestContextListenerConfig.class, WebMvcEndpointChildContextConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(RequestContextListener.class); + assertThat(context).doesNotHaveBean(OrderedRequestContextFilter.class); + }); } @Test void contextShouldConfigureDispatcherServletPathWithRootPath() { this.contextRunner.withUserConfiguration(WebMvcEndpointChildContextConfiguration.class) - .run((context) -> assertThat(context.getBean(DispatcherServletPath.class).getPath()).isEqualTo("/")); + .run((context) -> assertThat(context.getBean(DispatcherServletPath.class).getPath()).isEqualTo("/")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceAutoConfigurationTests.java index bef1caa34d..b9bd9de941 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ import static org.assertj.core.api.Assertions.assertThat; class HttpTraceAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpTraceAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HttpTraceAutoConfiguration.class)); @Test void autoConfigurationIsDisabledByDefault() { @@ -67,44 +67,48 @@ class HttpTraceAutoConfigurationTests { @Test void usesUserProvidedTracer() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) - .withUserConfiguration(CustomTracerConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(HttpExchangeTracer.class); - assertThat(context.getBean(HttpExchangeTracer.class)).isInstanceOf(CustomHttpExchangeTracer.class); - }); + .withUserConfiguration(CustomTracerConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(HttpExchangeTracer.class); + assertThat(context.getBean(HttpExchangeTracer.class)).isInstanceOf(CustomHttpExchangeTracer.class); + }); } @Test void usesUserProvidedWebFilterWhenReactiveContext() { new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpTraceAutoConfiguration.class)) - .withUserConfiguration(HttpTraceRepositoryConfiguration.class) - .withUserConfiguration(CustomWebFilterConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(HttpTraceWebFilter.class); - assertThat(context.getBean(HttpTraceWebFilter.class)).isInstanceOf(CustomHttpTraceWebFilter.class); - }); + .withConfiguration(AutoConfigurations.of(HttpTraceAutoConfiguration.class)) + .withUserConfiguration(HttpTraceRepositoryConfiguration.class) + .withUserConfiguration(CustomWebFilterConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(HttpTraceWebFilter.class); + assertThat(context.getBean(HttpTraceWebFilter.class)).isInstanceOf(CustomHttpTraceWebFilter.class); + }); } @Test void configuresServletFilter() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(HttpTraceFilter.class)); + .run((context) -> assertThat(context).hasSingleBean(HttpTraceFilter.class)); } @Test void usesUserProvidedServletFilter() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) - .withUserConfiguration(CustomFilterConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(HttpTraceFilter.class); - assertThat(context.getBean(HttpTraceFilter.class)).isInstanceOf(CustomHttpTraceFilter.class); - }); + .withUserConfiguration(CustomFilterConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(HttpTraceFilter.class); + assertThat(context.getBean(HttpTraceFilter.class)).isInstanceOf(CustomHttpTraceFilter.class); + }); } @Test void backsOffWhenDisabled() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) - .withPropertyValues("management.trace.http.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(InMemoryHttpTraceRepository.class) - .doesNotHaveBean(HttpExchangeTracer.class).doesNotHaveBean(HttpTraceFilter.class)); + .withPropertyValues("management.trace.http.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(InMemoryHttpTraceRepository.class) + .doesNotHaveBean(HttpExchangeTracer.class) + .doesNotHaveBean(HttpTraceFilter.class)); } static class CustomHttpTraceRepository implements HttpTraceRepository { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceEndpointAutoConfigurationTests.java index 7fc77d2f4d..39d0dab708 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,28 +43,28 @@ class HttpTraceEndpointAutoConfigurationTests { @Test void runWhenRepositoryBeanAvailableShouldHaveEndpointBean() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=httptrace") - .run((context) -> assertThat(context).hasSingleBean(HttpTraceEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=httptrace") + .run((context) -> assertThat(context).hasSingleBean(HttpTraceEndpoint.class)); } @Test void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(HttpTraceEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(HttpTraceEndpoint.class)); } @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=httptrace") - .withPropertyValues("management.endpoint.httptrace.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(HttpTraceEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=httptrace") + .withPropertyValues("management.endpoint.httptrace.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(HttpTraceEndpoint.class)); } @Test void endpointBacksOffWhenRepositoryIsNotAvailable() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=httptrace") - .run((context) -> assertThat(context).doesNotHaveBean(HttpTraceEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(HttpTraceEndpoint.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicator.java index 2ce4a058b2..386da31a9b 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ public class RabbitHealthIndicator extends AbstractHealthIndicator { private String getVersion() { return this.rabbitTemplate - .execute((channel) -> channel.getConnection().getServerProperties().get("version").toString()); + .execute((channel) -> channel.getConnection().getServerProperties().get("version").toString()); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CachesEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CachesEndpoint.java index f4c9911c58..5f1ebdd6cd 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CachesEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CachesEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -109,16 +109,22 @@ public class CachesEndpoint { private List getCacheEntries(Predicate cacheNamePredicate, Predicate cacheManagerNamePredicate) { - return this.cacheManagers.keySet().stream().filter(cacheManagerNamePredicate) - .flatMap((cacheManagerName) -> getCacheEntries(cacheManagerName, cacheNamePredicate).stream()) - .collect(Collectors.toList()); + return this.cacheManagers.keySet() + .stream() + .filter(cacheManagerNamePredicate) + .flatMap((cacheManagerName) -> getCacheEntries(cacheManagerName, cacheNamePredicate).stream()) + .collect(Collectors.toList()); } private List getCacheEntries(String cacheManagerName, Predicate cacheNamePredicate) { CacheManager cacheManager = this.cacheManagers.get(cacheManagerName); - return cacheManager.getCacheNames().stream().filter(cacheNamePredicate).map(cacheManager::getCache) - .filter(Objects::nonNull).map((cache) -> new CacheEntry(cache, cacheManagerName)) - .collect(Collectors.toList()); + return cacheManager.getCacheNames() + .stream() + .filter(cacheNamePredicate) + .map(cacheManager::getCache) + .filter(Objects::nonNull) + .map((cache) -> new CacheEntry(cache, cacheManagerName)) + .collect(Collectors.toList()); } private CacheEntry extractUniqueCacheEntry(String cache, List entries) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/ShutdownEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/ShutdownEndpoint.java index 2588da2a73..1ac66f8b97 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/ShutdownEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/ShutdownEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,10 +38,10 @@ import org.springframework.context.ConfigurableApplicationContext; public class ShutdownEndpoint implements ApplicationContextAware { private static final Map NO_CONTEXT_MESSAGE = Collections - .unmodifiableMap(Collections.singletonMap("message", "No context to shutdown.")); + .unmodifiableMap(Collections.singletonMap("message", "No context to shutdown.")); private static final Map SHUTDOWN_MESSAGE = Collections - .unmodifiableMap(Collections.singletonMap("message", "Shutting down, bye...")); + .unmodifiableMap(Collections.singletonMap("message", "Shutting down, bye...")); private ConfigurableApplicationContext context; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpoint.java index 00df14059d..ee9a1932b1 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -201,8 +201,8 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext private void applyConfigurationPropertiesFilter(JsonMapper.Builder builder) { builder.annotationIntrospector(new ConfigurationPropertiesAnnotationIntrospector()); - builder.filterProvider( - new SimpleFilterProvider().setDefaultFilter(new ConfigurationPropertiesPropertyFilter())); + builder + .filterProvider(new SimpleFilterProvider().setDefaultFilter(new ConfigurationPropertiesPropertyFilter())); } /** @@ -211,16 +211,17 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext */ private void applySerializationModifier(JsonMapper.Builder builder) { SerializerFactory factory = BeanSerializerFactory.instance - .withSerializerModifier(new GenericSerializerModifier()); + .withSerializerModifier(new GenericSerializerModifier()); builder.serializerFactory(factory); } private ContextConfigurationProperties describeBeans(ObjectMapper mapper, ApplicationContext context, Predicate beanFilterPredicate) { Map beans = ConfigurationPropertiesBean.getAll(context); - Map descriptors = beans.values().stream() - .filter(beanFilterPredicate) - .collect(Collectors.toMap(ConfigurationPropertiesBean::getName, (bean) -> describeBean(mapper, bean))); + Map descriptors = beans.values() + .stream() + .filter(beanFilterPredicate) + .collect(Collectors.toMap(ConfigurationPropertiesBean::getName, (bean) -> describeBean(mapper, bean))); return new ContextConfigurationProperties(descriptors, (context.getParent() != null) ? context.getParent().getId() : null); } @@ -517,9 +518,10 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext names = new String[parameters.length]; } for (int i = 0; i < parameters.length; i++) { - String name = MergedAnnotations.from(parameters[i]).get(Name.class) - .getValue(MergedAnnotation.VALUE, String.class) - .orElse((names[i] != null) ? names[i] : parameters[i].getName()); + String name = MergedAnnotations.from(parameters[i]) + .get(Name.class) + .getValue(MergedAnnotation.VALUE, String.class) + .orElse((names[i] != null) ? names[i] : parameters[i].getName()); if (name.equals(writer.getName())) { return true; } @@ -570,8 +572,8 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext private Constructor findBindConstructor(Class type) { boolean classConstructorBinding = MergedAnnotations - .from(type, SearchStrategy.TYPE_HIERARCHY_AND_ENCLOSING_CLASSES) - .isPresent(ConstructorBinding.class); + .from(type, SearchStrategy.TYPE_HIERARCHY_AND_ENCLOSING_CLASSES) + .isPresent(ConstructorBinding.class); if (KotlinDetector.isKotlinPresent() && KotlinDetector.isKotlinType(type)) { Constructor constructor = BeanUtils.findPrimaryConstructor(type); if (constructor != null) { @@ -583,10 +585,11 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext private Constructor findBindConstructor(boolean classConstructorBinding, Constructor... candidates) { List> candidateConstructors = Arrays.stream(candidates) - .filter((constructor) -> constructor.getParameterCount() > 0).collect(Collectors.toList()); + .filter((constructor) -> constructor.getParameterCount() > 0) + .collect(Collectors.toList()); List> flaggedConstructors = candidateConstructors.stream() - .filter((candidate) -> MergedAnnotations.from(candidate).isPresent(ConstructorBinding.class)) - .collect(Collectors.toList()); + .filter((candidate) -> MergedAnnotations.from(candidate).isPresent(ConstructorBinding.class)) + .collect(Collectors.toList()); if (flaggedConstructors.size() == 1) { return flaggedConstructors.get(0); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebExtension.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebExtension.java index 8f3b5db261..b8b7e9d955 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebExtension.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,9 +42,11 @@ public class ConfigurationPropertiesReportEndpointWebExtension { public WebEndpointResponse configurationPropertiesWithPrefix( @Selector String prefix) { ApplicationConfigurationProperties configurationProperties = this.delegate - .configurationPropertiesWithPrefix(prefix); - boolean foundMatchingBeans = configurationProperties.getContexts().values().stream() - .anyMatch((context) -> !context.getBeans().isEmpty()); + .configurationPropertiesWithPrefix(prefix); + boolean foundMatchingBeans = configurationProperties.getContexts() + .values() + .stream() + .anyMatch((context) -> !context.getBeans().isEmpty()); return (foundMatchingBeans) ? new WebEndpointResponse<>(configurationProperties, WebEndpointResponse.STATUS_OK) : new WebEndpointResponse<>(WebEndpointResponse.STATUS_NOT_FOUND); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/couchbase/CouchbaseHealth.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/couchbase/CouchbaseHealth.java index 005921fd49..39f07d9242 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/couchbase/CouchbaseHealth.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/couchbase/CouchbaseHealth.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,13 @@ class CouchbaseHealth { void applyTo(Builder builder) { builder = isCouchbaseUp(this.diagnostics) ? builder.up() : builder.down(); builder.withDetail("sdk", this.diagnostics.sdk()); - builder.withDetail("endpoints", this.diagnostics.endpoints().values().stream().flatMap(Collection::stream) - .map(this::describe).collect(Collectors.toList())); + builder.withDetail("endpoints", + this.diagnostics.endpoints() + .values() + .stream() + .flatMap(Collection::stream) + .map(this::describe) + .collect(Collectors.toList())); } private boolean isCouchbaseUp(DiagnosticsResult diagnostics) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/Sanitizer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/Sanitizer.java index 02e3ac96bc..84f236c6ed 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/Sanitizer.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/Sanitizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,7 +56,7 @@ public class Sanitizer { Arrays.asList("uri", "uris", "url", "urls", "address", "addresses")); private static final Pattern URI_USERINFO_PATTERN = Pattern - .compile("^\\[?[A-Za-z][A-Za-z0-9\\+\\.\\-]+://.+:(.*)@.+$"); + .compile("^\\[?[A-Za-z][A-Za-z0-9\\+\\.\\-]+://.+:(.*)@.+$"); private Pattern[] keysToSanitize; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredEndpoint.java index 9c053d306d..91fa1fa403 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,7 +70,7 @@ public abstract class AbstractDiscoveredEndpoint extends Ab @Override public String toString() { ToStringCreator creator = new ToStringCreator(this).append("discoverer", this.discoverer.getClass().getName()) - .append("endpointBean", this.endpointBean.getClass().getName()); + .append("endpointBean", this.endpointBean.getClass().getName()); appendFields(creator); return creator.toString(); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredOperation.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredOperation.java index cfc7a0f184..6138b7e138 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredOperation.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredOperation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,7 +63,7 @@ public abstract class AbstractDiscoveredOperation implements Operation { @Override public String toString() { ToStringCreator creator = new ToStringCreator(this).append("operationMethod", this.operationMethod) - .append("invoker", this.invoker); + .append("invoker", this.invoker); appendFields(creator); return creator.toString(); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactory.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactory.java index aa6b1aff66..2e4836b3d3 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactory.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,14 +70,17 @@ abstract class DiscoveredOperationsFactory { Collection createOperations(EndpointId id, Object target) { return MethodIntrospector - .selectMethods(target.getClass(), (MetadataLookup) (method) -> createOperation(id, target, method)) - .values(); + .selectMethods(target.getClass(), (MetadataLookup) (method) -> createOperation(id, target, method)) + .values(); } private O createOperation(EndpointId endpointId, Object target, Method method) { - return OPERATION_TYPES.entrySet().stream() - .map((entry) -> createOperation(endpointId, target, method, entry.getKey(), entry.getValue())) - .filter(Objects::nonNull).findFirst().orElse(null); + return OPERATION_TYPES.entrySet() + .stream() + .map((entry) -> createOperation(endpointId, target, method, entry.getKey(), entry.getValue())) + .filter(Objects::nonNull) + .findFirst() + .orElse(null); } private O createOperation(EndpointId endpointId, Object target, Method method, OperationType operationType, diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java index a6091f31a9..b2b0410715 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -148,7 +148,7 @@ public abstract class EndpointDiscoverer, O exten private void addExtensionBeans(Collection endpointBeans) { Map byId = endpointBeans.stream() - .collect(Collectors.toMap(EndpointBean::getId, Function.identity())); + .collect(Collectors.toMap(EndpointBean::getId, Function.identity())); String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors(this.applicationContext, EndpointExtension.class); for (String beanName : beanNames) { @@ -190,8 +190,10 @@ public abstract class EndpointDiscoverer, O exten EndpointId id = endpointBean.getId(); addOperations(indexed, id, endpointBean.getBean(), false); if (endpointBean.getExtensions().size() > 1) { - String extensionBeans = endpointBean.getExtensions().stream().map(ExtensionBean::getBeanName) - .collect(Collectors.joining(", ")); + String extensionBeans = endpointBean.getExtensions() + .stream() + .map(ExtensionBean::getBeanName) + .collect(Collectors.joining(", ")); throw new IllegalStateException("Found multiple extensions for the endpoint bean " + endpointBean.getBeanName() + " (" + extensionBeans + ")"); } @@ -199,8 +201,11 @@ public abstract class EndpointDiscoverer, O exten addOperations(indexed, id, extensionBean.getBean(), true); } assertNoDuplicateOperations(endpointBean, indexed); - List operations = indexed.values().stream().map(this::getLast).filter(Objects::nonNull) - .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); + List operations = indexed.values() + .stream() + .map(this::getLast) + .filter(Objects::nonNull) + .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); return createEndpoint(endpointBean.getBean(), id, endpointBean.isEnabledByDefault(), operations); } @@ -223,12 +228,16 @@ public abstract class EndpointDiscoverer, O exten } private void assertNoDuplicateOperations(EndpointBean endpointBean, MultiValueMap indexed) { - List duplicates = indexed.entrySet().stream().filter((entry) -> entry.getValue().size() > 1) - .map(Map.Entry::getKey).collect(Collectors.toList()); + List duplicates = indexed.entrySet() + .stream() + .filter((entry) -> entry.getValue().size() > 1) + .map(Map.Entry::getKey) + .collect(Collectors.toList()); if (!duplicates.isEmpty()) { Set extensions = endpointBean.getExtensions(); - String extensionBeanNames = extensions.stream().map(ExtensionBean::getBeanName) - .collect(Collectors.joining(", ")); + String extensionBeanNames = extensions.stream() + .map(ExtensionBean::getBeanName) + .collect(Collectors.joining(", ")); throw new IllegalStateException("Unable to map duplicate endpoint operations: " + duplicates.toString() + " to " + endpointBean.getBeanName() + (extensions.isEmpty() ? "" : " (" + extensionBeanNames + ")")); @@ -297,8 +306,10 @@ public abstract class EndpointDiscoverer, O exten @SuppressWarnings("unchecked") private boolean isFilterMatch(EndpointFilter filter, E endpoint) { - return LambdaSafe.callback(EndpointFilter.class, filter, endpoint).withLogger(EndpointDiscoverer.class) - .invokeAnd((f) -> f.match(endpoint)).get(); + return LambdaSafe.callback(EndpointFilter.class, filter, endpoint) + .withLogger(EndpointDiscoverer.class) + .invokeAnd((f) -> f.match(endpoint)) + .get(); } private E getFilterEndpoint(EndpointBean endpointBean) { @@ -410,7 +421,7 @@ public abstract class EndpointDiscoverer, O exten EndpointBean(Environment environment, String beanName, Class beanType, Supplier beanSupplier) { MergedAnnotation annotation = MergedAnnotations.from(beanType, SearchStrategy.TYPE_HIERARCHY) - .get(Endpoint.class); + .get(Endpoint.class); String id = annotation.getString("id"); Assert.state(StringUtils.hasText(id), () -> "No @Endpoint id attribute specified for " + beanType.getName()); @@ -431,8 +442,10 @@ public abstract class EndpointDiscoverer, O exten } private Class getFilter(Class type) { - return MergedAnnotations.from(type, SearchStrategy.TYPE_HIERARCHY).get(FilteredEndpoint.class) - .getValue(MergedAnnotation.VALUE, Class.class).orElse(null); + return MergedAnnotations.from(type, SearchStrategy.TYPE_HIERARCHY) + .get(FilteredEndpoint.class) + .getValue(MergedAnnotation.VALUE, Class.class) + .orElse(null); } String getBeanName() { @@ -481,10 +494,12 @@ public abstract class EndpointDiscoverer, O exten this.beanType = beanType; this.beanSupplier = beanSupplier; MergedAnnotation extensionAnnotation = MergedAnnotations - .from(beanType, SearchStrategy.TYPE_HIERARCHY).get(EndpointExtension.class); + .from(beanType, SearchStrategy.TYPE_HIERARCHY) + .get(EndpointExtension.class); Class endpointType = extensionAnnotation.getClass("endpoint"); MergedAnnotation endpointAnnotation = MergedAnnotations - .from(endpointType, SearchStrategy.TYPE_HIERARCHY).get(Endpoint.class); + .from(endpointType, SearchStrategy.TYPE_HIERARCHY) + .get(Endpoint.class); Assert.state(endpointAnnotation.isPresent(), () -> "Extension " + endpointType.getName() + " does not specify an endpoint"); this.endpointId = EndpointId.of(environment, endpointAnnotation.getString("id")); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/FilteredEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/FilteredEndpoint.java index 53899dffa8..eda0604578 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/FilteredEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/FilteredEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,6 +39,7 @@ import org.springframework.boot.actuate.endpoint.EndpointFilter; * boolean enableByDefault() default true; * * } + * * @author Phillip Webb * @since 2.0.0 * @see DiscovererEndpointFilter diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvoker.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvoker.java index 5a277da4b7..7f8f3960b4 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvoker.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvoker.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -75,8 +75,10 @@ public class ReflectiveOperationInvoker implements OperationInvoker { } private void validateRequiredParameters(InvocationContext context) { - Set missing = this.operationMethod.getParameters().stream() - .filter((parameter) -> isMissing(context, parameter)).collect(Collectors.toSet()); + Set missing = this.operationMethod.getParameters() + .stream() + .filter((parameter) -> isMissing(context, parameter)) + .collect(Collectors.toSet()); if (!missing.isEmpty()) { throw new MissingParametersException(missing); } @@ -93,8 +95,10 @@ public class ReflectiveOperationInvoker implements OperationInvoker { } private Object[] resolveArguments(InvocationContext context) { - return this.operationMethod.getParameters().stream().map((parameter) -> resolveArgument(parameter, context)) - .toArray(); + return this.operationMethod.getParameters() + .stream() + .map((parameter) -> resolveArgument(parameter, context)) + .toArray(); } private Object resolveArgument(OperationParameter parameter, InvocationContext context) { @@ -108,8 +112,9 @@ public class ReflectiveOperationInvoker implements OperationInvoker { @Override public String toString() { - return new ToStringCreator(this).append("target", this.target).append("method", this.operationMethod) - .toString(); + return new ToStringCreator(this).append("target", this.target) + .append("method", this.operationMethod) + .toString(); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBean.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBean.java index 5bd2031ad7..fc6a95ad1f 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBean.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -115,8 +115,10 @@ public class EndpointMBean implements DynamicMBean { private Object invoke(JmxOperation operation, Object[] params) throws MBeanException, ReflectionException { try { - String[] parameterNames = operation.getParameters().stream().map(JmxOperationParameter::getName) - .toArray(String[]::new); + String[] parameterNames = operation.getParameters() + .stream() + .map(JmxOperationParameter::getName) + .toArray(String[]::new); Map arguments = getArguments(parameterNames, params); InvocationContext context = new InvocationContext(SecurityContext.NONE, arguments); Object result = operation.invoke(context); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapper.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapper.java index 39ff94db1f..235d78b9fc 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapper.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,8 @@ public class JacksonJmxOperationResponseMapper implements JmxOperationResponseMa public JacksonJmxOperationResponseMapper(ObjectMapper objectMapper) { this.objectMapper = (objectMapper != null) ? objectMapper : new ObjectMapper(); this.listType = this.objectMapper.getTypeFactory().constructParametricType(List.class, Object.class); - this.mapType = this.objectMapper.getTypeFactory().constructParametricType(Map.class, String.class, - Object.class); + this.mapType = this.objectMapper.getTypeFactory() + .constructParametricType(Map.class, String.class, Object.class); } @Override diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperation.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperation.java index 60750d1cd4..7c9f2b492a 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperation.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -124,8 +124,10 @@ class DiscoveredJmxOperation extends AbstractDiscoveredOperation implements JmxO @Override protected void appendFields(ToStringCreator creator) { - creator.append("name", this.name).append("outputType", this.outputType).append("description", this.description) - .append("parameters", this.parameters); + creator.append("name", this.name) + .append("outputType", this.outputType) + .append("description", this.description) + .append("parameters", this.parameters); } /** diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredWebOperation.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredWebOperation.java index aaa5726c33..65c4c376b8 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredWebOperation.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/DiscoveredWebOperation.java @@ -60,8 +60,11 @@ class DiscoveredWebOperation extends AbstractDiscoveredOperation implements WebO } private String getId(EndpointId endpointId, OperationMethod method) { - return endpointId + method.getParameters().stream().filter(this::hasSelector).map(this::dashName) - .collect(Collectors.joining()); + return endpointId + method.getParameters() + .stream() + .filter(this::hasSelector) + .map(this::dashName) + .collect(Collectors.joining()); } private boolean hasSelector(OperationParameter parameter) { @@ -93,8 +96,9 @@ class DiscoveredWebOperation extends AbstractDiscoveredOperation implements WebO @Override protected void appendFields(ToStringCreator creator) { - creator.append("id", this.id).append("blocking", this.blocking).append("requestPredicate", - this.requestPredicate); + creator.append("id", this.id) + .append("blocking", this.blocking) + .append("requestPredicate", this.requestPredicate); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/RequestPredicateFactory.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/RequestPredicateFactory.java index 623e02b3f3..badfac2add 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/RequestPredicateFactory.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/RequestPredicateFactory.java @@ -53,8 +53,10 @@ class RequestPredicateFactory { WebOperationRequestPredicate getRequestPredicate(String rootPath, DiscoveredOperationMethod operationMethod) { Method method = operationMethod.getMethod(); - OperationParameter[] selectorParameters = operationMethod.getParameters().stream().filter(this::hasSelector) - .toArray(OperationParameter[]::new); + OperationParameter[] selectorParameters = operationMethod.getParameters() + .stream() + .filter(this::hasSelector) + .toArray(OperationParameter[]::new); OperationParameter allRemainingPathSegmentsParameter = getAllRemainingPathSegmentsParameter(selectorParameters); String path = getPath(rootPath, selectorParameters, allRemainingPathSegmentsParameter != null); WebEndpointHttpMethod httpMethod = determineHttpMethod(operationMethod.getOperationType()); @@ -131,7 +133,7 @@ class RequestPredicateFactory { private boolean consumesRequestBody(Method method) { return Stream.of(method.getParameters()) - .anyMatch((parameter) -> parameter.getAnnotation(Selector.class) == null); + .anyMatch((parameter) -> parameter.getAnnotation(Selector.class) == null); } private WebEndpointHttpMethod determineHttpMethod(OperationType operationType) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/jersey/JerseyEndpointResourceFactory.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/jersey/JerseyEndpointResourceFactory.java index cf769a6ed2..e4db18ba27 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/jersey/JerseyEndpointResourceFactory.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/jersey/JerseyEndpointResourceFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -84,8 +84,10 @@ public class JerseyEndpointResourceFactory { Collection endpoints, EndpointMediaTypes endpointMediaTypes, EndpointLinksResolver linksResolver, boolean shouldRegisterLinks) { List resources = new ArrayList<>(); - endpoints.stream().flatMap((endpoint) -> endpoint.getOperations().stream()) - .map((operation) -> createResource(endpointMapping, operation)).forEach(resources::add); + endpoints.stream() + .flatMap((endpoint) -> endpoint.getOperations().stream()) + .map((operation) -> createResource(endpointMapping, operation)) + .forEach(resources::add); if (shouldRegisterLinks) { Resource resource = createEndpointLinksResource(endpointMapping.getPath(), endpointMediaTypes, linksResolver); @@ -108,21 +110,23 @@ public class JerseyEndpointResourceFactory { protected Resource getResource(EndpointMapping endpointMapping, WebOperation operation, WebOperationRequestPredicate requestPredicate, String path, WebServerNamespace serverNamespace, JerseyRemainingPathSegmentProvider remainingPathSegmentProvider) { - Builder resourceBuilder = Resource.builder().path(endpointMapping.getPath()) - .path(endpointMapping.createSubPath(path)); + Builder resourceBuilder = Resource.builder() + .path(endpointMapping.getPath()) + .path(endpointMapping.createSubPath(path)); resourceBuilder.addMethod(requestPredicate.getHttpMethod().name()) - .consumes(StringUtils.toStringArray(requestPredicate.getConsumes())) - .produces(StringUtils.toStringArray(requestPredicate.getProduces())) - .handledBy(new OperationInflector(operation, !requestPredicate.getConsumes().isEmpty(), serverNamespace, - remainingPathSegmentProvider)); + .consumes(StringUtils.toStringArray(requestPredicate.getConsumes())) + .produces(StringUtils.toStringArray(requestPredicate.getProduces())) + .handledBy(new OperationInflector(operation, !requestPredicate.getConsumes().isEmpty(), serverNamespace, + remainingPathSegmentProvider)); return resourceBuilder.build(); } private Resource createEndpointLinksResource(String endpointPath, EndpointMediaTypes endpointMediaTypes, EndpointLinksResolver linksResolver) { Builder resourceBuilder = Resource.builder().path(endpointPath); - resourceBuilder.addMethod("GET").produces(StringUtils.toStringArray(endpointMediaTypes.getProduced())) - .handledBy(new EndpointLinksInflector(linksResolver)); + resourceBuilder.addMethod("GET") + .produces(StringUtils.toStringArray(endpointMediaTypes.getProduced())) + .handledBy(new EndpointLinksInflector(linksResolver)); return resourceBuilder.build(); } @@ -172,7 +176,7 @@ public class JerseyEndpointResourceFactory { try { JerseySecurityContext securityContext = new JerseySecurityContext(data.getSecurityContext()); OperationArgumentResolver serverNamespaceArgumentResolver = OperationArgumentResolver - .of(WebServerNamespace.class, () -> this.serverNamespace); + .of(WebServerNamespace.class, () -> this.serverNamespace); InvocationContext invocationContext = new InvocationContext(securityContext, arguments, serverNamespaceArgumentResolver, new ProducibleOperationArgumentResolver(() -> data.getHeaders().get("Accept"))); @@ -193,7 +197,7 @@ public class JerseyEndpointResourceFactory { private Map extractPathParameters(ContainerRequestContext requestContext) { Map pathParameters = extract(requestContext.getUriInfo().getPathParameters()); String matchAllRemainingPathSegmentsVariable = this.operation.getRequestPredicate() - .getMatchAllRemainingPathSegmentsVariable(); + .getMatchAllRemainingPathSegmentsVariable(); if (matchAllRemainingPathSegmentsVariable != null) { String remainingPathSegments = getRemainingPathSegments(requestContext, pathParameters, matchAllRemainingPathSegmentsVariable); @@ -245,8 +249,9 @@ public class JerseyEndpointResourceFactory { } WebEndpointResponse webEndpointResponse = (WebEndpointResponse) response; return Response.status(webEndpointResponse.getStatus()) - .header("Content-Type", webEndpointResponse.getContentType()) - .entity(convertIfNecessary(webEndpointResponse.getBody())).build(); + .header("Content-Type", webEndpointResponse.getContentType()) + .entity(convertIfNecessary(webEndpointResponse.getBody())) + .build(); } private Object convertIfNecessary(Object body) { @@ -323,7 +328,7 @@ public class JerseyEndpointResourceFactory { @Override public Response apply(ContainerRequestContext request) { Map links = this.linksResolver - .resolveLinks(request.getUriInfo().getAbsolutePath().toString()); + .resolveLinks(request.getUriInfo().getAbsolutePath().toString()); return Response.ok(Collections.singletonMap("_links", links)).build(); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/AbstractWebFluxEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/AbstractWebFluxEndpointHandlerMapping.java index 3975d3419c..6fc5da3f67 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/AbstractWebFluxEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/AbstractWebFluxEndpointHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -181,8 +181,10 @@ public abstract class AbstractWebFluxEndpointHandlerMapping extends RequestMappi private void registerLinksMapping() { String path = this.endpointMapping.getPath(); String[] produces = StringUtils.toStringArray(this.endpointMediaTypes.getProduced()); - RequestMappingInfo mapping = RequestMappingInfo.paths(path).methods(RequestMethod.GET).produces(produces) - .build(); + RequestMappingInfo mapping = RequestMappingInfo.paths(path) + .methods(RequestMethod.GET) + .produces(produces) + .build(); LinksHandler linksHandler = getLinksHandler(); registerMapping(mapping, linksHandler, ReflectionUtils.findMethod(linksHandler.getClass(), "links", ServerWebExchange.class)); @@ -300,8 +302,8 @@ public abstract class AbstractWebFluxEndpointHandlerMapping extends RequestMappi Mono springSecurityContext() { return ReactiveSecurityContextHolder.getContext() - .map((securityContext) -> new ReactiveSecurityContext(securityContext.getAuthentication())) - .switchIfEmpty(Mono.just(new ReactiveSecurityContext(null))); + .map((securityContext) -> new ReactiveSecurityContext(securityContext.getAuthentication())) + .switchIfEmpty(Mono.just(new ReactiveSecurityContext(null))); } Mono emptySecurityContext() { @@ -312,29 +314,30 @@ public abstract class AbstractWebFluxEndpointHandlerMapping extends RequestMappi public Mono> handle(ServerWebExchange exchange, Map body) { Map arguments = getArguments(exchange, body); OperationArgumentResolver serverNamespaceArgumentResolver = OperationArgumentResolver - .of(WebServerNamespace.class, () -> WebServerNamespace - .from(WebServerApplicationContext.getServerNamespace(exchange.getApplicationContext()))); + .of(WebServerNamespace.class, () -> WebServerNamespace + .from(WebServerApplicationContext.getServerNamespace(exchange.getApplicationContext()))); return this.securityContextSupplier.get() - .map((securityContext) -> new InvocationContext(securityContext, arguments, - serverNamespaceArgumentResolver, - new ProducibleOperationArgumentResolver( - () -> exchange.getRequest().getHeaders().get("Accept")))) - .flatMap((invocationContext) -> handleResult((Publisher) this.invoker.invoke(invocationContext), - exchange.getRequest().getMethod())); + .map((securityContext) -> new InvocationContext(securityContext, arguments, + serverNamespaceArgumentResolver, + new ProducibleOperationArgumentResolver( + () -> exchange.getRequest().getHeaders().get("Accept")))) + .flatMap((invocationContext) -> handleResult((Publisher) this.invoker.invoke(invocationContext), + exchange.getRequest().getMethod())); } private Map getArguments(ServerWebExchange exchange, Map body) { Map arguments = new LinkedHashMap<>(getTemplateVariables(exchange)); String matchAllRemainingPathSegmentsVariable = this.operation.getRequestPredicate() - .getMatchAllRemainingPathSegmentsVariable(); + .getMatchAllRemainingPathSegmentsVariable(); if (matchAllRemainingPathSegmentsVariable != null) { arguments.put(matchAllRemainingPathSegmentsVariable, getRemainingPathSegments(exchange)); } if (body != null) { arguments.putAll(body); } - exchange.getRequest().getQueryParams() - .forEach((name, values) -> arguments.put(name, (values.size() != 1) ? values : values.get(0))); + exchange.getRequest() + .getQueryParams() + .forEach((name, values) -> arguments.put(name, (values.size() != 1) ? values : values.get(0))); return arguments; } @@ -342,7 +345,8 @@ public abstract class AbstractWebFluxEndpointHandlerMapping extends RequestMappi PathPattern pathPattern = exchange.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); if (pathPattern.hasPatternSyntax()) { String remainingSegments = pathPattern - .extractPathWithinPattern(exchange.getRequest().getPath().pathWithinApplication()).value(); + .extractPathWithinPattern(exchange.getRequest().getPath().pathWithinApplication()) + .value(); return tokenizePathSegments(remainingSegments); } return tokenizePathSegments(pathPattern.toString()); @@ -366,11 +370,12 @@ public abstract class AbstractWebFluxEndpointHandlerMapping extends RequestMappi if (result instanceof Flux) { result = ((Flux) result).collectList(); } - return Mono.from(result).map(this::toResponseEntity) - .onErrorMap(InvalidEndpointRequestException.class, - (ex) -> new ResponseStatusException(HttpStatus.BAD_REQUEST, ex.getReason())) - .defaultIfEmpty(new ResponseEntity<>( - (httpMethod != HttpMethod.GET) ? HttpStatus.NO_CONTENT : HttpStatus.NOT_FOUND)); + return Mono.from(result) + .map(this::toResponseEntity) + .onErrorMap(InvalidEndpointRequestException.class, + (ex) -> new ResponseStatusException(HttpStatus.BAD_REQUEST, ex.getReason())) + .defaultIfEmpty(new ResponseEntity<>( + (httpMethod != HttpMethod.GET) ? HttpStatus.NO_CONTENT : HttpStatus.NOT_FOUND)); } private ResponseEntity toResponseEntity(Object response) { @@ -380,8 +385,9 @@ public abstract class AbstractWebFluxEndpointHandlerMapping extends RequestMappi WebEndpointResponse webEndpointResponse = (WebEndpointResponse) response; MediaType contentType = (webEndpointResponse.getContentType() != null) ? new MediaType(webEndpointResponse.getContentType()) : null; - return ResponseEntity.status(webEndpointResponse.getStatus()).contentType(contentType) - .body(webEndpointResponse.getBody()); + return ResponseEntity.status(webEndpointResponse.getStatus()) + .contentType(contentType) + .body(webEndpointResponse.getBody()); } @Override diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMapping.java index ef7583bc41..e326a9bada 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -92,7 +92,8 @@ public class ControllerEndpointHandlerMapping extends RequestMappingHandlerMappi patterns = Collections.singleton(getPathPatternParser().parse("")); } String[] endpointMappedPatterns = patterns.stream() - .map((pattern) -> getEndpointMappedPattern(endpoint, pattern)).toArray(String[]::new); + .map((pattern) -> getEndpointMappedPattern(endpoint, pattern)) + .toArray(String[]::new); return mapping.mutate().paths(endpointMappedPatterns).build(); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointHandlerMapping.java index 2b0a7ae83f..15980b6b0c 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,8 +76,9 @@ public class WebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointHandle @Override @ResponseBody public Map> links(ServerWebExchange exchange) { - String requestUri = UriComponentsBuilder.fromUri(exchange.getRequest().getURI()).replaceQuery(null) - .toUriString(); + String requestUri = UriComponentsBuilder.fromUri(exchange.getRequest().getURI()) + .replaceQuery(null) + .toUriString(); return Collections.singletonMap("_links", WebFluxEndpointHandlerMapping.this.linksResolver.resolveLinks(requestUri)); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/AbstractWebMvcEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/AbstractWebMvcEndpointHandlerMapping.java index 429ebace7d..159e47b6b8 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/AbstractWebMvcEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/AbstractWebMvcEndpointHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -234,16 +234,20 @@ public abstract class AbstractWebMvcEndpointHandlerMapping extends RequestMappin } private RequestMappingInfo createRequestMappingInfo(WebOperationRequestPredicate predicate, String path) { - return RequestMappingInfo.paths(this.endpointMapping.createSubPath(path)).options(this.builderConfig) - .methods(RequestMethod.valueOf(predicate.getHttpMethod().name())) - .consumes(predicate.getConsumes().toArray(new String[0])) - .produces(predicate.getProduces().toArray(new String[0])).build(); + return RequestMappingInfo.paths(this.endpointMapping.createSubPath(path)) + .options(this.builderConfig) + .methods(RequestMethod.valueOf(predicate.getHttpMethod().name())) + .consumes(predicate.getConsumes().toArray(new String[0])) + .produces(predicate.getProduces().toArray(new String[0])) + .build(); } private void registerLinksMapping() { RequestMappingInfo mapping = RequestMappingInfo.paths(this.endpointMapping.createSubPath("")) - .methods(RequestMethod.GET).produces(this.endpointMediaTypes.getProduced().toArray(new String[0])) - .options(this.builderConfig).build(); + .methods(RequestMethod.GET) + .produces(this.endpointMediaTypes.getProduced().toArray(new String[0])) + .options(this.builderConfig) + .build(); LinksHandler linksHandler = getLinksHandler(); registerMapping(mapping, linksHandler, ReflectionUtils.findMethod(linksHandler.getClass(), "links", HttpServletRequest.class, HttpServletResponse.class)); @@ -342,12 +346,12 @@ public abstract class AbstractWebMvcEndpointHandlerMapping extends RequestMappin ProducibleOperationArgumentResolver producibleOperationArgumentResolver = new ProducibleOperationArgumentResolver( () -> headers.get("Accept")); OperationArgumentResolver serverNamespaceArgumentResolver = OperationArgumentResolver - .of(WebServerNamespace.class, () -> { - WebApplicationContext applicationContext = WebApplicationContextUtils - .getRequiredWebApplicationContext(request.getServletContext()); - return WebServerNamespace - .from(WebServerApplicationContext.getServerNamespace(applicationContext)); - }); + .of(WebServerNamespace.class, () -> { + WebApplicationContext applicationContext = WebApplicationContextUtils + .getRequiredWebApplicationContext(request.getServletContext()); + return WebServerNamespace + .from(WebServerApplicationContext.getServerNamespace(applicationContext)); + }); InvocationContext invocationContext = new InvocationContext(securityContext, arguments, serverNamespaceArgumentResolver, producibleOperationArgumentResolver); return handleResult(this.operation.invoke(invocationContext), HttpMethod.resolve(request.getMethod())); @@ -365,15 +369,16 @@ public abstract class AbstractWebMvcEndpointHandlerMapping extends RequestMappin private Map getArguments(HttpServletRequest request, Map body) { Map arguments = new LinkedHashMap<>(getTemplateVariables(request)); String matchAllRemainingPathSegmentsVariable = this.operation.getRequestPredicate() - .getMatchAllRemainingPathSegmentsVariable(); + .getMatchAllRemainingPathSegmentsVariable(); if (matchAllRemainingPathSegmentsVariable != null) { arguments.put(matchAllRemainingPathSegmentsVariable, getRemainingPathSegments(request)); } if (body != null && HttpMethod.POST.name().equals(request.getMethod())) { arguments.putAll(body); } - request.getParameterMap().forEach( - (name, values) -> arguments.put(name, (values.length != 1) ? Arrays.asList(values) : values[0])); + request.getParameterMap() + .forEach((name, values) -> arguments.put(name, + (values.length != 1) ? Arrays.asList(values) : values[0])); return arguments; } @@ -417,8 +422,9 @@ public abstract class AbstractWebMvcEndpointHandlerMapping extends RequestMappin WebEndpointResponse response = (WebEndpointResponse) result; MediaType contentType = (response.getContentType() != null) ? new MediaType(response.getContentType()) : null; - return ResponseEntity.status(response.getStatus()).contentType(contentType) - .body(convertIfNecessary(response.getBody())); + return ResponseEntity.status(response.getStatus()) + .contentType(contentType) + .body(convertIfNecessary(response.getBody())); } private Object convertIfNecessary(Object body) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMapping.java index 45b226e5b9..c9280fd805 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -94,7 +94,8 @@ public class ControllerEndpointHandlerMapping extends RequestMappingHandlerMappi patterns = Collections.singleton(""); } String[] endpointMappedPatterns = patterns.stream() - .map((pattern) -> getEndpointMappedPattern(endpoint, pattern)).toArray(String[]::new); + .map((pattern) -> getEndpointMappedPattern(endpoint, pattern)) + .toArray(String[]::new); return mapping.mutate().paths(endpointMappedPatterns).build(); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/SkipPathExtensionContentNegotiation.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/SkipPathExtensionContentNegotiation.java index 156ee97996..52b45be1d0 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/SkipPathExtensionContentNegotiation.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/SkipPathExtensionContentNegotiation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ final class SkipPathExtensionContentNegotiation implements HandlerInterceptor { @SuppressWarnings("deprecation") private static final String SKIP_ATTRIBUTE = org.springframework.web.accept.PathExtensionContentNegotiationStrategy.class - .getName() + ".SKIP"; + .getName() + ".SKIP"; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 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 a261deeda4..eb7fc21974 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -147,8 +147,9 @@ public class EnvironmentEndpoint { private PropertySourceDescriptor describeSource(String sourceName, EnumerablePropertySource source, PlaceholdersResolver resolver, Predicate namePredicate) { Map properties = new LinkedHashMap<>(); - Stream.of(source.getPropertyNames()).filter(namePredicate) - .forEach((name) -> properties.put(name, describeValueOf(name, source, resolver))); + Stream.of(source.getPropertyNames()) + .filter(namePredicate) + .forEach((name) -> properties.put(name, describeValueOf(name, source, resolver))); return new PropertySourceDescriptor(sourceName, properties); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/flyway/FlywayEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/flyway/FlywayEndpoint.java index 5e819d7516..5ceafc408d 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/flyway/FlywayEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/flyway/FlywayEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,7 +58,7 @@ public class FlywayEndpoint { while (target != null) { Map flywayBeans = new HashMap<>(); target.getBeansOfType(Flyway.class) - .forEach((name, flyway) -> flywayBeans.put(name, new FlywayDescriptor(flyway.info().all()))); + .forEach((name, flyway) -> flywayBeans.put(name, new FlywayDescriptor(flyway.info().all()))); ApplicationContext parent = target.getParent(); contextFlywayBeans.put(target.getId(), new ContextFlywayBeans(flywayBeans, (parent != null) ? parent.getId() : null)); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointGroups.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointGroups.java index 26765672ca..87e3deb493 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointGroups.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointGroups.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -78,9 +78,10 @@ public interface HealthEndpointGroups { default Set getAllWithAdditionalPath(WebServerNamespace namespace) { Assert.notNull(namespace, "Namespace must not be null"); Set filteredGroups = new LinkedHashSet<>(); - getNames().stream().map(this::get).filter( - (group) -> group.getAdditionalPath() != null && group.getAdditionalPath().hasNamespace(namespace)) - .forEach(filteredGroups::add); + getNames().stream() + .map(this::get) + .filter((group) -> group.getAdditionalPath() != null && group.getAdditionalPath().hasNamespace(namespace)) + .forEach(filteredGroups::add); return filteredGroups; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointSupport.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointSupport.java index 7ae4e11793..b15aa92059 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointSupport.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -193,7 +193,7 @@ abstract class HealthEndpointSupport { protected final CompositeHealth getCompositeHealth(ApiVersion apiVersion, Map components, StatusAggregator statusAggregator, boolean showComponents, Set groupNames) { Status status = statusAggregator - .getAggregateStatus(components.values().stream().map(this::getStatus).collect(Collectors.toSet())); + .getAggregateStatus(components.values().stream().map(this::getStatus).collect(Collectors.toSet())); Map instances = showComponents ? components : null; if (groupNames != null) { return new SystemHealth(apiVersion, status, instances, groupNames); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/NamedContributorsMapAdapter.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/NamedContributorsMapAdapter.java index ccfb14c8a8..dfa14d1d17 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/NamedContributorsMapAdapter.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/NamedContributorsMapAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,10 @@ abstract class NamedContributorsMapAdapter implements NamedContributors Assert.notNull(map, "Map must not be null"); Assert.notNull(valueAdapter, "ValueAdapter must not be null"); map.keySet().forEach(this::validateKey); - this.map = Collections.unmodifiableMap(map.entrySet().stream().collect(LinkedHashMap::new, - (result, entry) -> result.put(entry.getKey(), adapt(entry.getValue(), valueAdapter)), Map::putAll)); + this.map = Collections.unmodifiableMap(map.entrySet() + .stream() + .collect(LinkedHashMap::new, + (result, entry) -> result.put(entry.getKey(), adapt(entry.getValue(), valueAdapter)), Map::putAll)); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtension.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtension.java index 7a1fc30ddb..ba3a4cc423 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtension.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -111,9 +111,11 @@ public class ReactiveHealthEndpointWebExtension protected Mono aggregateContributions(ApiVersion apiVersion, Map> contributions, StatusAggregator statusAggregator, boolean showComponents, Set groupNames) { - return Flux.fromIterable(contributions.entrySet()).flatMap(NamedHealthComponent::create) - .collectMap(NamedHealthComponent::getName, NamedHealthComponent::getHealth).map((components) -> this - .getCompositeHealth(apiVersion, components, statusAggregator, showComponents, groupNames)); + return Flux.fromIterable(contributions.entrySet()) + .flatMap(NamedHealthComponent::create) + .collectMap(NamedHealthComponent::getName, NamedHealthComponent::getHealth) + .map((components) -> this.getCompositeHealth(apiVersion, components, statusAggregator, showComponents, + groupNames)); } /** diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoPropertiesInfoContributor.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoPropertiesInfoContributor.java index 4f63d06cab..1261e80b47 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoPropertiesInfoContributor.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoPropertiesInfoContributor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -91,7 +91,7 @@ public abstract class InfoPropertiesInfoContributor im */ protected Map extractContent(PropertySource propertySource) { return new Binder(ConfigurationPropertySources.from(propertySource)).bind("", STRING_OBJECT_MAP) - .orElseGet(LinkedHashMap::new); + .orElseGet(LinkedHashMap::new); } /** diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/jms/JmsHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/jms/JmsHealthIndicator.java index 52edf5404e..805d51a319 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/jms/JmsHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/jms/JmsHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,7 +70,7 @@ public class JmsHealthIndicator extends AbstractHealthIndicator { try { if (!this.latch.await(5, TimeUnit.SECONDS)) { JmsHealthIndicator.this.logger - .warn("Connection failed to start within 5 seconds and will be closed."); + .warn("Connection failed to start within 5 seconds and will be closed."); closeConnection(); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpoint.java index da4222bb86..1ca1d85430 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,7 +63,7 @@ public class LiquibaseEndpoint { Map liquibaseBeans = new HashMap<>(); DatabaseFactory factory = DatabaseFactory.getInstance(); target.getBeansOfType(SpringLiquibase.class) - .forEach((name, liquibase) -> liquibaseBeans.put(name, createReport(liquibase, factory))); + .forEach((name, liquibase) -> liquibaseBeans.put(name, createReport(liquibase, factory))); ApplicationContext parent = target.getParent(); contextBeans.put(target.getId(), new ContextLiquibaseBeans(liquibaseBeans, (parent != null) ? parent.getId() : null)); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/HeapDumpWebEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/HeapDumpWebEndpoint.java index ec4cb401b4..da0dd88c57 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/HeapDumpWebEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/HeapDumpWebEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -165,9 +165,9 @@ public class HeapDumpWebEndpoint { protected HotSpotDiagnosticMXBeanHeapDumper() { try { Class diagnosticMXBeanClass = ClassUtils - .resolveClassName("com.sun.management.HotSpotDiagnosticMXBean", null); + .resolveClassName("com.sun.management.HotSpotDiagnosticMXBean", null); this.diagnosticMXBean = ManagementFactory - .getPlatformMXBean((Class) diagnosticMXBeanClass); + .getPlatformMXBean((Class) diagnosticMXBeanClass); this.dumpHeapMethod = ReflectionUtils.findMethod(diagnosticMXBeanClass, "dumpHeap", String.class, Boolean.TYPE); } @@ -284,7 +284,7 @@ public class HeapDumpWebEndpoint { } catch (IOException ex) { TemporaryFileSystemResource.this.logger - .warn("Failed to delete temporary heap dump file '" + getFile() + "'", ex); + .warn("Failed to delete temporary heap dump file '" + getFile() + "'", ex); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/PlainTextThreadDumpFormatter.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/PlainTextThreadDumpFormatter.java index 80569a7967..1a696dcd6f 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/PlainTextThreadDumpFormatter.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/PlainTextThreadDumpFormatter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,8 +73,9 @@ class PlainTextThreadDumpFormatter { } private List lockedMonitorsForDepth(MonitorInfo[] lockedMonitors, int depth) { - return Stream.of(lockedMonitors).filter((lockedMonitor) -> lockedMonitor.getLockedStackDepth() == depth) - .collect(Collectors.toList()); + return Stream.of(lockedMonitors) + .filter((lockedMonitor) -> lockedMonitor.getLockedStackDepth() == depth) + .collect(Collectors.toList()); } private void writeStackTraceElement(PrintWriter writer, StackTraceElement element, ThreadInfo info, 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..f5e58c6084 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -117,8 +117,12 @@ public class MetricsEndpoint { private Collection findFirstMatchingMeters(CompositeMeterRegistry composite, String name, Iterable tags) { - return composite.getRegistries().stream().map((registry) -> findFirstMatchingMeters(registry, name, tags)) - .filter((matching) -> !matching.isEmpty()).findFirst().orElse(Collections.emptyList()); + return composite.getRegistries() + .stream() + .map((registry) -> findFirstMatchingMeters(registry, name, tags)) + .filter((matching) -> !matching.isEmpty()) + .findFirst() + .orElse(Collections.emptyList()); } private Map getSamples(Collection meters) { @@ -128,8 +132,9 @@ public class MetricsEndpoint { } private void mergeMeasurements(Map samples, Meter meter) { - meter.measure().forEach((measurement) -> samples.merge(measurement.getStatistic(), measurement.getValue(), - mergeFunction(measurement.getStatistic()))); + meter.measure() + .forEach((measurement) -> samples.merge(measurement.getStatistic(), measurement.getValue(), + mergeFunction(measurement.getStatistic()))); } private BiFunction mergeFunction(Statistic statistic) { @@ -157,8 +162,10 @@ public class MetricsEndpoint { } private List asList(Map map, BiFunction mapper) { - return map.entrySet().stream().map((entry) -> mapper.apply(entry.getKey(), entry.getValue())) - .collect(Collectors.toList()); + return map.entrySet() + .stream() + .map((entry) -> mapper.apply(entry.getKey(), entry.getValue())) + .collect(Collectors.toList()); } /** 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..c53223e738 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,9 +72,11 @@ public class CacheMetricsRegistrar { private MeterBinder getMeterBinder(Cache cache, Tags tags) { Tags cacheTags = tags.and(getAdditionalTags(cache)); return LambdaSafe.callbacks(CacheMeterBinderProvider.class, this.binderProviders, cache) - .withLogger(CacheMetricsRegistrar.class) - .invokeAnd((binderProvider) -> binderProvider.getMeterBinder(cache, cacheTags)).filter(Objects::nonNull) - .findFirst().orElse(null); + .withLogger(CacheMetricsRegistrar.class) + .invokeAnd((binderProvider) -> binderProvider.getMeterBinder(cache, cacheTags)) + .filter(Objects::nonNull) + .findFirst() + .orElse(null); } /** diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProvider.java index 92894ec0f4..5a2d89facb 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +48,8 @@ public class HazelcastCacheMeterBinderProvider implements CacheMeterBinderProvid try { Method nativeCacheAccessor = ReflectionUtils.findMethod(HazelcastCache.class, "getNativeCache"); Object nativeCache = ReflectionUtils.invokeMethod(nativeCacheAccessor, cache); - return HazelcastCacheMetrics.class.getConstructor(Object.class, Iterable.class).newInstance(nativeCache, - tags); + return HazelcastCacheMetrics.class.getConstructor(Object.class, Iterable.class) + .newInstance(nativeCache, tags); } catch (Exception ex) { throw new IllegalStateException("Failed to create MeterBinder for Hazelcast", ex); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/RedisCacheMetrics.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/RedisCacheMetrics.java index 45a026bb4e..a9469484d6 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/RedisCacheMetrics.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/RedisCacheMetrics.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,15 +69,20 @@ public class RedisCacheMetrics extends CacheMeterBinder { @Override protected void bindImplementationSpecificMetrics(MeterRegistry registry) { FunctionCounter.builder("cache.removals", this.cache, (cache) -> cache.getStatistics().getDeletes()) - .tags(getTagsWithCacheName()).description("Cache removals").register(registry); + .tags(getTagsWithCacheName()) + .description("Cache removals") + .register(registry); FunctionCounter.builder("cache.gets", this.cache, (cache) -> cache.getStatistics().getPending()) - .tags(getTagsWithCacheName()).tag("result", "pending").description("The number of pending requests") - .register(registry); + .tags(getTagsWithCacheName()) + .tag("result", "pending") + .description("The number of pending requests") + .register(registry); TimeGauge - .builder("cache.lock.duration", this.cache, TimeUnit.NANOSECONDS, - (cache) -> cache.getStatistics().getLockWaitDuration(TimeUnit.NANOSECONDS)) - .tags(getTagsWithCacheName()).description("The time the cache has spent waiting on a lock") - .register(registry); + .builder("cache.lock.duration", this.cache, TimeUnit.NANOSECONDS, + (cache) -> cache.getStatistics().getLockWaitDuration(TimeUnit.NANOSECONDS)) + .tags(getTagsWithCacheName()) + .description("The time the cache has spent waiting on a lock") + .register(registry); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/data/MetricsRepositoryMethodInvocationListener.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/data/MetricsRepositoryMethodInvocationListener.java index a30257d960..f0c66981cc 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/data/MetricsRepositoryMethodInvocationListener.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/data/MetricsRepositoryMethodInvocationListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,8 +69,10 @@ public class MetricsRepositoryMethodInvocationListener implements RepositoryMeth Iterable tags = this.tagsProvider.repositoryTags(invocation); long duration = invocation.getDuration(TimeUnit.NANOSECONDS); AutoTimer.apply(this.autoTimer, this.metricName, annotations, - (builder) -> builder.description("Duration of repository invocations").tags(tags) - .register(this.registrySupplier.get()).record(duration, TimeUnit.NANOSECONDS)); + (builder) -> builder.description("Duration of repository invocations") + .tags(tags) + .register(this.registrySupplier.get()) + .record(duration, TimeUnit.NANOSECONDS)); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/graphql/GraphQlMetricsInstrumentation.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/graphql/GraphQlMetricsInstrumentation.java index af49865d54..5fdd97cfa2 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/graphql/GraphQlMetricsInstrumentation.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/graphql/GraphQlMetricsInstrumentation.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2022 the original author or authors. + * Copyright 2020-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,8 +55,10 @@ public class GraphQlMetricsInstrumentation extends SimpleInstrumentation { this.registry = registry; this.tagsProvider = tagsProvider; this.autoTimer = autoTimer; - this.dataFetchingSummary = DistributionSummary.builder("graphql.request.datafetch.count").baseUnit("calls") - .description("Count of DataFetcher calls per request.").register(this.registry); + this.dataFetchingSummary = DistributionSummary.builder("graphql.request.datafetch.count") + .baseUnit("calls") + .description("Count of DataFetcher calls per request.") + .register(this.registry); } @Override @@ -77,8 +79,11 @@ public class GraphQlMetricsInstrumentation extends SimpleInstrumentation { state.tags(tags).stopTimer(); if (!result.getErrors().isEmpty()) { result.getErrors() - .forEach((error) -> GraphQlMetricsInstrumentation.this.registry.counter("graphql.error", - GraphQlMetricsInstrumentation.this.tagsProvider.getErrorTags(parameters, error)) + .forEach( + (error) -> GraphQlMetricsInstrumentation.this.registry + .counter("graphql.error", + GraphQlMetricsInstrumentation.this.tagsProvider.getErrorTags(parameters, + error)) .increment()); } GraphQlMetricsInstrumentation.this.dataFetchingSummary.record(state.getDataFetchingCount()); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetrics.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetrics.java index 3ebdccd0ff..caf29f30ff 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetrics.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetrics.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -88,7 +88,9 @@ public class DataSourcePoolMetrics implements MeterBinder { Function function) { if (function.apply(this.dataSource) != null) { Gauge.builder("jdbc.connections." + metricName, this.dataSource, (m) -> function.apply(m).doubleValue()) - .tags(this.tags).description(description).register(registry); + .tags(this.tags) + .description(description) + .register(registry); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/r2dbc/ConnectionPoolMetrics.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/r2dbc/ConnectionPoolMetrics.java index 845ceae8ee..36a499fc0f 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/r2dbc/ConnectionPoolMetrics.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/r2dbc/ConnectionPoolMetrics.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,22 +50,21 @@ public class ConnectionPoolMetrics implements MeterBinder { this.pool.getMetrics().ifPresent((poolMetrics) -> { bindConnectionPoolMetric(registry, Gauge.builder(metricKey("acquired"), poolMetrics, PoolMetrics::acquiredSize) - .description("Size of successfully acquired connections which are in active use.")); + .description("Size of successfully acquired connections which are in active use.")); bindConnectionPoolMetric(registry, Gauge.builder(metricKey("allocated"), poolMetrics, PoolMetrics::allocatedSize) - .description("Size of allocated connections in the pool which are in active use or idle.")); + .description("Size of allocated connections in the pool which are in active use or idle.")); bindConnectionPoolMetric(registry, Gauge.builder(metricKey("idle"), poolMetrics, PoolMetrics::idleSize) - .description("Size of idle connections in the pool.")); + .description("Size of idle connections in the pool.")); bindConnectionPoolMetric(registry, - Gauge.builder(metricKey("pending"), poolMetrics, PoolMetrics::pendingAcquireSize).description( - "Size of pending to acquire connections from the underlying connection factory.")); + Gauge.builder(metricKey("pending"), poolMetrics, PoolMetrics::pendingAcquireSize) + .description("Size of pending to acquire connections from the underlying connection factory.")); bindConnectionPoolMetric(registry, Gauge.builder(metricKey("max.allocated"), poolMetrics, PoolMetrics::getMaxAllocatedSize) - .description("Maximum size of allocated connections that this pool allows.")); + .description("Maximum size of allocated connections that this pool allows.")); bindConnectionPoolMetric(registry, Gauge.builder(metricKey("max.pending"), poolMetrics, PoolMetrics::getMaxPendingAcquireSize) - .description( - "Maximum size of pending state to acquire connections that this pool allows.")); + .description("Maximum size of pending state to acquire connections that this pool allows.")); }); } 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..63ba53fdb5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -116,8 +116,10 @@ public class StartupTimeMetricsListener implements SmartApplicationListener { SpringApplication springApplication) { if (timeTaken != null) { Iterable tags = createTagsFrom(springApplication); - TimeGauge.builder(name, timeTaken::toMillis, TimeUnit.MILLISECONDS).tags(tags).description(description) - .register(this.meterRegistry); + TimeGauge.builder(name, timeTaken::toMillis, TimeUnit.MILLISECONDS) + .tags(tags) + .description(description) + .register(this.meterRegistry); } } 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 5dd05ed2d6..e4a19695c7 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 @@ -88,8 +88,8 @@ class MetricsClientHttpRequestInterceptor implements ClientHttpRequestIntercepto } finally { try { - getTimeBuilder(request, response).register(this.meterRegistry).record(System.nanoTime() - startTime, - TimeUnit.NANOSECONDS); + getTimeBuilder(request, response).register(this.meterRegistry) + .record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS); } catch (Exception ex) { logger.info("Failed to record metrics.", ex); @@ -113,8 +113,8 @@ class MetricsClientHttpRequestInterceptor implements ClientHttpRequestIntercepto private Timer.Builder getTimeBuilder(HttpRequest request, ClientHttpResponse response) { return this.autoTimer.builder(this.metricName) - .tags(this.tagProvider.getTags(urlTemplate.get().poll(), request, response)) - .description("Timer of RestTemplate operation"); + .tags(this.tagProvider.getTags(urlTemplate.get().poll(), request, response)) + .description("Timer of RestTemplate operation"); } private final class CapturingUriTemplateHandler implements UriTemplateHandler { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunction.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunction.java index 067bb37b70..c103729d76 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunction.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunction.java @@ -79,8 +79,9 @@ public class MetricsWebClientFilterFunction implements ExchangeFilterFunction { if (!this.autoTimer.isEnabled()) { return next.exchange(request); } - return next.exchange(request).as((responseMono) -> instrumentResponse(request, responseMono)) - .contextWrite(this::putStartTime); + return next.exchange(request) + .as((responseMono) -> instrumentResponse(request, responseMono)) + .contextWrite(this::putStartTime); } private Mono instrumentResponse(ClientRequest request, Mono responseMono) { @@ -100,8 +101,11 @@ public class MetricsWebClientFilterFunction implements ExchangeFilterFunction { private void recordTimer(ClientRequest request, ClientResponse response, Throwable error, Long startTime) { try { Iterable tags = this.tagProvider.tags(request, response, error); - this.autoTimer.builder(this.metricName).tags(tags).description("Timer of WebClient operation") - .register(this.meterRegistry).record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS); + this.autoTimer.builder(this.metricName) + .tags(tags) + .description("Timer of WebClient operation") + .register(this.meterRegistry) + .record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS); } catch (Exception ex) { logger.warn("Failed to record timer metrics", ex); 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 2609055f06..43fca24cd9 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-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,7 +85,7 @@ public class MetricsWebFilter implements WebFilter { private Publisher filter(ServerWebExchange exchange, Mono call) { long start = System.nanoTime(); return call.doOnEach((signal) -> onTerminalSignal(exchange, signal.getThrowable(), start)) - .doOnCancel(() -> onTerminalSignal(exchange, new CancelledServerWebExchangeException(), start)); + .doOnCancel(() -> onTerminalSignal(exchange, new CancelledServerWebExchangeException(), start)); } private void onTerminalSignal(ServerWebExchange exchange, Throwable cause, long start) { @@ -109,8 +109,10 @@ public class MetricsWebFilter implements WebFilter { Iterable tags = this.tagsProvider.httpRequestTags(exchange, cause); long duration = System.nanoTime() - start; AutoTimer.apply(this.autoTimer, this.metricName, annotations, - (builder) -> builder.description("Duration of HTTP server request handling").tags(tags) - .register(this.registry).record(duration, TimeUnit.NANOSECONDS)); + (builder) -> builder.description("Duration of HTTP server request handling") + .tags(tags) + .register(this.registry) + .record(duration, TimeUnit.NANOSECONDS)); } catch (Exception ex) { logger.warn("Failed to record timer metrics", ex); 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 7f5be970bb..ec40678f8e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -125,8 +125,9 @@ public class LongTaskTimingHandlerInterceptor implements HandlerInterceptor { } private Set findTimedAnnotations(AnnotatedElement element) { - return MergedAnnotations.from(element).stream(Timed.class) - .collect(MergedAnnotationCollectors.toAnnotationSet()); + return MergedAnnotations.from(element) + .stream(Timed.class) + .collect(MergedAnnotationCollectors.toAnnotationSet()); } private void stopLongTaskTimers(LongTaskTimingContext timingContext) { 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 ae050db9d8..150634f72b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -159,7 +159,8 @@ public class WebMvcMetricsFilter extends OncePerRequestFilter { private Timer getTimer(Builder builder, Object handler, HttpServletRequest request, HttpServletResponse response, Throwable exception) { return builder.description("Duration of HTTP server request handling") - .tags(this.tagsProvider.getTags(request, response, handler, exception)).register(this.registry); + .tags(this.tagsProvider.getTags(request, response, handler, exception)) + .register(this.registry); } /** diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthDetailsHandler.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthDetailsHandler.java index aec1250275..42eaaf5e66 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthDetailsHandler.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthDetailsHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,9 @@ class Neo4jHealthDetailsHandler { void addHealthDetails(Builder builder, Neo4jHealthDetails healthDetails) { ResultSummary summary = healthDetails.getSummary(); ServerInfo serverInfo = summary.server(); - builder.up().withDetail("server", healthDetails.getVersion() + "@" + serverInfo.address()).withDetail("edition", - healthDetails.getEdition()); + builder.up() + .withDetail("server", healthDetails.getVersion() + "@" + serverInfo.address()) + .withDetail("edition", healthDetails.getEdition()); DatabaseInfo databaseInfo = summary.database(); if (StringUtils.hasText(databaseInfo.name())) { builder.withDetail("database", databaseInfo.name()); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicator.java index 1cab0e246c..86fa156fb3 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,8 +57,9 @@ public class Neo4jHealthIndicator extends AbstractHealthIndicator { /** * The default session config to use while connecting. */ - static final SessionConfig DEFAULT_SESSION_CONFIG = SessionConfig.builder().withDefaultAccessMode(AccessMode.WRITE) - .build(); + static final SessionConfig DEFAULT_SESSION_CONFIG = SessionConfig.builder() + .withDefaultAccessMode(AccessMode.WRITE) + .build(); private final Driver driver; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicator.java index 2980bbc11d..58b04157c7 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,12 +53,12 @@ public final class Neo4jReactiveHealthIndicator extends AbstractReactiveHealthIn @Override protected Mono doHealthCheck(Health.Builder builder) { return runHealthCheckQuery() - .doOnError(SessionExpiredException.class, - (ex) -> logger.warn(Neo4jHealthIndicator.MESSAGE_SESSION_EXPIRED)) - .retryWhen(Retry.max(1).filter(SessionExpiredException.class::isInstance)).map((healthDetails) -> { - this.healthDetailsHandler.addHealthDetails(builder, healthDetails); - return builder.build(); - }); + .doOnError(SessionExpiredException.class, (ex) -> logger.warn(Neo4jHealthIndicator.MESSAGE_SESSION_EXPIRED)) + .retryWhen(Retry.max(1).filter(SessionExpiredException.class::isInstance)) + .map((healthDetails) -> { + this.healthDetailsHandler.addHealthDetails(builder, healthDetails); + return builder.build(); + }); } Mono runHealthCheckQuery() { @@ -66,8 +66,9 @@ public final class Neo4jReactiveHealthIndicator extends AbstractReactiveHealthIn // all possible workloads return Mono.using(() -> this.driver.rxSession(Neo4jHealthIndicator.DEFAULT_SESSION_CONFIG), (session) -> { RxResult result = session.run(Neo4jHealthIndicator.CYPHER); - return Mono.from(result.records()).zipWhen((record) -> Mono.from(result.consume())) - .map((tuple) -> new Neo4jHealthDetails(tuple.getT1(), tuple.getT2())); + return Mono.from(result.records()) + .zipWhen((record) -> Mono.from(result.consume())) + .map((tuple) -> new Neo4jHealthDetails(tuple.getT1(), tuple.getT2())); }, RxSession::close); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/quartz/QuartzEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/quartz/QuartzEndpoint.java index a6ece7f386..0e1a9934bb 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/quartz/QuartzEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/quartz/QuartzEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,8 +64,8 @@ import org.springframework.util.Assert; public class QuartzEndpoint { private static final Comparator TRIGGER_COMPARATOR = Comparator - .comparing(Trigger::getNextFireTime, Comparator.nullsLast(Comparator.naturalOrder())) - .thenComparing(Comparator.comparingInt(Trigger::getPriority).reversed()); + .comparing(Trigger::getNextFireTime, Comparator.nullsLast(Comparator.naturalOrder())) + .thenComparing(Comparator.comparingInt(Trigger::getPriority).reversed()); private final Scheduler scheduler; @@ -111,8 +111,10 @@ public class QuartzEndpoint { public QuartzGroups quartzJobGroups() throws SchedulerException { Map result = new LinkedHashMap<>(); for (String groupName : this.scheduler.getJobGroupNames()) { - List jobs = this.scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName)).stream() - .map((key) -> key.getName()).collect(Collectors.toList()); + List jobs = this.scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName)) + .stream() + .map((key) -> key.getName()) + .collect(Collectors.toList()); result.put(groupName, Collections.singletonMap("jobs", jobs)); } return new QuartzGroups(result); @@ -129,8 +131,11 @@ public class QuartzEndpoint { for (String groupName : this.scheduler.getTriggerGroupNames()) { Map groupDetails = new LinkedHashMap<>(); groupDetails.put("paused", pausedTriggerGroups.contains(groupName)); - groupDetails.put("triggers", this.scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(groupName)) - .stream().map((key) -> key.getName()).collect(Collectors.toList())); + groupDetails.put("triggers", + this.scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(groupName)) + .stream() + .map((key) -> key.getName()) + .collect(Collectors.toList())); result.put(groupName, groupDetails); } return new QuartzGroups(result); @@ -242,8 +247,9 @@ public class QuartzEndpoint { public Map quartzTrigger(String groupName, String triggerName) throws SchedulerException { TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, groupName); Trigger trigger = this.scheduler.getTrigger(triggerKey); - return (trigger != null) ? TriggerDescription.of(trigger).buildDetails( - this.scheduler.getTriggerState(triggerKey), sanitizeJobDataMap(trigger.getJobDataMap())) : null; + return (trigger != null) ? TriggerDescription.of(trigger) + .buildDetails(this.scheduler.getTriggerState(triggerKey), sanitizeJobDataMap(trigger.getJobDataMap())) + : null; } private static Duration getIntervalDuration(long amount, IntervalUnit unit) { @@ -581,9 +587,12 @@ public class QuartzEndpoint { private final TriggerType type; private static TriggerDescription of(Trigger trigger) { - return DESCRIBERS.entrySet().stream().filter((entry) -> entry.getKey().isInstance(trigger)) - .map((entry) -> entry.getValue().apply(trigger)).findFirst() - .orElse(new CustomTriggerDescription(trigger)); + return DESCRIBERS.entrySet() + .stream() + .filter((entry) -> entry.getKey().isInstance(trigger)) + .map((entry) -> entry.getValue().apply(trigger)) + .findFirst() + .orElse(new CustomTriggerDescription(trigger)); } protected TriggerDescription(Trigger trigger, TriggerType type) { @@ -732,7 +741,7 @@ public class QuartzEndpoint { protected void appendSummary(Map content) { content.put("interval", getIntervalDuration(this.trigger.getRepeatInterval(), this.trigger.getRepeatIntervalUnit()) - .toMillis()); + .toMillis()); putIfNoNull(content, "daysOfWeek", this.trigger.getDaysOfWeek()); putIfNoNull(content, "startTimeOfDay", getLocalTime(this.trigger.getStartTimeOfDay())); putIfNoNull(content, "endTimeOfDay", getLocalTime(this.trigger.getEndTimeOfDay())); @@ -763,7 +772,7 @@ public class QuartzEndpoint { protected void appendSummary(Map content) { content.put("interval", getIntervalDuration(this.trigger.getRepeatInterval(), this.trigger.getRepeatIntervalUnit()) - .toMillis()); + .toMillis()); putIfNoNull(content, "timeZone", this.trigger.getTimeZone()); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/r2dbc/ConnectionFactoryHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/r2dbc/ConnectionFactoryHealthIndicator.java index 55417c7f4e..d1c3d942cb 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/r2dbc/ConnectionFactoryHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/r2dbc/ConnectionFactoryHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,8 +70,8 @@ public class ConnectionFactoryHealthIndicator extends AbstractReactiveHealthIndi @Override protected final Mono doHealthCheck(Builder builder) { - return validate(builder).defaultIfEmpty(builder.build()).onErrorResume(Exception.class, - (ex) -> Mono.just(builder.down(ex).build())); + return validate(builder).defaultIfEmpty(builder.build()) + .onErrorResume(Exception.class, (ex) -> Mono.just(builder.down(ex).build())); } private Mono validate(Builder builder) { @@ -84,7 +84,8 @@ public class ConnectionFactoryHealthIndicator extends AbstractReactiveHealthIndi builder.withDetail("validationQuery", this.validationQuery); Mono connectionValidation = Mono.usingWhen(this.connectionFactory.create(), (conn) -> Flux.from(conn.createStatement(this.validationQuery).execute()) - .flatMap((it) -> it.map(this::extractResult)).next(), + .flatMap((it) -> it.map(this::extractResult)) + .next(), Connection::close, (o, throwable) -> o.close(), Connection::close); return connectionValidation.map((result) -> builder.up().withDetail("result", result).build()); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicator.java index e915531708..867181c28b 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,18 +54,18 @@ public class RedisReactiveHealthIndicator extends AbstractReactiveHealthIndicato private Mono getConnection() { return Mono.fromSupplier(this.connectionFactory::getReactiveConnection) - .subscribeOn(Schedulers.boundedElastic()); + .subscribeOn(Schedulers.boundedElastic()); } private Mono doHealthCheck(Health.Builder builder, ReactiveRedisConnection connection) { return getHealth(builder, connection).onErrorResume((ex) -> Mono.just(builder.down(ex).build())) - .flatMap((health) -> connection.closeLater().thenReturn(health)); + .flatMap((health) -> connection.closeLater().thenReturn(health)); } private Mono getHealth(Health.Builder builder, ReactiveRedisConnection connection) { if (connection instanceof ReactiveRedisClusterConnection) { return ((ReactiveRedisClusterConnection) connection).clusterGetClusterInfo() - .map((info) -> fromClusterInfo(builder, info)); + .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..712cd6bb5c 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,9 +60,11 @@ public class ScheduledTasksEndpoint { @ReadOperation public ScheduledTasksReport scheduledTasks() { Map> descriptionsByType = this.scheduledTaskHolders.stream() - .flatMap((holder) -> holder.getScheduledTasks().stream()).map(ScheduledTask::getTask) - .map(TaskDescription::of).filter(Objects::nonNull) - .collect(Collectors.groupingBy(TaskDescription::getType)); + .flatMap((holder) -> holder.getScheduledTasks().stream()) + .map(ScheduledTask::getTask) + .map(TaskDescription::of) + .filter(Objects::nonNull) + .collect(Collectors.groupingBy(TaskDescription::getType)); return new ScheduledTasksReport(descriptionsByType); } @@ -124,8 +126,12 @@ public class ScheduledTasksEndpoint { private final RunnableDescription runnable; private static TaskDescription of(Task task) { - return DESCRIBERS.entrySet().stream().filter((entry) -> entry.getKey().isInstance(task)) - .map((entry) -> entry.getValue().apply(task)).findFirst().orElse(null); + return DESCRIBERS.entrySet() + .stream() + .filter((entry) -> entry.getKey().isInstance(task)) + .map((entry) -> entry.getValue().apply(task)) + .findFirst() + .orElse(null); } private static TaskDescription describeTriggerTask(TriggerTask triggerTask) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/solr/SolrHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/solr/SolrHealthIndicator.java index 83d4482194..8f67f02eb5 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/solr/SolrHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/solr/SolrHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,8 +52,9 @@ public class SolrHealthIndicator extends AbstractHealthIndicator { protected void doHealthCheck(Health.Builder builder) throws Exception { int statusCode = initializeStatusCheck(); Status status = (statusCode != 0) ? Status.DOWN : Status.UP; - builder.status(status).withDetail("status", statusCode).withDetail("detectedPathType", - this.statusCheck.getPathType()); + builder.status(status) + .withDetail("status", statusCode) + .withDetail("detectedPathType", this.statusCheck.getPathType()); } private int initializeStatusCheck() throws Exception { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicator.java index bf3919a5e5..ef3d88d7d9 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,8 +67,10 @@ public class DiskSpaceHealthIndicator extends AbstractHealthIndicator { diskFreeInBytes, this.threshold)); builder.down(); } - builder.withDetail("total", this.path.getTotalSpace()).withDetail("free", diskFreeInBytes) - .withDetail("threshold", this.threshold.toBytes()).withDetail("exists", this.path.exists()); + builder.withDetail("total", this.path.getTotalSpace()) + .withDetail("free", diskFreeInBytes) + .withDetail("threshold", this.threshold.toBytes()) + .withDetail("exists", this.path.exists()); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracer.java index 97917c0cf5..5cc7df6511 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracer.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -98,8 +98,11 @@ public class HttpExchangeTracer { if (!this.includes.contains(include)) { return new LinkedHashMap<>(); } - return headersSupplier.get().entrySet().stream().filter((entry) -> headerPredicate.test(entry.getKey())) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + return headersSupplier.get() + .entrySet() + .stream() + .filter((entry) -> headerPredicate.test(entry.getKey())) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } private long calculateTimeTaken(HttpTrace trace) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlersMappingDescriptionProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlersMappingDescriptionProvider.java index f231b6120e..beaa0cd4d1 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlersMappingDescriptionProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlersMappingDescriptionProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,8 +56,8 @@ import org.springframework.web.util.pattern.PathPattern; public class DispatcherHandlersMappingDescriptionProvider implements MappingDescriptionProvider { private static final List> descriptionProviders = Arrays - .asList(new RequestMappingInfoHandlerMappingDescriptionProvider(), - new UrlHandlerMappingDescriptionProvider(), new RouterFunctionMappingDescriptionProvider()); + .asList(new RequestMappingInfoHandlerMappingDescriptionProvider(), new UrlHandlerMappingDescriptionProvider(), + new RouterFunctionMappingDescriptionProvider()); @Override public String getMappingName() { @@ -68,7 +68,7 @@ public class DispatcherHandlersMappingDescriptionProvider implements MappingDesc public Map> describeMappings(ApplicationContext context) { Map> mappings = new HashMap<>(); context.getBeansOfType(DispatcherHandler.class) - .forEach((name, handler) -> mappings.put(name, describeMappings(handler))); + .forEach((name, handler) -> mappings.put(name, describeMappings(handler))); return mappings; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/RequestMappingConditionsDescription.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/RequestMappingConditionsDescription.java index a133bb5310..1a9299a9d0 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/RequestMappingConditionsDescription.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/RequestMappingConditionsDescription.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,17 +47,32 @@ public class RequestMappingConditionsDescription { private final List produces; RequestMappingConditionsDescription(RequestMappingInfo requestMapping) { - this.consumes = requestMapping.getConsumesCondition().getExpressions().stream() - .map(MediaTypeExpressionDescription::new).collect(Collectors.toList()); - this.headers = requestMapping.getHeadersCondition().getExpressions().stream() - .map(NameValueExpressionDescription::new).collect(Collectors.toList()); + this.consumes = requestMapping.getConsumesCondition() + .getExpressions() + .stream() + .map(MediaTypeExpressionDescription::new) + .collect(Collectors.toList()); + this.headers = requestMapping.getHeadersCondition() + .getExpressions() + .stream() + .map(NameValueExpressionDescription::new) + .collect(Collectors.toList()); this.methods = requestMapping.getMethodsCondition().getMethods(); - this.params = requestMapping.getParamsCondition().getExpressions().stream() - .map(NameValueExpressionDescription::new).collect(Collectors.toList()); - this.patterns = requestMapping.getPatternsCondition().getPatterns().stream().map(PathPattern::getPatternString) - .collect(Collectors.toSet()); - this.produces = requestMapping.getProducesCondition().getExpressions().stream() - .map(MediaTypeExpressionDescription::new).collect(Collectors.toList()); + this.params = requestMapping.getParamsCondition() + .getExpressions() + .stream() + .map(NameValueExpressionDescription::new) + .collect(Collectors.toList()); + this.patterns = requestMapping.getPatternsCondition() + .getPatterns() + .stream() + .map(PathPattern::getPatternString) + .collect(Collectors.toSet()); + this.produces = requestMapping.getProducesCondition() + .getExpressions() + .stream() + .map(MediaTypeExpressionDescription::new) + .collect(Collectors.toList()); } public List getConsumes() { 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 ec858aded0..f764187f63 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -96,8 +96,10 @@ final class DispatcherServletHandlerMappings { } private Optional findContext() { - return Stream.of(this.webServer.getTomcat().getHost().findChildren()).filter(Context.class::isInstance) - .map(Context.class::cast).findFirst(); + return Stream.of(this.webServer.getTomcat().getHost().findChildren()) + .filter(Context.class::isInstance) + .map(Context.class::cast) + .findFirst(); } private void initializeServlet(Context context, String name) { 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 8644d8366b..8839a149f2 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-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -187,8 +187,8 @@ public class DispatcherServletsMappingDescriptionProvider implements MappingDesc public List describe(Iterable handlerMapping) { List descriptions = new ArrayList<>(); for (Object delegate : handlerMapping) { - descriptions.addAll( - DispatcherServletsMappingDescriptionProvider.describe(delegate, this.descriptionProviders)); + descriptions + .addAll(DispatcherServletsMappingDescriptionProvider.describe(delegate, this.descriptionProviders)); } return descriptions; } 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 677558448a..837372d518 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-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,12 @@ public class FiltersMappingDescriptionProvider implements MappingDescriptionProv if (!(context instanceof WebApplicationContext)) { return Collections.emptyList(); } - return ((WebApplicationContext) context).getServletContext().getFilterRegistrations().values().stream() - .map(FilterRegistrationMappingDescription::new).collect(Collectors.toList()); + return ((WebApplicationContext) context).getServletContext() + .getFilterRegistrations() + .values() + .stream() + .map(FilterRegistrationMappingDescription::new) + .collect(Collectors.toList()); } @Override diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/RequestMappingConditionsDescription.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/RequestMappingConditionsDescription.java index 46cafd0474..cfc053f6af 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/RequestMappingConditionsDescription.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/RequestMappingConditionsDescription.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,16 +47,28 @@ public class RequestMappingConditionsDescription { private final List produces; RequestMappingConditionsDescription(RequestMappingInfo requestMapping) { - this.consumes = requestMapping.getConsumesCondition().getExpressions().stream() - .map(MediaTypeExpressionDescription::new).collect(Collectors.toList()); - this.headers = requestMapping.getHeadersCondition().getExpressions().stream() - .map(NameValueExpressionDescription::new).collect(Collectors.toList()); + this.consumes = requestMapping.getConsumesCondition() + .getExpressions() + .stream() + .map(MediaTypeExpressionDescription::new) + .collect(Collectors.toList()); + this.headers = requestMapping.getHeadersCondition() + .getExpressions() + .stream() + .map(NameValueExpressionDescription::new) + .collect(Collectors.toList()); this.methods = requestMapping.getMethodsCondition().getMethods(); - this.params = requestMapping.getParamsCondition().getExpressions().stream() - .map(NameValueExpressionDescription::new).collect(Collectors.toList()); + this.params = requestMapping.getParamsCondition() + .getExpressions() + .stream() + .map(NameValueExpressionDescription::new) + .collect(Collectors.toList()); this.patterns = extractPathPatterns(requestMapping); - this.produces = requestMapping.getProducesCondition().getExpressions().stream() - .map(MediaTypeExpressionDescription::new).collect(Collectors.toList()); + this.produces = requestMapping.getProducesCondition() + .getExpressions() + .stream() + .map(MediaTypeExpressionDescription::new) + .collect(Collectors.toList()); } private Set extractPathPatterns(RequestMappingInfo requestMapping) { 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 4cf432c121..cfd6e79e14 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-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,12 @@ public class ServletsMappingDescriptionProvider implements MappingDescriptionPro if (!(context instanceof WebApplicationContext)) { return Collections.emptyList(); } - return ((WebApplicationContext) context).getServletContext().getServletRegistrations().values().stream() - .map(ServletRegistrationMappingDescription::new).collect(Collectors.toList()); + return ((WebApplicationContext) context).getServletContext() + .getServletRegistrations() + .values() + .stream() + .map(ServletRegistrationMappingDescription::new) + .collect(Collectors.toList()); } @Override diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/reactive/HttpTraceWebFilter.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/reactive/HttpTraceWebFilter.java index 224724f8d7..6ac228e6df 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/reactive/HttpTraceWebFilter.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/reactive/HttpTraceWebFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,8 +71,9 @@ public class HttpTraceWebFilter implements WebFilter, Ordered { Mono principal = (this.includes.contains(Include.PRINCIPAL) ? exchange.getPrincipal().cast(Object.class).defaultIfEmpty(NONE) : Mono.just(NONE)); Mono session = (this.includes.contains(Include.SESSION_ID) ? exchange.getSession() : Mono.just(NONE)); - return Mono.zip(principal, session).flatMap((tuple) -> filter(exchange, chain, - asType(tuple.getT1(), Principal.class), asType(tuple.getT2(), WebSession.class))); + return Mono.zip(principal, session) + .flatMap((tuple) -> filter(exchange, chain, asType(tuple.getT1(), Principal.class), + asType(tuple.getT2(), WebSession.class))); } private T asType(Object object, Class type) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java index 0e7ab62d5c..63856b2f16 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ class RabbitHealthIndicatorTests { @Test void createWhenRabbitTemplateIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new RabbitHealthIndicator(null)) - .withMessageContaining("RabbitTemplate must not be null"); + .withMessageContaining("RabbitTemplate must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java index 2d31dc02fa..23f1f92ebd 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,15 +59,15 @@ class AuditEventTests { @Test void nullTimestamp() { assertThatIllegalArgumentException() - .isThrownBy(() -> new AuditEvent(null, "phil", "UNKNOWN", Collections.singletonMap("a", "b"))) - .withMessageContaining("Timestamp must not be null"); + .isThrownBy(() -> new AuditEvent(null, "phil", "UNKNOWN", Collections.singletonMap("a", "b"))) + .withMessageContaining("Timestamp must not be null"); } @Test void nullType() { assertThatIllegalArgumentException() - .isThrownBy(() -> new AuditEvent("phil", null, Collections.singletonMap("a", "b"))) - .withMessageContaining("Type must not be null"); + .isThrownBy(() -> new AuditEvent("phil", null, Collections.singletonMap("a", "b"))) + .withMessageContaining("Type must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointWebIntegrationTests.java index 66e60ca94a..324565a836 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,32 +37,54 @@ class AuditEventsEndpointWebIntegrationTests { @WebEndpointTest void allEvents(WebTestClient client) { - client.get().uri((builder) -> builder.path("/actuator/auditevents").build()).exchange().expectStatus().isOk() - .expectBody().jsonPath("events.[*].principal") - .isEqualTo(new JSONArray().appendElement("admin").appendElement("admin").appendElement("user")); + client.get() + .uri((builder) -> builder.path("/actuator/auditevents").build()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("events.[*].principal") + .isEqualTo(new JSONArray().appendElement("admin").appendElement("admin").appendElement("user")); } @WebEndpointTest void eventsAfter(WebTestClient client) { client.get() - .uri((builder) -> builder.path("/actuator/auditevents") - .queryParam("after", "2016-11-01T13:00:00%2B00:00").build()) - .exchange().expectStatus().isOk().expectBody().jsonPath("events").isEmpty(); + .uri((builder) -> builder.path("/actuator/auditevents") + .queryParam("after", "2016-11-01T13:00:00%2B00:00") + .build()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("events") + .isEmpty(); } @WebEndpointTest void eventsWithPrincipal(WebTestClient client) { - client.get().uri((builder) -> builder.path("/actuator/auditevents").queryParam("principal", "user").build()) - .exchange().expectStatus().isOk().expectBody().jsonPath("events.[*].principal") - .isEqualTo(new JSONArray().appendElement("user")); + client.get() + .uri((builder) -> builder.path("/actuator/auditevents").queryParam("principal", "user").build()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("events.[*].principal") + .isEqualTo(new JSONArray().appendElement("user")); } @WebEndpointTest void eventsWithType(WebTestClient client) { - client.get().uri((builder) -> builder.path("/actuator/auditevents").queryParam("type", "logout").build()) - .exchange().expectStatus().isOk().expectBody().jsonPath("events.[*].principal") - .isEqualTo(new JSONArray().appendElement("admin")).jsonPath("events.[*].type") - .isEqualTo(new JSONArray().appendElement("logout")); + client.get() + .uri((builder) -> builder.path("/actuator/auditevents").queryParam("type", "logout").build()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("events.[*].principal") + .isEqualTo(new JSONArray().appendElement("admin")) + .jsonPath("events.[*].type") + .isEqualTo(new JSONArray().appendElement("logout")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java index 1c332729d4..320948f1ca 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,7 +63,7 @@ class InMemoryAuditEventRepositoryTests { void addNullAuditEvent() { InMemoryAuditEventRepository repository = new InMemoryAuditEventRepository(); assertThatIllegalArgumentException().isThrownBy(() -> repository.add(null)) - .withMessageContaining("AuditEvent must not be null"); + .withMessageContaining("AuditEvent must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/availability/AvailabilityStateHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/availability/AvailabilityStateHealthIndicatorTests.java index e7823e4f6c..a874e4be5f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/availability/AvailabilityStateHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/availability/AvailabilityStateHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,30 +44,33 @@ class AvailabilityStateHealthIndicatorTests { @Test void createWhenApplicationAvailabilityIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new AvailabilityStateHealthIndicator(null, LivenessState.class, (statusMappings) -> { - })).withMessage("ApplicationAvailability must not be null"); + .isThrownBy(() -> new AvailabilityStateHealthIndicator(null, LivenessState.class, (statusMappings) -> { + })) + .withMessage("ApplicationAvailability must not be null"); } @Test void createWhenStateTypeIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy( () -> new AvailabilityStateHealthIndicator(this.applicationAvailability, null, (statusMappings) -> { - })).withMessage("StateType must not be null"); + })) + .withMessage("StateType must not be null"); } @Test void createWhenStatusMappingIsNullThrowsException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new AvailabilityStateHealthIndicator(this.applicationAvailability, LivenessState.class, null)) - .withMessage("StatusMappings must not be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new AvailabilityStateHealthIndicator(this.applicationAvailability, LivenessState.class, null)) + .withMessage("StatusMappings must not be null"); } @Test void createWhenStatusMappingDoesNotCoverAllEnumsThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new AvailabilityStateHealthIndicator(this.applicationAvailability, - LivenessState.class, (statusMappings) -> statusMappings.add(LivenessState.CORRECT, Status.UP))) - .withMessage("StatusMappings does not include BROKEN"); + .isThrownBy(() -> new AvailabilityStateHealthIndicator(this.applicationAvailability, LivenessState.class, + (statusMappings) -> statusMappings.add(LivenessState.CORRECT, Status.UP))) + .withMessage("StatusMappings does not include BROKEN"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/beans/BeansEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/beans/BeansEndpointTests.java index 0bb7d07d1b..e885079bfb 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/beans/BeansEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/beans/BeansEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ class BeansEndpointTests { @Test void beansAreFound() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(EndpointConfiguration.class); + .withUserConfiguration(EndpointConfiguration.class); contextRunner.run((context) -> { ApplicationBeans result = context.getBean(BeansEndpoint.class).beans(); ContextBeans descriptor = result.getContexts().get(context.getId()); @@ -61,13 +61,13 @@ class BeansEndpointTests { @Test void infrastructureBeansAreOmitted() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(EndpointConfiguration.class); + .withUserConfiguration(EndpointConfiguration.class); contextRunner.run((context) -> { ConfigurableListableBeanFactory factory = (ConfigurableListableBeanFactory) context - .getAutowireCapableBeanFactory(); + .getAutowireCapableBeanFactory(); List infrastructureBeans = Stream.of(context.getBeanDefinitionNames()) - .filter((name) -> BeanDefinition.ROLE_INFRASTRUCTURE == factory.getBeanDefinition(name).getRole()) - .collect(Collectors.toList()); + .filter((name) -> BeanDefinition.ROLE_INFRASTRUCTURE == factory.getBeanDefinition(name).getRole()) + .collect(Collectors.toList()); ApplicationBeans result = context.getBean(BeansEndpoint.class).beans(); ContextBeans contextDescriptor = result.getContexts().get(context.getId()); Map beans = contextDescriptor.getBeans(); @@ -80,7 +80,7 @@ class BeansEndpointTests { @Test void lazyBeansAreOmitted() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(EndpointConfiguration.class, LazyBeanConfiguration.class); + .withUserConfiguration(EndpointConfiguration.class, LazyBeanConfiguration.class); contextRunner.run((context) -> { ApplicationBeans result = context.getBean(BeansEndpoint.class).beans(); ContextBeans contextDescriptor = result.getContexts().get(context.getId()); @@ -92,14 +92,15 @@ class BeansEndpointTests { @Test void beansInParentContextAreFound() { ApplicationContextRunner parentRunner = new ApplicationContextRunner() - .withUserConfiguration(BeanConfiguration.class); + .withUserConfiguration(BeanConfiguration.class); parentRunner.run((parent) -> { - new ApplicationContextRunner().withUserConfiguration(EndpointConfiguration.class).withParent(parent) - .run((child) -> { - ApplicationBeans result = child.getBean(BeansEndpoint.class).beans(); - assertThat(result.getContexts().get(parent.getId()).getBeans()).containsKey("bean"); - assertThat(result.getContexts().get(child.getId()).getBeans()).containsKey("endpoint"); - }); + new ApplicationContextRunner().withUserConfiguration(EndpointConfiguration.class) + .withParent(parent) + .run((child) -> { + ApplicationBeans result = child.getBean(BeansEndpoint.class).beans(); + assertThat(result.getContexts().get(parent.getId()).getBeans()).containsKey("bean"); + assertThat(result.getContexts().get(child.getId()).getBeans()).containsKey("endpoint"); + }); }); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java index bbbd0e5b42..581086132b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,7 +87,9 @@ class CachesEndpointTests { cacheManagers.put("another", new ConcurrentMapCacheManager("c", "dupe-cache")); CachesEndpoint endpoint = new CachesEndpoint(cacheManagers); assertThatExceptionOfType(NonUniqueCacheException.class).isThrownBy(() -> endpoint.cache("dupe-cache", null)) - .withMessageContaining("dupe-cache").withMessageContaining("test").withMessageContaining("another"); + .withMessageContaining("dupe-cache") + .withMessageContaining("test") + .withMessageContaining("another"); } @Test @@ -147,8 +149,10 @@ class CachesEndpointTests { cacheManagers.put("another", cacheManager(mockCache("dupe-cache"))); CachesEndpoint endpoint = new CachesEndpoint(cacheManagers); assertThatExceptionOfType(NonUniqueCacheException.class) - .isThrownBy(() -> endpoint.clearCache("dupe-cache", null)).withMessageContaining("dupe-cache") - .withMessageContaining("test").withMessageContaining("another"); + .isThrownBy(() -> endpoint.clearCache("dupe-cache", null)) + .withMessageContaining("dupe-cache") + .withMessageContaining("test") + .withMessageContaining("another"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointWebIntegrationTests.java index 1feb23577a..28f4742c87 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,18 +40,36 @@ class CachesEndpointWebIntegrationTests { @WebEndpointTest void allCaches(WebTestClient client) { - client.get().uri("/actuator/caches").exchange().expectStatus().isOk().expectBody() - .jsonPath("cacheManagers.one.caches.a.target").isEqualTo(ConcurrentHashMap.class.getName()) - .jsonPath("cacheManagers.one.caches.b.target").isEqualTo(ConcurrentHashMap.class.getName()) - .jsonPath("cacheManagers.two.caches.a.target").isEqualTo(ConcurrentHashMap.class.getName()) - .jsonPath("cacheManagers.two.caches.c.target").isEqualTo(ConcurrentHashMap.class.getName()); + client.get() + .uri("/actuator/caches") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("cacheManagers.one.caches.a.target") + .isEqualTo(ConcurrentHashMap.class.getName()) + .jsonPath("cacheManagers.one.caches.b.target") + .isEqualTo(ConcurrentHashMap.class.getName()) + .jsonPath("cacheManagers.two.caches.a.target") + .isEqualTo(ConcurrentHashMap.class.getName()) + .jsonPath("cacheManagers.two.caches.c.target") + .isEqualTo(ConcurrentHashMap.class.getName()); } @WebEndpointTest void namedCache(WebTestClient client) { - client.get().uri("/actuator/caches/b").exchange().expectStatus().isOk().expectBody().jsonPath("name") - .isEqualTo("b").jsonPath("cacheManager").isEqualTo("one").jsonPath("target") - .isEqualTo(ConcurrentHashMap.class.getName()); + client.get() + .uri("/actuator/caches/b") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("name") + .isEqualTo("b") + .jsonPath("cacheManager") + .isEqualTo("one") + .jsonPath("target") + .isEqualTo(ConcurrentHashMap.class.getName()); } @WebEndpointTest diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraDriverHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraDriverHealthIndicatorTests.java index 51de584231..fa59cdab10 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraDriverHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraDriverHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -140,7 +140,7 @@ class CassandraDriverHealthIndicatorTests { Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); assertThat(health.getDetails().get("error")) - .isEqualTo(DriverTimeoutException.class.getName() + ": Test Exception"); + .isEqualTo(DriverTimeoutException.class.getName() + ": Test Exception"); } private CqlSession mockCqlSessionWithNodeState(NodeState... nodeStates) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraDriverReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraDriverReactiveHealthIndicatorTests.java index 39542e5a2c..831225ba35 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraDriverReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraDriverReactiveHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,8 +59,9 @@ class CassandraDriverReactiveHealthIndicatorTests { CqlSession session = mockCqlSessionWithNodeState(NodeState.UP); CassandraDriverReactiveHealthIndicator healthIndicator = new CassandraDriverReactiveHealthIndicator(session); Mono health = healthIndicator.health(); - StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.UP)) - .verifyComplete(); + StepVerifier.create(health) + .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.UP)) + .verifyComplete(); } @Test @@ -68,8 +69,9 @@ class CassandraDriverReactiveHealthIndicatorTests { CqlSession session = mockCqlSessionWithNodeState(NodeState.DOWN); CassandraDriverReactiveHealthIndicator healthIndicator = new CassandraDriverReactiveHealthIndicator(session); Mono health = healthIndicator.health(); - StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) - .verifyComplete(); + StepVerifier.create(health) + .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) + .verifyComplete(); } @Test @@ -77,8 +79,9 @@ class CassandraDriverReactiveHealthIndicatorTests { CqlSession session = mockCqlSessionWithNodeState(NodeState.UNKNOWN); CassandraDriverReactiveHealthIndicator healthIndicator = new CassandraDriverReactiveHealthIndicator(session); Mono health = healthIndicator.health(); - StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) - .verifyComplete(); + StepVerifier.create(health) + .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) + .verifyComplete(); } @Test @@ -86,8 +89,9 @@ class CassandraDriverReactiveHealthIndicatorTests { CqlSession session = mockCqlSessionWithNodeState(NodeState.FORCED_DOWN); CassandraDriverReactiveHealthIndicator healthIndicator = new CassandraDriverReactiveHealthIndicator(session); Mono health = healthIndicator.health(); - StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) - .verifyComplete(); + StepVerifier.create(health) + .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) + .verifyComplete(); } @Test @@ -95,8 +99,9 @@ class CassandraDriverReactiveHealthIndicatorTests { CqlSession session = mockCqlSessionWithNodeState(NodeState.UP, NodeState.DOWN); CassandraDriverReactiveHealthIndicator healthIndicator = new CassandraDriverReactiveHealthIndicator(session); Mono health = healthIndicator.health(); - StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.UP)) - .verifyComplete(); + StepVerifier.create(health) + .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.UP)) + .verifyComplete(); } @Test @@ -104,8 +109,9 @@ class CassandraDriverReactiveHealthIndicatorTests { CqlSession session = mockCqlSessionWithNodeState(NodeState.UP, NodeState.UNKNOWN); CassandraDriverReactiveHealthIndicator healthIndicator = new CassandraDriverReactiveHealthIndicator(session); Mono health = healthIndicator.health(); - StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.UP)) - .verifyComplete(); + StepVerifier.create(health) + .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.UP)) + .verifyComplete(); } @Test @@ -113,8 +119,9 @@ class CassandraDriverReactiveHealthIndicatorTests { CqlSession session = mockCqlSessionWithNodeState(NodeState.UP, NodeState.FORCED_DOWN); CassandraDriverReactiveHealthIndicator healthIndicator = new CassandraDriverReactiveHealthIndicator(session); Mono health = healthIndicator.health(); - StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.UP)) - .verifyComplete(); + StepVerifier.create(health) + .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.UP)) + .verifyComplete(); } @Test @@ -157,7 +164,7 @@ class CassandraDriverReactiveHealthIndicatorTests { assertThat(h.getStatus()).isEqualTo(Status.DOWN); assertThat(h.getDetails()).containsOnlyKeys("error"); assertThat(h.getDetails().get("error")) - .isEqualTo(DriverTimeoutException.class.getName() + ": Test Exception"); + .isEqualTo(DriverTimeoutException.class.getName() + ": Test Exception"); }).verifyComplete(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/ShutdownEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/ShutdownEndpointTests.java index 05f0ef4b4b..c7530f5c76 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/ShutdownEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/ShutdownEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ class ShutdownEndpointTests { @Test void shutdown() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(EndpointConfig.class); + .withUserConfiguration(EndpointConfig.class); contextRunner.run((context) -> { EndpointConfig config = context.getBean(EndpointConfig.class); ClassLoader previousTccl = Thread.currentThread().getContextClassLoader(); @@ -69,7 +69,9 @@ class ShutdownEndpointTests { @Test void shutdownChild() throws Exception { ConfigurableApplicationContext context = new SpringApplicationBuilder(EmptyConfig.class) - .child(EndpointConfig.class).web(WebApplicationType.NONE).run(); + .child(EndpointConfig.class) + .web(WebApplicationType.NONE) + .run(); CountDownLatch latch = context.getBean(EndpointConfig.class).latch; assertThat(context.getBean(ShutdownEndpoint.class).shutdown().get("message")).startsWith("Shutting down"); assertThat(context.isActive()).isTrue(); @@ -79,7 +81,9 @@ class ShutdownEndpointTests { @Test void shutdownParent() throws Exception { ConfigurableApplicationContext context = new SpringApplicationBuilder(EndpointConfig.class) - .child(EmptyConfig.class).web(WebApplicationType.NONE).run(); + .child(EmptyConfig.class) + .web(WebApplicationType.NONE) + .run(); CountDownLatch parentLatch = context.getBean(EndpointConfig.class).latch; CountDownLatch childLatch = context.getBean(EmptyConfig.class).latch; assertThat(context.getBean(ShutdownEndpoint.class).shutdown().get("message")).startsWith("Shutting down"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointFilteringTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointFilteringTests.java index ec2f5c7a0b..a88fc02919 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointFilteringTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointFilteringTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,28 +38,28 @@ class ConfigurationPropertiesReportEndpointFilteringTests { @Test void filterByPrefixSingleMatch() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(Config.class) - .withPropertyValues("foo.primary.name:foo1", "foo.secondary.name:foo2", "only.bar.name:solo1"); + .withPropertyValues("foo.primary.name:foo1", "foo.secondary.name:foo2", "only.bar.name:solo1"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ApplicationConfigurationProperties applicationProperties = endpoint - .configurationPropertiesWithPrefix("only.bar"); + .configurationPropertiesWithPrefix("only.bar"); assertThat(applicationProperties.getContexts()).containsOnlyKeys(context.getId()); ContextConfigurationProperties contextProperties = applicationProperties.getContexts().get(context.getId()); - assertThat(contextProperties.getBeans().values()).singleElement().hasFieldOrPropertyWithValue("prefix", - "only.bar"); + assertThat(contextProperties.getBeans().values()).singleElement() + .hasFieldOrPropertyWithValue("prefix", "only.bar"); }); } @Test void filterByPrefixMultipleMatches() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(Config.class) - .withPropertyValues("foo.primary.name:foo1", "foo.secondary.name:foo2", "only.bar.name:solo1"); + .withPropertyValues("foo.primary.name:foo1", "foo.secondary.name:foo2", "only.bar.name:solo1"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ApplicationConfigurationProperties applicationProperties = endpoint - .configurationPropertiesWithPrefix("foo."); + .configurationPropertiesWithPrefix("foo."); assertThat(applicationProperties.getContexts()).containsOnlyKeys(context.getId()); ContextConfigurationProperties contextProperties = applicationProperties.getContexts().get(context.getId()); assertThat(contextProperties.getBeans()).containsOnlyKeys("primaryFoo", "secondaryFoo"); @@ -69,12 +69,12 @@ class ConfigurationPropertiesReportEndpointFilteringTests { @Test void filterByPrefixNoMatches() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(Config.class) - .withPropertyValues("foo.primary.name:foo1", "foo.secondary.name:foo2", "only.bar.name:solo1"); + .withPropertyValues("foo.primary.name:foo1", "foo.secondary.name:foo2", "only.bar.name:solo1"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ApplicationConfigurationProperties applicationProperties = endpoint - .configurationPropertiesWithPrefix("foo.third"); + .configurationPropertiesWithPrefix("foo.third"); assertThat(applicationProperties.getContexts()).containsOnlyKeys(context.getId()); ContextConfigurationProperties contextProperties = applicationProperties.getContexts().get(context.getId()); assertThat(contextProperties.getBeans()).isEmpty(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java index dddd6007f1..b8dd9d7bb0 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,10 +40,10 @@ class ConfigurationPropertiesReportEndpointMethodAnnotationsTests { @Test void testNaming() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(Config.class) - .withPropertyValues("other.name:foo", "first.name:bar"); + .withPropertyValues("other.name:foo", "first.name:bar"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); assertThat(applicationProperties.getContexts()).containsOnlyKeys(context.getId()); ContextConfigurationProperties contextProperties = applicationProperties.getContexts().get(context.getId()); @@ -58,10 +58,11 @@ class ConfigurationPropertiesReportEndpointMethodAnnotationsTests { @Test void prefixFromBeanMethodConfigurationPropertiesCanOverridePrefixOnClass() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(OverriddenPrefix.class).withPropertyValues("other.name:foo"); + .withUserConfiguration(OverriddenPrefix.class) + .withPropertyValues("other.name:foo"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); assertThat(applicationProperties.getContexts()).containsOnlyKeys(context.getId()); ContextConfigurationProperties contextProperties = applicationProperties.getContexts().get(context.getId()); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointParentTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointParentTests.java index 52e9cae993..70980e2497 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointParentTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointParentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,17 +39,18 @@ class ConfigurationPropertiesReportEndpointParentTests { @Test void configurationPropertiesClass() { new ApplicationContextRunner().withUserConfiguration(Parent.class).run((parent) -> { - new ApplicationContextRunner().withUserConfiguration(ClassConfigurationProperties.class).withParent(parent) - .run((child) -> { - ConfigurationPropertiesReportEndpoint endpoint = child - .getBean(ConfigurationPropertiesReportEndpoint.class); - ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); - assertThat(applicationProperties.getContexts()).containsOnlyKeys(child.getId(), parent.getId()); - assertThat(applicationProperties.getContexts().get(child.getId()).getBeans().keySet()) - .containsExactly("someProperties"); - assertThat((applicationProperties.getContexts().get(parent.getId()).getBeans().keySet())) - .containsExactly("testProperties"); - }); + new ApplicationContextRunner().withUserConfiguration(ClassConfigurationProperties.class) + .withParent(parent) + .run((child) -> { + ConfigurationPropertiesReportEndpoint endpoint = child + .getBean(ConfigurationPropertiesReportEndpoint.class); + ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); + assertThat(applicationProperties.getContexts()).containsOnlyKeys(child.getId(), parent.getId()); + assertThat(applicationProperties.getContexts().get(child.getId()).getBeans().keySet()) + .containsExactly("someProperties"); + assertThat((applicationProperties.getContexts().get(parent.getId()).getBeans().keySet())) + .containsExactly("testProperties"); + }); }); } @@ -57,15 +58,16 @@ class ConfigurationPropertiesReportEndpointParentTests { void configurationPropertiesBeanMethod() { new ApplicationContextRunner().withUserConfiguration(Parent.class).run((parent) -> { new ApplicationContextRunner().withUserConfiguration(BeanMethodConfigurationProperties.class) - .withParent(parent).run((child) -> { - ConfigurationPropertiesReportEndpoint endpoint = child - .getBean(ConfigurationPropertiesReportEndpoint.class); - ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); - assertThat(applicationProperties.getContexts().get(child.getId()).getBeans().keySet()) - .containsExactlyInAnyOrder("otherProperties"); - assertThat((applicationProperties.getContexts().get(parent.getId()).getBeans().keySet())) - .containsExactly("testProperties"); - }); + .withParent(parent) + .run((child) -> { + ConfigurationPropertiesReportEndpoint endpoint = child + .getBean(ConfigurationPropertiesReportEndpoint.class); + ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); + assertThat(applicationProperties.getContexts().get(child.getId()).getBeans().keySet()) + .containsExactlyInAnyOrder("otherProperties"); + assertThat((applicationProperties.getContexts().get(parent.getId()).getBeans().keySet())) + .containsExactly("testProperties"); + }); }); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointProxyTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointProxyTests.java index 61c7a82709..f359af84e9 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointProxyTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointProxyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,22 +58,36 @@ class ConfigurationPropertiesReportEndpointProxyTests { SqlExecutor.class); contextRunner.run((context) -> { ApplicationConfigurationProperties applicationProperties = context - .getBean(ConfigurationPropertiesReportEndpoint.class).configurationProperties(); - assertThat(applicationProperties.getContexts().get(context.getId()).getBeans().values().stream() - .map(ConfigurationPropertiesBeanDescriptor::getPrefix).filter("executor.sql"::equals).findFirst()) - .isNotEmpty(); + .getBean(ConfigurationPropertiesReportEndpoint.class) + .configurationProperties(); + assertThat(applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .values() + .stream() + .map(ConfigurationPropertiesBeanDescriptor::getPrefix) + .filter("executor.sql"::equals) + .findFirst()).isNotEmpty(); }); } @Test void proxiedConstructorBoundPropertiesShouldBeAvailableInReport() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(ValidatedConfiguration.class).withPropertyValues("validated.name=baz"); + .withUserConfiguration(ValidatedConfiguration.class) + .withPropertyValues("validated.name=baz"); contextRunner.run((context) -> { ApplicationConfigurationProperties applicationProperties = context - .getBean(ConfigurationPropertiesReportEndpoint.class).configurationProperties(); - Map properties = applicationProperties.getContexts().get(context.getId()).getBeans() - .values().stream().map(ConfigurationPropertiesBeanDescriptor::getProperties).findFirst().get(); + .getBean(ConfigurationPropertiesReportEndpoint.class) + .configurationProperties(); + Map properties = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .values() + .stream() + .map(ConfigurationPropertiesBeanDescriptor::getProperties) + .findFirst() + .get(); assertThat(properties.get("name")).isEqualTo("baz"); }); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java index 798ff71189..c271053ac6 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,13 +58,15 @@ class ConfigurationPropertiesReportEndpointSerializationTests { @Test void testNaming() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(FooConfig.class) - .withPropertyValues("foo.name:foo"); + .withPropertyValues("foo.name:foo"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("foo"); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("foo"); assertThat(foo).isNotNull(); assertThat(foo.getPrefix()).isEqualTo("foo"); Map map = foo.getProperties(); @@ -78,13 +80,15 @@ class ConfigurationPropertiesReportEndpointSerializationTests { @SuppressWarnings("unchecked") void testNestedNaming() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(FooConfig.class) - .withPropertyValues("foo.bar.name:foo"); + .withPropertyValues("foo.bar.name:foo"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("foo"); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("foo"); assertThat(foo).isNotNull(); Map map = foo.getProperties(); assertThat(map).isNotNull(); @@ -97,13 +101,16 @@ class ConfigurationPropertiesReportEndpointSerializationTests { @SuppressWarnings("unchecked") void testSelfReferentialProperty() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(SelfReferentialConfig.class).withPropertyValues("foo.name:foo"); + .withUserConfiguration(SelfReferentialConfig.class) + .withPropertyValues("foo.name:foo"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("foo"); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("foo"); assertThat(foo.getPrefix()).isEqualTo("foo"); Map map = foo.getProperties(); assertThat(map).isNotNull(); @@ -118,13 +125,15 @@ class ConfigurationPropertiesReportEndpointSerializationTests { @Test void testCycle() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(CycleConfig.class); + .withUserConfiguration(CycleConfig.class); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor cycle = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("cycle"); + ConfigurationPropertiesBeanDescriptor cycle = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("cycle"); assertThat(cycle.getPrefix()).isEqualTo("cycle"); Map map = cycle.getProperties(); assertThat(map).isNotNull(); @@ -137,13 +146,15 @@ class ConfigurationPropertiesReportEndpointSerializationTests { @SuppressWarnings("unchecked") void testMap() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(MapConfig.class) - .withPropertyValues("foo.map.name:foo"); + .withPropertyValues("foo.map.name:foo"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); ConfigurationPropertiesBeanDescriptor fooProperties = applicationProperties.getContexts() - .get(context.getId()).getBeans().get("foo"); + .get(context.getId()) + .getBeans() + .get("foo"); assertThat(fooProperties).isNotNull(); assertThat(fooProperties.getPrefix()).isEqualTo("foo"); Map map = fooProperties.getProperties(); @@ -158,10 +169,12 @@ class ConfigurationPropertiesReportEndpointSerializationTests { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(MapConfig.class); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("foo"); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("foo"); assertThat(foo).isNotNull(); assertThat(foo.getPrefix()).isEqualTo("foo"); Map map = foo.getProperties(); @@ -175,13 +188,15 @@ class ConfigurationPropertiesReportEndpointSerializationTests { @SuppressWarnings("unchecked") void testList() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(ListConfig.class) - .withPropertyValues("foo.list[0]:foo"); + .withPropertyValues("foo.list[0]:foo"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("foo"); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("foo"); assertThat(foo).isNotNull(); assertThat(foo.getPrefix()).isEqualTo("foo"); Map map = foo.getProperties(); @@ -194,13 +209,16 @@ class ConfigurationPropertiesReportEndpointSerializationTests { @Test void testInetAddress() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(AddressedConfig.class).withPropertyValues("foo.address:192.168.1.10"); + .withUserConfiguration(AddressedConfig.class) + .withPropertyValues("foo.address:192.168.1.10"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("foo"); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("foo"); assertThat(foo).isNotNull(); assertThat(foo.getPrefix()).isEqualTo("foo"); Map map = foo.getProperties(); @@ -214,14 +232,16 @@ class ConfigurationPropertiesReportEndpointSerializationTests { @SuppressWarnings("unchecked") void testInitializedMapAndList() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(InitializedMapAndListPropertiesConfig.class) - .withPropertyValues("foo.map.entryOne:true", "foo.list[0]:abc"); + .withUserConfiguration(InitializedMapAndListPropertiesConfig.class) + .withPropertyValues("foo.map.entryOne:true", "foo.list[0]:abc"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("foo"); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("foo"); assertThat(foo.getPrefix()).isEqualTo("foo"); Map propertiesMap = foo.getProperties(); assertThat(propertiesMap).containsOnlyKeys("bar", "name", "map", "list"); @@ -235,13 +255,15 @@ class ConfigurationPropertiesReportEndpointSerializationTests { @Test void hikariDataSourceConfigurationPropertiesBeanCanBeSerialized() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(HikariDataSourceConfig.class); + .withUserConfiguration(HikariDataSourceConfig.class); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); ConfigurationPropertiesBeanDescriptor hikariDataSource = applicationProperties.getContexts() - .get(context.getId()).getBeans().get("hikariDataSource"); + .get(context.getId()) + .getBeans() + .get("hikariDataSource"); Map nestedProperties = hikariDataSource.getProperties(); assertThat(nestedProperties).doesNotContainKey("error"); }); @@ -252,15 +274,18 @@ class ConfigurationPropertiesReportEndpointSerializationTests { void endpointResponseUsesToStringOfCharSequenceAsPropertyValue() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withInitializer((context) -> { ConfigurableEnvironment environment = context.getEnvironment(); - environment.getPropertySources().addFirst(new MapPropertySource("test", - Collections.singletonMap("foo.name", new CharSequenceProperty("Spring Boot")))); + environment.getPropertySources() + .addFirst(new MapPropertySource("test", + Collections.singletonMap("foo.name", new CharSequenceProperty("Spring Boot")))); }).withUserConfiguration(FooConfig.class); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor descriptor = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("foo"); + ConfigurationPropertiesBeanDescriptor descriptor = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("foo"); assertThat((Map) descriptor.getInputs().get("name")).containsEntry("value", "Spring Boot"); }); } @@ -270,15 +295,18 @@ class ConfigurationPropertiesReportEndpointSerializationTests { void endpointResponseUsesPlaceholderForComplexValueAsPropertyValue() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withInitializer((context) -> { ConfigurableEnvironment environment = context.getEnvironment(); - environment.getPropertySources().addFirst(new MapPropertySource("test", - Collections.singletonMap("foo.name", new ComplexProperty("Spring Boot")))); + environment.getPropertySources() + .addFirst(new MapPropertySource("test", + Collections.singletonMap("foo.name", new ComplexProperty("Spring Boot")))); }).withUserConfiguration(ComplexPropertyToStringConverter.class, FooConfig.class); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ApplicationConfigurationProperties applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor descriptor = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("foo"); + ConfigurationPropertiesBeanDescriptor descriptor = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("foo"); assertThat((Map) descriptor.getInputs().get("name")).containsEntry("value", "Complex property value " + ComplexProperty.class.getName()); }); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointTests.java index 32cbf8ea58..c6cfc7b1de 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,108 +65,116 @@ import static org.assertj.core.api.Assertions.entry; class ConfigurationPropertiesReportEndpointTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(EndpointConfig.class); + .withUserConfiguration(EndpointConfig.class); @Test void descriptorWithJavaBeanBindMethodDetectsRelevantProperties() { - this.contextRunner.withUserConfiguration(TestPropertiesConfiguration.class).run(assertProperties("test", - (properties) -> assertThat(properties).containsOnlyKeys("dbPassword", "myTestProperty", "duration"))); + this.contextRunner.withUserConfiguration(TestPropertiesConfiguration.class) + .run(assertProperties("test", (properties) -> assertThat(properties).containsOnlyKeys("dbPassword", + "myTestProperty", "duration"))); } @Test void descriptorWithValueObjectBindMethodDetectsRelevantProperties() { - this.contextRunner.withUserConfiguration(ImmutablePropertiesConfiguration.class).run(assertProperties( - "immutable", - (properties) -> assertThat(properties).containsOnlyKeys("dbPassword", "myTestProperty", "for"))); + this.contextRunner.withUserConfiguration(ImmutablePropertiesConfiguration.class) + .run(assertProperties("immutable", + (properties) -> assertThat(properties).containsOnlyKeys("dbPassword", "myTestProperty", "for"))); } @Test void descriptorWithValueObjectBindMethodUseDedicatedConstructor() { - this.contextRunner.withUserConfiguration(MultiConstructorPropertiesConfiguration.class).run(assertProperties( - "multiconstructor", (properties) -> assertThat(properties).containsOnly(entry("name", "test")))); + this.contextRunner.withUserConfiguration(MultiConstructorPropertiesConfiguration.class) + .run(assertProperties("multiconstructor", + (properties) -> assertThat(properties).containsOnly(entry("name", "test")))); } @Test void descriptorWithValueObjectBindMethodHandleNestedType() { this.contextRunner.withPropertyValues("immutablenested.nested.name=nested", "immutablenested.nested.counter=42") - .withUserConfiguration(ImmutableNestedPropertiesConfiguration.class) - .run(assertProperties("immutablenested", (properties) -> { - assertThat(properties).containsOnlyKeys("name", "nested"); - Map nested = (Map) properties.get("nested"); - assertThat(nested).containsOnly(entry("name", "nested"), entry("counter", 42)); - }, (inputs) -> { - Map nested = (Map) inputs.get("nested"); - Map name = (Map) nested.get("name"); - Map counter = (Map) nested.get("counter"); - assertThat(name.get("value")).isEqualTo("nested"); - assertThat(name.get("origin")) - .isEqualTo("\"immutablenested.nested.name\" from property source \"test\""); - assertThat(counter.get("origin")) - .isEqualTo("\"immutablenested.nested.counter\" from property source \"test\""); - assertThat(counter.get("value")).isEqualTo("42"); - })); + .withUserConfiguration(ImmutableNestedPropertiesConfiguration.class) + .run(assertProperties("immutablenested", (properties) -> { + assertThat(properties).containsOnlyKeys("name", "nested"); + Map nested = (Map) properties.get("nested"); + assertThat(nested).containsOnly(entry("name", "nested"), entry("counter", 42)); + }, (inputs) -> { + Map nested = (Map) inputs.get("nested"); + Map name = (Map) nested.get("name"); + Map counter = (Map) nested.get("counter"); + assertThat(name.get("value")).isEqualTo("nested"); + assertThat(name.get("origin")) + .isEqualTo("\"immutablenested.nested.name\" from property source \"test\""); + assertThat(counter.get("origin")) + .isEqualTo("\"immutablenested.nested.counter\" from property source \"test\""); + assertThat(counter.get("value")).isEqualTo("42"); + })); } @Test void descriptorWithSimpleList() { this.contextRunner.withUserConfiguration(SensiblePropertiesConfiguration.class) - .withPropertyValues("sensible.simpleList=a,b").run(assertProperties("sensible", (properties) -> { - assertThat(properties.get("simpleList")).isInstanceOf(List.class); - List list = (List) properties.get("simpleList"); - assertThat(list).hasSize(2); - assertThat(list.get(0)).isEqualTo("a"); - assertThat(list.get(1)).isEqualTo("b"); - }, (inputs) -> { - List list = (List) inputs.get("simpleList"); - assertThat(list).hasSize(2); - Map item = (Map) list.get(0); - String origin = item.get("origin"); - String value = item.get("value"); - assertThat(value).isEqualTo("a,b"); - assertThat(origin).isEqualTo("\"sensible.simpleList\" from property source \"test\""); - })); + .withPropertyValues("sensible.simpleList=a,b") + .run(assertProperties("sensible", (properties) -> { + assertThat(properties.get("simpleList")).isInstanceOf(List.class); + List list = (List) properties.get("simpleList"); + assertThat(list).hasSize(2); + assertThat(list.get(0)).isEqualTo("a"); + assertThat(list.get(1)).isEqualTo("b"); + }, (inputs) -> { + List list = (List) inputs.get("simpleList"); + assertThat(list).hasSize(2); + Map item = (Map) list.get(0); + String origin = item.get("origin"); + String value = item.get("value"); + assertThat(value).isEqualTo("a,b"); + assertThat(origin).isEqualTo("\"sensible.simpleList\" from property source \"test\""); + })); } @Test void descriptorDoesNotIncludePropertyWithNullValue() { this.contextRunner.withUserConfiguration(TestPropertiesConfiguration.class) - .run(assertProperties("test", (properties) -> assertThat(properties).doesNotContainKey("nullValue"))); + .run(assertProperties("test", (properties) -> assertThat(properties).doesNotContainKey("nullValue"))); } @Test void descriptorWithDurationProperty() { - this.contextRunner.withUserConfiguration(TestPropertiesConfiguration.class).run(assertProperties("test", - (properties) -> assertThat(properties.get("duration")).isEqualTo(Duration.ofSeconds(10).toString()))); + this.contextRunner.withUserConfiguration(TestPropertiesConfiguration.class) + .run(assertProperties("test", (properties) -> assertThat(properties.get("duration")) + .isEqualTo(Duration.ofSeconds(10).toString()))); } @Test void descriptorWithNonCamelCaseProperty() { - this.contextRunner.withUserConfiguration(MixedCasePropertiesConfiguration.class).run(assertProperties( - "mixedcase", (properties) -> assertThat(properties.get("myURL")).isEqualTo("https://example.com"))); + this.contextRunner.withUserConfiguration(MixedCasePropertiesConfiguration.class) + .run(assertProperties("mixedcase", + (properties) -> assertThat(properties.get("myURL")).isEqualTo("https://example.com"))); } @Test void descriptorWithMixedCaseProperty() { - this.contextRunner.withUserConfiguration(MixedCasePropertiesConfiguration.class).run(assertProperties( - "mixedcase", (properties) -> assertThat(properties.get("mIxedCase")).isEqualTo("mixed"))); + this.contextRunner.withUserConfiguration(MixedCasePropertiesConfiguration.class) + .run(assertProperties("mixedcase", + (properties) -> assertThat(properties.get("mIxedCase")).isEqualTo("mixed"))); } @Test void descriptorWithSingleLetterProperty() { this.contextRunner.withUserConfiguration(MixedCasePropertiesConfiguration.class) - .run(assertProperties("mixedcase", (properties) -> assertThat(properties.get("z")).isEqualTo("zzz"))); + .run(assertProperties("mixedcase", (properties) -> assertThat(properties.get("z")).isEqualTo("zzz"))); } @Test void descriptorWithSimpleBooleanProperty() { - this.contextRunner.withUserConfiguration(BooleanPropertiesConfiguration.class).run(assertProperties("boolean", - (properties) -> assertThat(properties.get("simpleBoolean")).isEqualTo(true))); + this.contextRunner.withUserConfiguration(BooleanPropertiesConfiguration.class) + .run(assertProperties("boolean", + (properties) -> assertThat(properties.get("simpleBoolean")).isEqualTo(true))); } @Test void descriptorWithMixedBooleanProperty() { - this.contextRunner.withUserConfiguration(BooleanPropertiesConfiguration.class).run(assertProperties("boolean", - (properties) -> assertThat(properties.get("mixedBoolean")).isEqualTo(true))); + this.contextRunner.withUserConfiguration(BooleanPropertiesConfiguration.class) + .run(assertProperties("boolean", + (properties) -> assertThat(properties.get("mixedBoolean")).isEqualTo(true))); } @Test @@ -174,187 +182,193 @@ class ConfigurationPropertiesReportEndpointTests { String configSize = "1MB"; String stringifySize = DataSize.parse(configSize).toString(); this.contextRunner.withUserConfiguration(DataSizePropertiesConfiguration.class) - .withPropertyValues(String.format("data.size=%s", configSize)).run(assertProperties("data", - (properties) -> assertThat(properties.get("size")).isEqualTo(stringifySize), (inputs) -> { - Map size = (Map) inputs.get("size"); - assertThat(size.get("value")).isEqualTo(configSize); - assertThat(size.get("origin")).isEqualTo("\"data.size\" from property source \"test\""); - })); + .withPropertyValues(String.format("data.size=%s", configSize)) + .run(assertProperties("data", (properties) -> assertThat(properties.get("size")).isEqualTo(stringifySize), + (inputs) -> { + Map size = (Map) inputs.get("size"); + assertThat(size.get("value")).isEqualTo(configSize); + assertThat(size.get("origin")).isEqualTo("\"data.size\" from property source \"test\""); + })); } @Test void sanitizeWithDefaultSettings() { this.contextRunner.withUserConfiguration(TestPropertiesConfiguration.class) - .run(assertProperties("test", (properties) -> { - assertThat(properties.get("dbPassword")).isEqualTo("******"); - assertThat(properties.get("myTestProperty")).isEqualTo("654321"); - })); + .run(assertProperties("test", (properties) -> { + assertThat(properties.get("dbPassword")).isEqualTo("******"); + assertThat(properties.get("myTestProperty")).isEqualTo("654321"); + })); } @Test void sanitizeWithCustomKey() { this.contextRunner.withUserConfiguration(TestPropertiesConfiguration.class) - .withPropertyValues("test.keys-to-sanitize=property").run(assertProperties("test", (properties) -> { - assertThat(properties.get("dbPassword")).isEqualTo("123456"); - assertThat(properties.get("myTestProperty")).isEqualTo("******"); - })); + .withPropertyValues("test.keys-to-sanitize=property") + .run(assertProperties("test", (properties) -> { + assertThat(properties.get("dbPassword")).isEqualTo("123456"); + assertThat(properties.get("myTestProperty")).isEqualTo("******"); + })); } @Test void sanitizeWithCustomKeyPattern() { this.contextRunner.withUserConfiguration(TestPropertiesConfiguration.class) - .withPropertyValues("test.keys-to-sanitize=.*pass.*").run(assertProperties("test", (properties) -> { - assertThat(properties.get("dbPassword")).isEqualTo("******"); - assertThat(properties.get("myTestProperty")).isEqualTo("654321"); - })); + .withPropertyValues("test.keys-to-sanitize=.*pass.*") + .run(assertProperties("test", (properties) -> { + assertThat(properties.get("dbPassword")).isEqualTo("******"); + assertThat(properties.get("myTestProperty")).isEqualTo("654321"); + })); } @Test void sanitizeWithCustomPatternUsingCompositeKeys() { this.contextRunner.withUserConfiguration(Gh4415PropertiesConfiguration.class) - .withPropertyValues("test.keys-to-sanitize=.*\\.secrets\\..*,.*\\.hidden\\..*") - .run(assertProperties("gh4415", (properties) -> { - Map secrets = (Map) properties.get("secrets"); - Map hidden = (Map) properties.get("hidden"); - assertThat(secrets.get("mine")).isEqualTo("******"); - assertThat(secrets.get("yours")).isEqualTo("******"); - assertThat(hidden.get("mine")).isEqualTo("******"); - })); + .withPropertyValues("test.keys-to-sanitize=.*\\.secrets\\..*,.*\\.hidden\\..*") + .run(assertProperties("gh4415", (properties) -> { + Map secrets = (Map) properties.get("secrets"); + Map hidden = (Map) properties.get("hidden"); + assertThat(secrets.get("mine")).isEqualTo("******"); + assertThat(secrets.get("yours")).isEqualTo("******"); + assertThat(hidden.get("mine")).isEqualTo("******"); + })); } @Test void sanitizeUriWithSensitiveInfo() { this.contextRunner.withUserConfiguration(SensiblePropertiesConfiguration.class) - .withPropertyValues("sensible.sensitiveUri=http://user:password@localhost:8080") - .run(assertProperties("sensible", (properties) -> assertThat(properties.get("sensitiveUri")) - .isEqualTo("http://user:******@localhost:8080"), (inputs) -> { - Map sensitiveUri = (Map) inputs.get("sensitiveUri"); - assertThat(sensitiveUri.get("value")).isEqualTo("http://user:******@localhost:8080"); - assertThat(sensitiveUri.get("origin")) - .isEqualTo("\"sensible.sensitiveUri\" from property source \"test\""); - })); + .withPropertyValues("sensible.sensitiveUri=http://user:password@localhost:8080") + .run(assertProperties("sensible", (properties) -> assertThat(properties.get("sensitiveUri")) + .isEqualTo("http://user:******@localhost:8080"), (inputs) -> { + Map sensitiveUri = (Map) inputs.get("sensitiveUri"); + assertThat(sensitiveUri.get("value")).isEqualTo("http://user:******@localhost:8080"); + assertThat(sensitiveUri.get("origin")) + .isEqualTo("\"sensible.sensitiveUri\" from property source \"test\""); + })); } @Test void sanitizeUriWithNoPassword() { this.contextRunner.withUserConfiguration(SensiblePropertiesConfiguration.class) - .withPropertyValues("sensible.noPasswordUri=http://user:@localhost:8080") - .run(assertProperties("sensible", (properties) -> assertThat(properties.get("noPasswordUri")) - .isEqualTo("http://user:******@localhost:8080"), (inputs) -> { - Map noPasswordUri = (Map) inputs.get("noPasswordUri"); - assertThat(noPasswordUri.get("value")).isEqualTo("http://user:******@localhost:8080"); - assertThat(noPasswordUri.get("origin")) - .isEqualTo("\"sensible.noPasswordUri\" from property source \"test\""); - })); + .withPropertyValues("sensible.noPasswordUri=http://user:@localhost:8080") + .run(assertProperties("sensible", (properties) -> assertThat(properties.get("noPasswordUri")) + .isEqualTo("http://user:******@localhost:8080"), (inputs) -> { + Map noPasswordUri = (Map) inputs.get("noPasswordUri"); + assertThat(noPasswordUri.get("value")).isEqualTo("http://user:******@localhost:8080"); + assertThat(noPasswordUri.get("origin")) + .isEqualTo("\"sensible.noPasswordUri\" from property source \"test\""); + })); } @Test void sanitizeAddressesFieldContainingMultipleRawSensitiveUris() { this.contextRunner.withUserConfiguration(SensiblePropertiesConfiguration.class) - .run(assertProperties("sensible", (properties) -> assertThat(properties.get("rawSensitiveAddresses")) - .isEqualTo("http://user:******@localhost:8080,http://user2:******@localhost:8082"))); + .run(assertProperties("sensible", (properties) -> assertThat(properties.get("rawSensitiveAddresses")) + .isEqualTo("http://user:******@localhost:8080,http://user2:******@localhost:8082"))); } @Test void sanitizeLists() { this.contextRunner.withUserConfiguration(SensiblePropertiesConfiguration.class) - .withPropertyValues("sensible.listItems[0].some-password=password") - .run(assertProperties("sensible", (properties) -> { - assertThat(properties.get("listItems")).isInstanceOf(List.class); - List list = (List) properties.get("listItems"); - assertThat(list).hasSize(1); - Map item = (Map) list.get(0); - assertThat(item.get("somePassword")).isEqualTo("******"); - }, (inputs) -> { - List list = (List) inputs.get("listItems"); - assertThat(list).hasSize(1); - Map item = (Map) list.get(0); - Map somePassword = (Map) item.get("somePassword"); - assertThat(somePassword.get("value")).isEqualTo("******"); - assertThat(somePassword.get("origin")) - .isEqualTo("\"sensible.listItems[0].some-password\" from property source \"test\""); - })); + .withPropertyValues("sensible.listItems[0].some-password=password") + .run(assertProperties("sensible", (properties) -> { + assertThat(properties.get("listItems")).isInstanceOf(List.class); + List list = (List) properties.get("listItems"); + assertThat(list).hasSize(1); + Map item = (Map) list.get(0); + assertThat(item.get("somePassword")).isEqualTo("******"); + }, (inputs) -> { + List list = (List) inputs.get("listItems"); + assertThat(list).hasSize(1); + Map item = (Map) list.get(0); + Map somePassword = (Map) item.get("somePassword"); + assertThat(somePassword.get("value")).isEqualTo("******"); + assertThat(somePassword.get("origin")) + .isEqualTo("\"sensible.listItems[0].some-password\" from property source \"test\""); + })); } @Test void listsOfListsAreSanitized() { this.contextRunner.withUserConfiguration(SensiblePropertiesConfiguration.class) - .withPropertyValues("sensible.listOfListItems[0][0].some-password=password") - .run(assertProperties("sensible", (properties) -> { - assertThat(properties.get("listOfListItems")).isInstanceOf(List.class); - List> listOfLists = (List>) properties.get("listOfListItems"); - assertThat(listOfLists).hasSize(1); - List list = listOfLists.get(0); - assertThat(list).hasSize(1); - Map item = (Map) list.get(0); - assertThat(item.get("somePassword")).isEqualTo("******"); - }, (inputs) -> { - assertThat(inputs.get("listOfListItems")).isInstanceOf(List.class); - List> listOfLists = (List>) inputs.get("listOfListItems"); - assertThat(listOfLists).hasSize(1); - List list = listOfLists.get(0); - assertThat(list).hasSize(1); - Map item = (Map) list.get(0); - Map somePassword = (Map) item.get("somePassword"); - assertThat(somePassword.get("value")).isEqualTo("******"); - assertThat(somePassword.get("origin")).isEqualTo( - "\"sensible.listOfListItems[0][0].some-password\" from property source \"test\""); - })); + .withPropertyValues("sensible.listOfListItems[0][0].some-password=password") + .run(assertProperties("sensible", (properties) -> { + assertThat(properties.get("listOfListItems")).isInstanceOf(List.class); + List> listOfLists = (List>) properties.get("listOfListItems"); + assertThat(listOfLists).hasSize(1); + List list = listOfLists.get(0); + assertThat(list).hasSize(1); + Map item = (Map) list.get(0); + assertThat(item.get("somePassword")).isEqualTo("******"); + }, (inputs) -> { + assertThat(inputs.get("listOfListItems")).isInstanceOf(List.class); + List> listOfLists = (List>) inputs.get("listOfListItems"); + assertThat(listOfLists).hasSize(1); + List list = listOfLists.get(0); + assertThat(list).hasSize(1); + Map item = (Map) list.get(0); + Map somePassword = (Map) item.get("somePassword"); + assertThat(somePassword.get("value")).isEqualTo("******"); + assertThat(somePassword.get("origin")) + .isEqualTo("\"sensible.listOfListItems[0][0].some-password\" from property source \"test\""); + })); } @Test void sanitizeWithCustomSanitizingFunction() { - new ApplicationContextRunner().withUserConfiguration(CustomSanitizingEndpointConfig.class, - SanitizingFunctionConfiguration.class, TestPropertiesConfiguration.class) - .run(assertProperties("test", (properties) -> { - assertThat(properties.get("dbPassword")).isEqualTo("$$$"); - assertThat(properties.get("myTestProperty")).isEqualTo("$$$"); - })); + new ApplicationContextRunner() + .withUserConfiguration(CustomSanitizingEndpointConfig.class, SanitizingFunctionConfiguration.class, + TestPropertiesConfiguration.class) + .run(assertProperties("test", (properties) -> { + assertThat(properties.get("dbPassword")).isEqualTo("$$$"); + assertThat(properties.get("myTestProperty")).isEqualTo("$$$"); + })); } @Test void sanitizeWithCustomPropertySourceBasedSanitizingFunction() { new ApplicationContextRunner() - .withUserConfiguration(CustomSanitizingEndpointConfig.class, - PropertySourceBasedSanitizingFunctionConfiguration.class, TestPropertiesConfiguration.class) - .withPropertyValues("test.my-test-property=abcde").run(assertProperties("test", (properties) -> { - assertThat(properties.get("dbPassword")).isEqualTo("******"); - assertThat(properties.get("myTestProperty")).isEqualTo("$$$"); - })); + .withUserConfiguration(CustomSanitizingEndpointConfig.class, + PropertySourceBasedSanitizingFunctionConfiguration.class, TestPropertiesConfiguration.class) + .withPropertyValues("test.my-test-property=abcde") + .run(assertProperties("test", (properties) -> { + assertThat(properties.get("dbPassword")).isEqualTo("******"); + assertThat(properties.get("myTestProperty")).isEqualTo("$$$"); + })); } @Test void sanitizeListsWithCustomSanitizingFunction() { new ApplicationContextRunner() - .withUserConfiguration(CustomSanitizingEndpointConfig.class, SanitizingFunctionConfiguration.class, - SensiblePropertiesConfiguration.class) - .withPropertyValues("sensible.listItems[0].custom=my-value") - .run(assertProperties("sensible", (properties) -> { - assertThat(properties.get("listItems")).isInstanceOf(List.class); - List list = (List) properties.get("listItems"); - assertThat(list).hasSize(1); - Map item = (Map) list.get(0); - assertThat(item.get("custom")).isEqualTo("$$$"); - }, (inputs) -> { - List list = (List) inputs.get("listItems"); - assertThat(list).hasSize(1); - Map item = (Map) list.get(0); - Map somePassword = (Map) item.get("custom"); - assertThat(somePassword.get("value")).isEqualTo("$$$"); - assertThat(somePassword.get("origin")) - .isEqualTo("\"sensible.listItems[0].custom\" from property source \"test\""); - })); + .withUserConfiguration(CustomSanitizingEndpointConfig.class, SanitizingFunctionConfiguration.class, + SensiblePropertiesConfiguration.class) + .withPropertyValues("sensible.listItems[0].custom=my-value") + .run(assertProperties("sensible", (properties) -> { + assertThat(properties.get("listItems")).isInstanceOf(List.class); + List list = (List) properties.get("listItems"); + assertThat(list).hasSize(1); + Map item = (Map) list.get(0); + assertThat(item.get("custom")).isEqualTo("$$$"); + }, (inputs) -> { + List list = (List) inputs.get("listItems"); + assertThat(list).hasSize(1); + Map item = (Map) list.get(0); + Map somePassword = (Map) item.get("custom"); + assertThat(somePassword.get("value")).isEqualTo("$$$"); + assertThat(somePassword.get("origin")) + .isEqualTo("\"sensible.listItems[0].custom\" from property source \"test\""); + })); } @Test void originParents() { this.contextRunner.withUserConfiguration(SensiblePropertiesConfiguration.class) - .withInitializer(this::initializeOriginParents).run(assertProperties("sensible", (properties) -> { - }, (inputs) -> { - Map stringInputs = (Map) inputs.get("string"); - String[] originParents = (String[]) stringInputs.get("originParents"); - assertThat(originParents).containsExactly("spring", "boot"); - })); + .withInitializer(this::initializeOriginParents) + .run(assertProperties("sensible", (properties) -> { + }, (inputs) -> { + Map stringInputs = (Map) inputs.get("string"); + String[] originParents = (String[]) stringInputs.get("originParents"); + assertThat(originParents).containsExactly("spring", "boot"); + })); } private void initializeOriginParents(ConfigurableApplicationContext context) { @@ -373,11 +387,15 @@ class ConfigurationPropertiesReportEndpointTests { Consumer> properties, Consumer> inputs) { return (context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); - ContextConfigurationProperties allProperties = endpoint.configurationProperties().getContexts() - .get(context.getId()); - Optional key = allProperties.getBeans().keySet().stream() - .filter((id) -> findIdFromPrefix(prefix, id)).findAny(); + .getBean(ConfigurationPropertiesReportEndpoint.class); + ContextConfigurationProperties allProperties = endpoint.configurationProperties() + .getContexts() + .get(context.getId()); + Optional key = allProperties.getBeans() + .keySet() + .stream() + .filter((id) -> findIdFromPrefix(prefix, id)) + .findAny(); assertThat(key).describedAs("No configuration properties with prefix '%s' found", prefix).isPresent(); ConfigurationPropertiesBeanDescriptor descriptor = allProperties.getBeans().get(key.get()); assertThat(descriptor.getPrefix()).isEqualTo(prefix); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebIntegrationTests.java index 80b6b16da4..a5885b21a9 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,22 +48,48 @@ class ConfigurationPropertiesReportEndpointWebIntegrationTests { @WebEndpointTest void noFilters() { - this.client.get().uri("/actuator/configprops").exchange().expectStatus().isOk().expectBody() - .jsonPath("$..beans[*]").value(hasSize(greaterThanOrEqualTo(2))).jsonPath("$..beans['fooDotCom']") - .exists().jsonPath("$..beans['barDotCom']").exists(); + this.client.get() + .uri("/actuator/configprops") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$..beans[*]") + .value(hasSize(greaterThanOrEqualTo(2))) + .jsonPath("$..beans['fooDotCom']") + .exists() + .jsonPath("$..beans['barDotCom']") + .exists(); } @WebEndpointTest void filterByExactPrefix() { - this.client.get().uri("/actuator/configprops/com.foo").exchange().expectStatus().isOk().expectBody() - .jsonPath("$..beans[*]").value(hasSize(1)).jsonPath("$..beans['fooDotCom']").exists(); + this.client.get() + .uri("/actuator/configprops/com.foo") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$..beans[*]") + .value(hasSize(1)) + .jsonPath("$..beans['fooDotCom']") + .exists(); } @WebEndpointTest void filterByGeneralPrefix() { - this.client.get().uri("/actuator/configprops/com.").exchange().expectStatus().isOk().expectBody() - .jsonPath("$..beans[*]").value(hasSize(2)).jsonPath("$..beans['fooDotCom']").exists() - .jsonPath("$..beans['barDotCom']").exists(); + this.client.get() + .uri("/actuator/configprops/com.") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$..beans[*]") + .value(hasSize(2)) + .jsonPath("$..beans['fooDotCom']") + .exists() + .jsonPath("$..beans['barDotCom']") + .exists(); } @WebEndpointTest diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchReactiveHealthIndicatorTests.java index c1e56b7e56..8e16ac04d1 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchReactiveHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ class ElasticsearchReactiveHealthIndicatorTests { this.server = new MockWebServer(); this.server.start(); ReactiveElasticsearchClient client = DefaultReactiveElasticsearchClient - .create(ClientConfiguration.create(this.server.getHostName() + ":" + this.server.getPort())); + .create(ClientConfiguration.create(this.server.getHostName() + ":" + this.server.getPort())); this.healthIndicator = new ElasticsearchReactiveHealthIndicator(client); } @@ -84,7 +84,7 @@ class ElasticsearchReactiveHealthIndicatorTests { Health health = this.healthIndicator.health().block(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); assertThat(health.getDetails().get("error")).asString() - .contains("org.springframework.data.elasticsearch.client.NoReachableHostException"); + .contains("org.springframework.data.elasticsearch.client.NoReachableHostException"); } @Test @@ -121,8 +121,8 @@ class ElasticsearchReactiveHealthIndicatorTests { // to "/" this.server.enqueue(new MockResponse()); MockResponse mockResponse = new MockResponse().setResponseCode(HttpStatus.valueOf(responseCode).value()) - .setBody(createJsonResult(responseCode, status)) - .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + .setBody(createJsonResult(responseCode, status)) + .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); this.server.enqueue(mockResponse); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EndpointIdTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EndpointIdTests.java index 3f272ad1f9..71f2cc0c2b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EndpointIdTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EndpointIdTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ class EndpointIdTests { @Test void ofWhenNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of(null)) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test @@ -48,31 +48,31 @@ class EndpointIdTests { @Test void ofWhenContainsSlashThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of("foo/bar")) - .withMessage("Value must only contain valid chars"); + .withMessage("Value must only contain valid chars"); } @Test void ofWhenContainsBackslashThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of("foo\\bar")) - .withMessage("Value must only contain valid chars"); + .withMessage("Value must only contain valid chars"); } @Test void ofWhenHasBadCharThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of("foo!bar")) - .withMessage("Value must only contain valid chars"); + .withMessage("Value must only contain valid chars"); } @Test void ofWhenStartsWithNumberThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of("1foo")) - .withMessage("Value must not start with a number"); + .withMessage("Value must not start with a number"); } @Test void ofWhenStartsWithUppercaseLetterThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of("Foo")) - .withMessage("Value must not start with an uppercase letter"); + .withMessage("Value must not start with an uppercase letter"); } @Test @@ -96,7 +96,7 @@ class EndpointIdTests { EndpointId.resetLoggedWarnings(); EndpointId.of("foo-bar"); assertThat(output) - .contains("Endpoint ID 'foo-bar' contains invalid characters, please migrate to a valid format"); + .contains("Endpoint ID 'foo-bar' contains invalid characters, please migrate to a valid format"); } @Test @@ -136,8 +136,12 @@ class EndpointIdTests { EndpointId five = EndpointId.of("barfoo1"); EndpointId six = EndpointId.of("foobar2"); assertThat(one.hashCode()).isEqualTo(two.hashCode()); - assertThat(one).isEqualTo(one).isEqualTo(two).isEqualTo(three).isEqualTo(four).isNotEqualTo(five) - .isNotEqualTo(six); + assertThat(one).isEqualTo(one) + .isEqualTo(two) + .isEqualTo(three) + .isEqualTo(four) + .isNotEqualTo(five) + .isNotEqualTo(six); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/InvocationContextTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/InvocationContextTests.java index e4465feb48..84f2a83279 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/InvocationContextTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/InvocationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,13 +45,13 @@ class InvocationContextTests { @Test void createWhenSecurityContextIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new InvocationContext(null, this.arguments)) - .withMessage("SecurityContext must not be null"); + .withMessage("SecurityContext must not be null"); } @Test void createWhenArgumentsIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new InvocationContext(this.securityContext, null)) - .withMessage("Arguments must not be null"); + .withMessage("Arguments must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ProducibleOperationArgumentResolverTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ProducibleOperationArgumentResolverTests.java index a63dd31640..138737e5e0 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ProducibleOperationArgumentResolverTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ProducibleOperationArgumentResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,9 +67,9 @@ class ProducibleOperationArgumentResolverTests { @Test void whenSingleValueIsAcceptableThenMatchingEnumValueIsReturned() { assertThat(new ProducibleOperationArgumentResolver(acceptHeader(V2_JSON)).resolve(ApiVersion.class)) - .isEqualTo(ApiVersion.V2); + .isEqualTo(ApiVersion.V2); assertThat(new ProducibleOperationArgumentResolver(acceptHeader(V3_JSON)).resolve(ApiVersion.class)) - .isEqualTo(ApiVersion.V3); + .isEqualTo(ApiVersion.V3); } @Test @@ -90,7 +90,7 @@ class ProducibleOperationArgumentResolverTests { @Test void whenMultipleDefaultsThrowsException() { assertThatIllegalStateException().isThrownBy(() -> resolve(acceptHeader("one/one"), WithMultipleDefaults.class)) - .withMessageContaining("Multiple default values"); + .withMessageContaining("Multiple default values"); } private Supplier> acceptHeader(String... types) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java index a29771f058..c3daabe343 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -127,7 +127,7 @@ class SanitizerTests { void uriWithSingleValueWithPasswordShouldBeSanitized(String key) { Sanitizer sanitizer = new Sanitizer(); assertThat(sanitizer.sanitize(key, "http://user:password@localhost:8080")) - .isEqualTo("http://user:******@localhost:8080"); + .isEqualTo("http://user:******@localhost:8080"); } @ParameterizedTest(name = "key = {0}") @@ -135,7 +135,7 @@ class SanitizerTests { void uriWithNonAlphaSchemeCharactersAndSingleValueWithPasswordShouldBeSanitized(String key) { Sanitizer sanitizer = new Sanitizer(); assertThat(sanitizer.sanitize(key, "s-ch3m.+-e://user:password@localhost:8080")) - .isEqualTo("s-ch3m.+-e://user:******@localhost:8080"); + .isEqualTo("s-ch3m.+-e://user:******@localhost:8080"); } @ParameterizedTest(name = "key = {0}") @@ -151,7 +151,7 @@ class SanitizerTests { void uriWithSingleValueWithPasswordMatchingOtherPartsOfStringShouldBeSanitized(String key) { Sanitizer sanitizer = new Sanitizer(); assertThat(sanitizer.sanitize(key, "http://user://@localhost:8080")) - .isEqualTo("http://user:******@localhost:8080"); + .isEqualTo("http://user:******@localhost:8080"); } @ParameterizedTest(name = "key = {0}") @@ -160,7 +160,7 @@ class SanitizerTests { Sanitizer sanitizer = new Sanitizer(); assertThat( sanitizer.sanitize(key, "http://user1:password1@localhost:8080,http://user2:password2@localhost:8082")) - .isEqualTo("http://user1:******@localhost:8080,http://user2:******@localhost:8082"); + .isEqualTo("http://user1:******@localhost:8080,http://user2:******@localhost:8082"); } @ParameterizedTest(name = "key = {0}") @@ -168,7 +168,7 @@ class SanitizerTests { void uriWithMultipleValuesNoneWithPasswordShouldHaveNoneSanitized(String key) { Sanitizer sanitizer = new Sanitizer(); assertThat(sanitizer.sanitize(key, "http://user@localhost:8080,http://localhost:8082")) - .isEqualTo("http://user@localhost:8080,http://localhost:8082"); + .isEqualTo("http://user@localhost:8080,http://localhost:8082"); } @ParameterizedTest(name = "key = {0}") @@ -176,8 +176,8 @@ class SanitizerTests { void uriWithMultipleValuesSomeWithPasswordShouldHaveThoseSanitized(String key) { Sanitizer sanitizer = new Sanitizer(); assertThat(sanitizer.sanitize(key, - "http://user1:password1@localhost:8080,http://user2@localhost:8082,http://localhost:8083")).isEqualTo( - "http://user1:******@localhost:8080,http://user2@localhost:8082,http://localhost:8083"); + "http://user1:password1@localhost:8080,http://user2@localhost:8082,http://localhost:8083")) + .isEqualTo("http://user1:******@localhost:8080,http://user2@localhost:8082,http://localhost:8083"); } @ParameterizedTest(name = "key = {0}") @@ -185,7 +185,7 @@ class SanitizerTests { void uriWithMultipleValuesWithPasswordMatchingOtherPartsOfStringShouldBeSanitized(String key) { Sanitizer sanitizer = new Sanitizer(); assertThat(sanitizer.sanitize(key, "http://user1://@localhost:8080,http://user2://@localhost:8082")) - .isEqualTo("http://user1:******@localhost:8080,http://user2:******@localhost:8082"); + .isEqualTo("http://user1:******@localhost:8080,http://user2:******@localhost:8082"); } @ParameterizedTest(name = "key = {0}") @@ -193,15 +193,15 @@ class SanitizerTests { void uriKeyWithUserProvidedListLiteralShouldBeSanitized(String key) { Sanitizer sanitizer = new Sanitizer(); assertThat(sanitizer.sanitize(key, "[amqp://username:password@host/]")) - .isEqualTo("[amqp://username:******@host/]"); + .isEqualTo("[amqp://username:******@host/]"); assertThat(sanitizer.sanitize(key, - "[http://user1:password1@localhost:8080,http://user2@localhost:8082,http://localhost:8083]")).isEqualTo( - "[http://user1:******@localhost:8080,http://user2@localhost:8082,http://localhost:8083]"); + "[http://user1:password1@localhost:8080,http://user2@localhost:8082,http://localhost:8083]")) + .isEqualTo("[http://user1:******@localhost:8080,http://user2@localhost:8082,http://localhost:8083]"); assertThat(sanitizer.sanitize(key, "[http://user1:password1@localhost:8080,http://user2:password2@localhost:8082]")) - .isEqualTo("[http://user1:******@localhost:8080,http://user2:******@localhost:8082]"); + .isEqualTo("[http://user1:******@localhost:8080,http://user2:******@localhost:8082]"); assertThat(sanitizer.sanitize(key, "[http://user1@localhost:8080,http://user2@localhost:8082]")) - .isEqualTo("[http://user1@localhost:8080,http://user2@localhost:8082]"); + .isEqualTo("[http://user1@localhost:8080,http://user2@localhost:8082]"); } private static Stream matchingUriUserInfoKeys() { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java index ca17253b3a..3227e787f4 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,8 @@ class DiscoveredOperationMethodTests { void createWhenAnnotationAttributesIsNullShouldThrowException() { Method method = ReflectionUtils.findMethod(getClass(), "example"); assertThatIllegalArgumentException() - .isThrownBy(() -> new DiscoveredOperationMethod(method, OperationType.READ, null)) - .withMessageContaining("AnnotationAttributes must not be null"); + .isThrownBy(() -> new DiscoveredOperationMethod(method, OperationType.READ, null)) + .withMessageContaining("AnnotationAttributes must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java index 1f08a91468..c619700eab 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class DiscovererEndpointFilterTests { @Test void createWhenDiscovererIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new TestDiscovererEndpointFilter(null)) - .withMessageContaining("Discoverer must not be null"); + .withMessageContaining("Discoverer must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java index fde226e419..14ec74f339 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,33 +71,33 @@ class EndpointDiscovererTests { @Test void createWhenApplicationContextIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestEndpointDiscoverer(null, mock(ParameterValueMapper.class), - Collections.emptyList(), Collections.emptyList())) - .withMessageContaining("ApplicationContext must not be null"); + .isThrownBy(() -> new TestEndpointDiscoverer(null, mock(ParameterValueMapper.class), + Collections.emptyList(), Collections.emptyList())) + .withMessageContaining("ApplicationContext must not be null"); } @Test void createWhenParameterValueMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestEndpointDiscoverer(mock(ApplicationContext.class), null, - Collections.emptyList(), Collections.emptyList())) - .withMessageContaining("ParameterValueMapper must not be null"); + .isThrownBy(() -> new TestEndpointDiscoverer(mock(ApplicationContext.class), null, Collections.emptyList(), + Collections.emptyList())) + .withMessageContaining("ParameterValueMapper must not be null"); } @Test void createWhenInvokerAdvisorsIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestEndpointDiscoverer(mock(ApplicationContext.class), - mock(ParameterValueMapper.class), null, Collections.emptyList())) - .withMessageContaining("InvokerAdvisors must not be null"); + .isThrownBy(() -> new TestEndpointDiscoverer(mock(ApplicationContext.class), + mock(ParameterValueMapper.class), null, Collections.emptyList())) + .withMessageContaining("InvokerAdvisors must not be null"); } @Test void createWhenFiltersIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestEndpointDiscoverer(mock(ApplicationContext.class), - mock(ParameterValueMapper.class), Collections.emptyList(), null)) - .withMessageContaining("Filters must not be null"); + .isThrownBy(() -> new TestEndpointDiscoverer(mock(ApplicationContext.class), + mock(ParameterValueMapper.class), Collections.emptyList(), null)) + .withMessageContaining("Filters must not be null"); } @Test @@ -139,8 +139,8 @@ class EndpointDiscovererTests { void getEndpointsWhenTwoEndpointsHaveTheSameIdShouldThrowException() { load(ClashingEndpointConfiguration.class, (context) -> assertThatIllegalStateException() - .isThrownBy(new TestEndpointDiscoverer(context)::getEndpoints) - .withMessageContaining("Found two endpoints with the id 'test': ")); + .isThrownBy(new TestEndpointDiscoverer(context)::getEndpoints) + .withMessageContaining("Found two endpoints with the id 'test': ")); } @Test @@ -159,8 +159,9 @@ class EndpointDiscovererTests { Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); Map operations = mapOperations(endpoints.get(EndpointId.of("test"))); - operations.values().forEach( - (operation) -> assertThat(operation.getInvoker()).isNotInstanceOf(CachingOperationInvoker.class)); + operations.values() + .forEach((operation) -> assertThat(operation.getInvoker()) + .isNotInstanceOf(CachingOperationInvoker.class)); }); } @@ -172,8 +173,9 @@ class EndpointDiscovererTests { Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); Map operations = mapOperations(endpoints.get(EndpointId.of("test"))); - operations.values().forEach( - (operation) -> assertThat(operation.getInvoker()).isNotInstanceOf(CachingOperationInvoker.class)); + operations.values() + .forEach((operation) -> assertThat(operation.getInvoker()) + .isNotInstanceOf(CachingOperationInvoker.class)); }); } @@ -188,7 +190,7 @@ class EndpointDiscovererTests { TestOperation getAll = operations.get(findTestEndpointMethod("getAll")); TestOperation getOne = operations.get(findTestEndpointMethod("getOne", String.class)); TestOperation update = operations - .get(ReflectionUtils.findMethod(TestEndpoint.class, "update", String.class, String.class)); + .get(ReflectionUtils.findMethod(TestEndpoint.class, "update", String.class, String.class)); assertThat(((CachingOperationInvoker) getAll.getInvoker()).getTimeToLive()).isEqualTo(500); assertThat(getOne.getInvoker()).isNotInstanceOf(CachingOperationInvoker.class); assertThat(update.getInvoker()).isNotInstanceOf(CachingOperationInvoker.class); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java index 31c07a45cd..3ba4df37a9 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java @@ -58,12 +58,12 @@ class ConversionServiceParameterValueMapperTests { given(conversionService.convert(any(), any())).willThrow(error); ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper(conversionService); assertThatExceptionOfType(ParameterMappingException.class) - .isThrownBy(() -> mapper.mapParameterValue(new TestOperationParameter(Integer.class), "123")) - .satisfies((ex) -> { - assertThat(ex.getValue()).isEqualTo("123"); - assertThat(ex.getParameter().getType()).isEqualTo(Integer.class); - assertThat(ex.getCause()).isEqualTo(error); - }); + .isThrownBy(() -> mapper.mapParameterValue(new TestOperationParameter(Integer.class), "123")) + .satisfies((ex) -> { + assertThat(ex.getValue()).isEqualTo("123"); + assertThat(ex.getParameter().getType()).isEqualTo(Integer.class); + assertThat(ex.getCause()).isEqualTo(error); + }); } @Test @@ -79,7 +79,7 @@ class ConversionServiceParameterValueMapperTests { ConversionService conversionService = new DefaultConversionService(); ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper(conversionService); assertThatExceptionOfType(ParameterMappingException.class).isThrownBy(() -> mapper - .mapParameterValue(new TestOperationParameter(OffsetDateTime.class), "2011-12-03T10:15:30+01:00")); + .mapParameterValue(new TestOperationParameter(OffsetDateTime.class), "2011-12-03T10:15:30+01:00")); } static class TestOperationParameter implements OperationParameter { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java index f18c92b8ee..82088fddde 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,22 +51,21 @@ class OperationMethodParametersTests { @Test void createWhenMethodIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new OperationMethodParameters(null, mock(ParameterNameDiscoverer.class))) - .withMessageContaining("Method must not be null"); + .isThrownBy(() -> new OperationMethodParameters(null, mock(ParameterNameDiscoverer.class))) + .withMessageContaining("Method must not be null"); } @Test void createWhenParameterNameDiscovererIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new OperationMethodParameters(this.exampleMethod, null)) - .withMessageContaining("ParameterNameDiscoverer must not be null"); + .withMessageContaining("ParameterNameDiscoverer must not be null"); } @Test void createWhenParameterNameDiscovererReturnsNullShouldThrowException() { assertThatIllegalStateException() - .isThrownBy( - () -> new OperationMethodParameters(this.exampleMethod, mock(ParameterNameDiscoverer.class))) - .withMessageContaining("Failed to extract parameter names"); + .isThrownBy(() -> new OperationMethodParameters(this.exampleMethod, mock(ParameterNameDiscoverer.class))) + .withMessageContaining("Failed to extract parameter names"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java index 577e3e63a4..2d64083998 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,13 +39,13 @@ class OperationMethodTests { @Test void createWhenMethodIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new OperationMethod(null, OperationType.READ)) - .withMessageContaining("Method must not be null"); + .withMessageContaining("Method must not be null"); } @Test void createWhenOperationTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new OperationMethod(this.exampleMethod, null)) - .withMessageContaining("OperationType must not be null"); + .withMessageContaining("OperationType must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java index 25aa5869ad..9e7cab081a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,22 +59,22 @@ class ReflectiveOperationInvokerTests { @Test void createWhenTargetIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ReflectiveOperationInvoker(null, this.operationMethod, this.parameterValueMapper)) - .withMessageContaining("Target must not be null"); + .isThrownBy(() -> new ReflectiveOperationInvoker(null, this.operationMethod, this.parameterValueMapper)) + .withMessageContaining("Target must not be null"); } @Test void createWhenOperationMethodIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ReflectiveOperationInvoker(this.target, null, this.parameterValueMapper)) - .withMessageContaining("OperationMethod must not be null"); + .isThrownBy(() -> new ReflectiveOperationInvoker(this.target, null, this.parameterValueMapper)) + .withMessageContaining("OperationMethod must not be null"); } @Test void createWhenParameterValueMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ReflectiveOperationInvoker(this.target, this.operationMethod, null)) - .withMessageContaining("ParameterValueMapper must not be null"); + .isThrownBy(() -> new ReflectiveOperationInvoker(this.target, this.operationMethod, null)) + .withMessageContaining("ParameterValueMapper must not be null"); } @Test @@ -82,7 +82,7 @@ class ReflectiveOperationInvokerTests { ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, this.operationMethod, this.parameterValueMapper); Object result = invoker - .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", "boot"))); + .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", "boot"))); assertThat(result).isEqualTo("toob"); } @@ -91,7 +91,7 @@ class ReflectiveOperationInvokerTests { ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, this.operationMethod, this.parameterValueMapper); assertThatExceptionOfType(MissingParametersException.class).isThrownBy(() -> invoker - .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", null)))); + .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", null)))); } @Test @@ -101,7 +101,7 @@ class ReflectiveOperationInvokerTests { ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, operationMethod, this.parameterValueMapper); Object result = invoker - .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", null))); + .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", null))); assertThat(result).isEqualTo("llun"); } @@ -110,7 +110,7 @@ class ReflectiveOperationInvokerTests { ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, this.operationMethod, this.parameterValueMapper); Object result = invoker - .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", 1234))); + .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", 1234))); assertThat(result).isEqualTo("4321"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java index 27e242874d..19efb8f682 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,8 +57,8 @@ class CachingOperationInvokerTests { @Test void createInstanceWithTtlSetToZero() { assertThatIllegalArgumentException() - .isThrownBy(() -> new CachingOperationInvoker(mock(OperationInvoker.class), 0)) - .withMessageContaining("TimeToLive"); + .isThrownBy(() -> new CachingOperationInvoker(mock(OperationInvoker.class), 0)) + .withMessageContaining("TimeToLive"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java index 227229154c..86356373db 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,15 +61,15 @@ class EndpointMBeanTests { @Test void createWhenResponseMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new EndpointMBean(null, null, mock(ExposableJmxEndpoint.class))) - .withMessageContaining("ResponseMapper must not be null"); + .isThrownBy(() -> new EndpointMBean(null, null, mock(ExposableJmxEndpoint.class))) + .withMessageContaining("ResponseMapper must not be null"); } @Test void createWhenEndpointIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new EndpointMBean(mock(JmxOperationResponseMapper.class), null, null)) - .withMessageContaining("Endpoint must not be null"); + .isThrownBy(() -> new EndpointMBean(mock(JmxOperationResponseMapper.class), null, null)) + .withMessageContaining("Endpoint must not be null"); } @Test @@ -93,8 +93,9 @@ class EndpointMBeanTests { })); EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint); assertThatExceptionOfType(MBeanException.class) - .isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE)) - .withCauseInstanceOf(IllegalStateException.class).withMessageContaining("test failure"); + .isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE)) + .withCauseInstanceOf(IllegalStateException.class) + .withMessageContaining("test failure"); } @@ -105,17 +106,18 @@ class EndpointMBeanTests { })); EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint); assertThatExceptionOfType(MBeanException.class) - .isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE)) - .withCauseInstanceOf(UnsupportedOperationException.class).withMessageContaining("test failure"); + .isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE)) + .withCauseInstanceOf(UnsupportedOperationException.class) + .withMessageContaining("test failure"); } @Test void invokeWhenActionNameIsNotAnOperationShouldThrowException() { EndpointMBean bean = createEndpointMBean(); assertThatExceptionOfType(ReflectionException.class) - .isThrownBy(() -> bean.invoke("missingOperation", NO_PARAMS, NO_SIGNATURE)) - .withCauseInstanceOf(IllegalArgumentException.class) - .withMessageContaining("no operation named missingOperation"); + .isThrownBy(() -> bean.invoke("missingOperation", NO_PARAMS, NO_SIGNATURE)) + .withCauseInstanceOf(IllegalArgumentException.class) + .withMessageContaining("no operation named missingOperation"); } @Test @@ -143,8 +145,9 @@ class EndpointMBeanTests { TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint(operation); EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint); assertThatExceptionOfType(ReflectionException.class) - .isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE)) - .withRootCauseInstanceOf(IllegalArgumentException.class).withMessageContaining("test failure"); + .isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE)) + .withRootCauseInstanceOf(IllegalArgumentException.class) + .withMessageContaining("test failure"); } @Test @@ -178,15 +181,15 @@ class EndpointMBeanTests { void getAttributeShouldThrowException() { EndpointMBean bean = createEndpointMBean(); assertThatExceptionOfType(AttributeNotFoundException.class).isThrownBy(() -> bean.getAttribute("test")) - .withMessageContaining("EndpointMBeans do not support attributes"); + .withMessageContaining("EndpointMBeans do not support attributes"); } @Test void setAttributeShouldThrowException() { EndpointMBean bean = createEndpointMBean(); assertThatExceptionOfType(AttributeNotFoundException.class) - .isThrownBy(() -> bean.setAttribute(new Attribute("test", "test"))) - .withMessageContaining("EndpointMBeans do not support attributes"); + .isThrownBy(() -> bean.setAttribute(new Attribute("test", "test"))) + .withMessageContaining("EndpointMBeans do not support attributes"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java index b4765c6882..55c6605bbd 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,31 +81,32 @@ class JmxEndpointExporterTests { @Test void createWhenMBeanServerIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new JmxEndpointExporter(null, this.objectNameFactory, this.responseMapper, this.endpoints)) - .withMessageContaining("MBeanServer must not be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new JmxEndpointExporter(null, this.objectNameFactory, this.responseMapper, this.endpoints)) + .withMessageContaining("MBeanServer must not be null"); } @Test void createWhenObjectNameFactoryIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new JmxEndpointExporter(this.mBeanServer, null, this.responseMapper, this.endpoints)) - .withMessageContaining("ObjectNameFactory must not be null"); + .isThrownBy(() -> new JmxEndpointExporter(this.mBeanServer, null, this.responseMapper, this.endpoints)) + .withMessageContaining("ObjectNameFactory must not be null"); } @Test void createWhenResponseMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, null, this.endpoints)) - .withMessageContaining("ResponseMapper must not be null"); + .isThrownBy(() -> new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, null, this.endpoints)) + .withMessageContaining("ResponseMapper must not be null"); } @Test void createWhenEndpointsIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, this.responseMapper, null)) - .withMessageContaining("Endpoints must not be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, this.responseMapper, null)) + .withMessageContaining("Endpoints must not be null"); } @Test @@ -127,19 +128,19 @@ class JmxEndpointExporterTests { @Test void registerWhenObjectNameIsMalformedShouldThrowException() throws Exception { given(this.objectNameFactory.getObjectName(any(ExposableJmxEndpoint.class))) - .willThrow(MalformedObjectNameException.class); + .willThrow(MalformedObjectNameException.class); this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); assertThatIllegalStateException().isThrownBy(this.exporter::afterPropertiesSet) - .withMessageContaining("Invalid ObjectName for endpoint 'test'"); + .withMessageContaining("Invalid ObjectName for endpoint 'test'"); } @Test void registerWhenRegistrationFailsShouldThrowException() throws Exception { given(this.mBeanServer.registerMBean(any(), any(ObjectName.class))) - .willThrow(new MBeanRegistrationException(new RuntimeException())); + .willThrow(new MBeanRegistrationException(new RuntimeException())); this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); assertThatExceptionOfType(MBeanExportException.class).isThrownBy(this.exporter::afterPropertiesSet) - .withMessageContaining("Failed to register MBean for endpoint 'test"); + .withMessageContaining("Failed to register MBean for endpoint 'test"); } @Test @@ -164,9 +165,9 @@ class JmxEndpointExporterTests { this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); this.exporter.afterPropertiesSet(); willThrow(new MBeanRegistrationException(new RuntimeException())).given(this.mBeanServer) - .unregisterMBean(any(ObjectName.class)); + .unregisterMBean(any(ObjectName.class)); assertThatExceptionOfType(JmxException.class).isThrownBy(() -> this.exporter.destroy()) - .withMessageContaining("Failed to unregister MBean with ObjectName 'boot"); + .withMessageContaining("Failed to unregister MBean with ObjectName 'boot"); } /** diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactoryTests.java index fbb349313f..60c3aedfd1 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,21 +61,21 @@ class MBeanInfoFactoryTests { @Test void getMBeanInfoWhenReadOperationShouldHaveInfoImpact() { MBeanInfo info = this.factory - .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.READ))); + .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.READ))); assertThat(info.getOperations()[0].getImpact()).isEqualTo(MBeanOperationInfo.INFO); } @Test void getMBeanInfoWhenWriteOperationShouldHaveActionImpact() { MBeanInfo info = this.factory - .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.WRITE))); + .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.WRITE))); assertThat(info.getOperations()[0].getImpact()).isEqualTo(MBeanOperationInfo.ACTION); } @Test void getMBeanInfoWhenDeleteOperationShouldHaveActionImpact() { MBeanInfo info = this.factory - .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.DELETE))); + .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.DELETE))); assertThat(info.getOperations()[0].getImpact()).isEqualTo(MBeanOperationInfo.ACTION); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java index 3fc4eaa9a3..9e822819bd 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -105,8 +105,9 @@ class JmxEndpointDiscovererTests { @Test void getEndpointsWhenJmxExtensionIsMissingEndpointShouldThrowException() { load(TestJmxEndpointExtension.class, (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Invalid extension 'jmxEndpointDiscovererTests.TestJmxEndpointExtension': no endpoint found with id 'test'")); + .isThrownBy(discoverer::getEndpoints) + .withMessageContaining( + "Invalid extension 'jmxEndpointDiscovererTests.TestJmxEndpointExtension': no endpoint found with id 'test'")); } @Test @@ -169,36 +170,40 @@ class JmxEndpointDiscovererTests { @Test void getEndpointsWhenTwoExtensionsHaveTheSameEndpointTypeShouldThrowException() { load(ClashingJmxEndpointConfiguration.class, (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Found multiple extensions for the endpoint bean testEndpoint (testExtensionOne, testExtensionTwo)")); + .isThrownBy(discoverer::getEndpoints) + .withMessageContaining( + "Found multiple extensions for the endpoint bean testEndpoint (testExtensionOne, testExtensionTwo)")); } @Test void getEndpointsWhenTwoStandardEndpointsHaveTheSameIdShouldThrowException() { load(ClashingStandardEndpointConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) - .withMessageContaining("Found two endpoints with the id 'test': ")); + .withMessageContaining("Found two endpoints with the id 'test': ")); } @Test void getEndpointsWhenWhenEndpointHasTwoOperationsWithTheSameNameShouldThrowException() { load(ClashingOperationsEndpoint.class, (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Unable to map duplicate endpoint operations: [MBean call 'getAll'] to jmxEndpointDiscovererTests.ClashingOperationsEndpoint")); + .isThrownBy(discoverer::getEndpoints) + .withMessageContaining( + "Unable to map duplicate endpoint operations: [MBean call 'getAll'] to jmxEndpointDiscovererTests.ClashingOperationsEndpoint")); } @Test void getEndpointsWhenWhenExtensionHasTwoOperationsWithTheSameNameShouldThrowException() { load(AdditionalClashingOperationsConfiguration.class, (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Unable to map duplicate endpoint operations: [MBean call 'getAll'] to testEndpoint (clashingOperationsJmxEndpointExtension)")); + .isThrownBy(discoverer::getEndpoints) + .withMessageContaining( + "Unable to map duplicate endpoint operations: [MBean call 'getAll'] to testEndpoint (clashingOperationsJmxEndpointExtension)")); } @Test void getEndpointsWhenExtensionIsNotCompatibleWithTheEndpointTypeShouldThrowException() { load(InvalidJmxExtensionConfiguration.class, (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Endpoint bean 'nonJmxEndpoint' cannot support the extension bean 'nonJmxJmxEndpointExtension'")); + .isThrownBy(discoverer::getEndpoints) + .withMessageContaining( + "Endpoint bean 'nonJmxEndpoint' cannot support the extension bean 'nonJmxJmxEndpointExtension'")); } private Object getInvoker(JmxOperation operation) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java index 8ca98ddd66..29a7b00384 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class EndpointLinksResolverTests { @Test void linkResolutionWithTrailingSlashStripsSlashOnSelfLink() { Map links = new EndpointLinksResolver(Collections.emptyList()) - .resolveLinks("https://api.example.com/actuator/"); + .resolveLinks("https://api.example.com/actuator/"); assertThat(links).hasSize(1); assertThat(links).hasEntrySatisfying("self", linkWithHref("https://api.example.com/actuator")); } @@ -50,7 +50,7 @@ class EndpointLinksResolverTests { @Test void linkResolutionWithoutTrailingSlash() { Map links = new EndpointLinksResolver(Collections.emptyList()) - .resolveLinks("https://api.example.com/actuator"); + .resolveLinks("https://api.example.com/actuator"); assertThat(links).hasSize(1); assertThat(links).hasEntrySatisfying("self", linkWithHref("https://api.example.com/actuator")); } @@ -66,7 +66,7 @@ class EndpointLinksResolverTests { given(endpoint.getOperations()).willReturn(operations); String requestUrl = "https://api.example.com/actuator"; Map links = new EndpointLinksResolver(Collections.singletonList(endpoint)) - .resolveLinks(requestUrl); + .resolveLinks(requestUrl); assertThat(links).hasSize(3); assertThat(links).hasEntrySatisfying("self", linkWithHref("https://api.example.com/actuator")); assertThat(links).hasEntrySatisfying("alpha", linkWithHref("https://api.example.com/actuator/alpha")); @@ -82,7 +82,7 @@ class EndpointLinksResolverTests { given(servletEndpoint.getRootPath()).willReturn("alpha"); String requestUrl = "https://api.example.com/actuator"; Map links = new EndpointLinksResolver(Collections.singletonList(servletEndpoint)) - .resolveLinks(requestUrl); + .resolveLinks(requestUrl); assertThat(links).hasSize(2); assertThat(links).hasEntrySatisfying("self", linkWithHref("https://api.example.com/actuator")); assertThat(links).hasEntrySatisfying("alpha", linkWithHref("https://api.example.com/actuator/alpha")); @@ -96,7 +96,7 @@ class EndpointLinksResolverTests { given(controllerEndpoint.getRootPath()).willReturn("alpha"); String requestUrl = "https://api.example.com/actuator"; Map links = new EndpointLinksResolver(Collections.singletonList(controllerEndpoint)) - .resolveLinks(requestUrl); + .resolveLinks(requestUrl); assertThat(links).hasSize(2); assertThat(links).hasEntrySatisfying("self", linkWithHref("https://api.example.com/actuator")); assertThat(links).hasEntrySatisfying("alpha", linkWithHref("https://api.example.com/actuator/alpha")); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java index 2f351a0a69..a9495d188e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,13 +47,13 @@ class EndpointMediaTypesTests { @Test void createWhenProducedIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new EndpointMediaTypes(null, Collections.emptyList())) - .withMessageContaining("Produced must not be null"); + .withMessageContaining("Produced must not be null"); } @Test void createWhenConsumedIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new EndpointMediaTypes(Collections.emptyList(), null)) - .withMessageContaining("Consumed must not be null"); + .withMessageContaining("Consumed must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java index ae9a1c276f..566ca01742 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,13 +42,13 @@ class EndpointServletTests { @Test void createWhenServletClassIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new EndpointServlet((Class) null)) - .withMessageContaining("Servlet must not be null"); + .withMessageContaining("Servlet must not be null"); } @Test void createWhenServletIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new EndpointServlet((Servlet) null)) - .withMessageContaining("Servlet must not be null"); + .withMessageContaining("Servlet must not be null"); } @Test @@ -85,36 +85,36 @@ class EndpointServletTests { @Test void withInitParameterWhenHasExistingShouldMergeParameters() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class).withInitParameter("a", "b") - .withInitParameter("c", "d"); + .withInitParameter("c", "d"); assertThat(endpointServlet.withInitParameter("a", "b1").withInitParameter("e", "f").getInitParameters()) - .containsExactly(entry("a", "b1"), entry("c", "d"), entry("e", "f")); + .containsExactly(entry("a", "b1"), entry("c", "d"), entry("e", "f")); } @Test void withInitParametersNullName() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); assertThatIllegalArgumentException() - .isThrownBy(() -> endpointServlet.withInitParameters(Collections.singletonMap(null, "value"))); + .isThrownBy(() -> endpointServlet.withInitParameters(Collections.singletonMap(null, "value"))); } @Test void withInitParametersEmptyName() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); assertThatIllegalArgumentException() - .isThrownBy(() -> endpointServlet.withInitParameters(Collections.singletonMap(" ", "value"))); + .isThrownBy(() -> endpointServlet.withInitParameters(Collections.singletonMap(" ", "value"))); } @Test void withInitParametersShouldCreateNewInstance() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); assertThat(endpointServlet.withInitParameters(Collections.singletonMap("spring", "boot"))) - .isNotSameAs(endpointServlet); + .isNotSameAs(endpointServlet); } @Test void withInitParametersWhenHasExistingShouldMergeParameters() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class).withInitParameter("a", "b") - .withInitParameter("c", "d"); + .withInitParameter("c", "d"); Map extra = new LinkedHashMap<>(); extra.put("a", "b1"); extra.put("e", "f"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/LinkTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/LinkTests.java index 7921b178cc..65f5a43183 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/LinkTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/LinkTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ class LinkTests { @Test void createWhenHrefIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new Link(null)) - .withMessageContaining("HREF must not be null"); + .withMessageContaining("HREF must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java index fa13f1e7a3..246a3991ca 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,15 +42,15 @@ class PathMappedEndpointsTests { @Test void createWhenSupplierIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new PathMappedEndpoints(null, (WebEndpointsSupplier) null)) - .withMessageContaining("Supplier must not be null"); + .isThrownBy(() -> new PathMappedEndpoints(null, (WebEndpointsSupplier) null)) + .withMessageContaining("Supplier must not be null"); } @Test void createWhenSuppliersIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new PathMappedEndpoints(null, (Collection>) null)) - .withMessageContaining("Suppliers must not be null"); + .isThrownBy(() -> new PathMappedEndpoints(null, (Collection>) null)) + .withMessageContaining("Suppliers must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java index cbbc52befe..ff25c857f7 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,7 +64,7 @@ class ServletEndpointRegistrarTests { @Test void createWhenServletEndpointsIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ServletEndpointRegistrar(null, null)) - .withMessageContaining("ServletEndpoints must not be null"); + .withMessageContaining("ServletEndpoints must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicateTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicateTests.java index ebd7b24ed0..5c7e87a48f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicateTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,7 +68,7 @@ class WebOperationRequestPredicateTests { @Test void predicatesWithMultiplePathVariablesInTheSamePlaceAreEqual() { assertThat(predicateWithPath("/path/{foo1}/more/{bar1}")) - .isEqualTo(predicateWithPath("/path/{foo2}/more/{bar2}")); + .isEqualTo(predicateWithPath("/path/{foo2}/more/{bar2}")); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java index 5520e248f1..75c5189e61 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -84,36 +84,79 @@ public abstract class AbstractWebEndpointIntegrationTests client.get().uri("/test").exchange().expectStatus().isOk() - .expectBody().jsonPath("All").isEqualTo(true)); + load(TestEndpointConfiguration.class, + (client) -> client.get() + .uri("/test") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("All") + .isEqualTo(true)); } @Test void readOperationWithEndpointsMappedToTheRoot() { - load(TestEndpointConfiguration.class, "", (client) -> client.get().uri("/test").exchange().expectStatus().isOk() - .expectBody().jsonPath("All").isEqualTo(true)); + load(TestEndpointConfiguration.class, "", + (client) -> client.get() + .uri("/test") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("All") + .isEqualTo(true)); } @Test void readOperationWithSelector() { - load(TestEndpointConfiguration.class, (client) -> client.get().uri("/test/one").exchange().expectStatus().isOk() - .expectBody().jsonPath("part").isEqualTo("one")); + load(TestEndpointConfiguration.class, + (client) -> client.get() + .uri("/test/one") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("part") + .isEqualTo("one")); } @Test void readOperationWithSelectorContainingADot() { - load(TestEndpointConfiguration.class, (client) -> client.get().uri("/test/foo.bar").exchange().expectStatus() - .isOk().expectBody().jsonPath("part").isEqualTo("foo.bar")); + load(TestEndpointConfiguration.class, + (client) -> client.get() + .uri("/test/foo.bar") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("part") + .isEqualTo("foo.bar")); } @Test void linksToOtherEndpointsAreProvided() { load(TestEndpointConfiguration.class, - (client) -> client.get().uri("").exchange().expectStatus().isOk().expectBody() - .jsonPath("_links.length()").isEqualTo(3).jsonPath("_links.self.href").isNotEmpty() - .jsonPath("_links.self.templated").isEqualTo(false).jsonPath("_links.test.href").isNotEmpty() - .jsonPath("_links.test.templated").isEqualTo(false).jsonPath("_links.test-part.href") - .isNotEmpty().jsonPath("_links.test-part.templated").isEqualTo(true)); + (client) -> client.get() + .uri("") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("_links.length()") + .isEqualTo(3) + .jsonPath("_links.self.href") + .isNotEmpty() + .jsonPath("_links.self.templated") + .isEqualTo(false) + .jsonPath("_links.test.href") + .isNotEmpty() + .jsonPath("_links.test.templated") + .isEqualTo(false) + .jsonPath("_links.test-part.href") + .isNotEmpty() + .jsonPath("_links.test-part.templated") + .isEqualTo(true)); } @Test @@ -124,53 +167,105 @@ public abstract class AbstractWebEndpointIntegrationTests client.get().uri("/test/").exchange().expectStatus().isOk() - .expectBody().jsonPath("All").isEqualTo(true)); + load(TestEndpointConfiguration.class, + (client) -> client.get() + .uri("/test/") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("All") + .isEqualTo(true)); } @Test void matchAllRemainingPathsSelectorShouldMatchFullPath() { load(MatchAllRemainingEndpointConfiguration.class, - (client) -> client.get().uri("/matchallremaining/one/two/three").exchange().expectStatus().isOk() - .expectBody().jsonPath("selection").isEqualTo("one|two|three")); + (client) -> client.get() + .uri("/matchallremaining/one/two/three") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("selection") + .isEqualTo("one|two|three")); } @Test void matchAllRemainingPathsSelectorShouldDecodePath() { load(MatchAllRemainingEndpointConfiguration.class, - (client) -> client.get().uri("/matchallremaining/one/two three/").exchange().expectStatus().isOk() - .expectBody().jsonPath("selection").isEqualTo("one|two three")); + (client) -> client.get() + .uri("/matchallremaining/one/two three/") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("selection") + .isEqualTo("one|two three")); } @Test void readOperationWithSingleQueryParameters() { - load(QueryEndpointConfiguration.class, (client) -> client.get().uri("/query?one=1&two=2").exchange() - .expectStatus().isOk().expectBody().jsonPath("query").isEqualTo("1 2")); + load(QueryEndpointConfiguration.class, + (client) -> client.get() + .uri("/query?one=1&two=2") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("query") + .isEqualTo("1 2")); } @Test void readOperationWithSingleQueryParametersAndMultipleValues() { - load(QueryEndpointConfiguration.class, (client) -> client.get().uri("/query?one=1&one=1&two=2").exchange() - .expectStatus().isOk().expectBody().jsonPath("query").isEqualTo("1,1 2")); + load(QueryEndpointConfiguration.class, + (client) -> client.get() + .uri("/query?one=1&one=1&two=2") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("query") + .isEqualTo("1,1 2")); } @Test void readOperationWithListQueryParameterAndSingleValue() { - load(QueryWithListEndpointConfiguration.class, (client) -> client.get().uri("/query?one=1&two=2").exchange() - .expectStatus().isOk().expectBody().jsonPath("query").isEqualTo("1 [2]")); + load(QueryWithListEndpointConfiguration.class, + (client) -> client.get() + .uri("/query?one=1&two=2") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("query") + .isEqualTo("1 [2]")); } @Test void readOperationWithListQueryParameterAndMultipleValues() { - load(QueryWithListEndpointConfiguration.class, (client) -> client.get().uri("/query?one=1&two=2&two=2") - .exchange().expectStatus().isOk().expectBody().jsonPath("query").isEqualTo("1 [2, 2]")); + load(QueryWithListEndpointConfiguration.class, + (client) -> client.get() + .uri("/query?one=1&two=2&two=2") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("query") + .isEqualTo("1 [2, 2]")); } @Test void readOperationWithMappingFailureProducesBadRequestResponse() { load(QueryEndpointConfiguration.class, (client) -> { - WebTestClient.BodyContentSpec body = client.get().uri("/query?two=two").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isBadRequest().expectBody(); + WebTestClient.BodyContentSpec body = client.get() + .uri("/query?two=two") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isBadRequest() + .expectBody(); validateErrorBody(body, HttpStatus.BAD_REQUEST, "/endpoints/query", "Missing parameters: one"); }); } @@ -195,8 +290,15 @@ public abstract class AbstractWebEndpointIntegrationTests client.delete().uri("/test/one").exchange().expectStatus() - .isOk().expectBody().jsonPath("part").isEqualTo("one")); + load(TestEndpointConfiguration.class, + (client) -> client.delete() + .uri("/test/one") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("part") + .isEqualTo("one")); } @Test @@ -220,8 +322,14 @@ public abstract class AbstractWebEndpointIntegrationTests { - client.post().uri("/test").contentType(MediaType.APPLICATION_JSON).exchange().expectStatus().isNoContent() - .expectBody().isEmpty(); + client.post() + .uri("/test") + .contentType(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isNoContent() + .expectBody() + .isEmpty(); then(context.getBean(EndpointDelegate.class)).should().write(null, null); }); } @@ -247,9 +355,15 @@ public abstract class AbstractWebEndpointIntegrationTests { - byte[] responseBody = client.get().uri("/resource").exchange().expectStatus().isOk().expectHeader() - .contentType(MediaType.APPLICATION_OCTET_STREAM).returnResult(byte[].class) - .getResponseBodyContent(); + byte[] responseBody = client.get() + .uri("/resource") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .returnResult(byte[].class) + .getResponseBodyContent(); assertThat(responseBody).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); }); } @@ -257,38 +371,71 @@ public abstract class AbstractWebEndpointIntegrationTests { - byte[] responseBody = client.get().uri("/resource").exchange().expectStatus().isOk().expectHeader() - .contentType(MediaType.APPLICATION_OCTET_STREAM).returnResult(byte[].class) - .getResponseBodyContent(); + byte[] responseBody = client.get() + .uri("/resource") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .returnResult(byte[].class) + .getResponseBodyContent(); assertThat(responseBody).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); }); } @Test void readOperationWithMonoResponse() { - load(MonoResponseEndpointConfiguration.class, (client) -> client.get().uri("/mono").exchange().expectStatus() - .isOk().expectBody().jsonPath("a").isEqualTo("alpha")); + load(MonoResponseEndpointConfiguration.class, + (client) -> client.get() + .uri("/mono") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("a") + .isEqualTo("alpha")); } @Test void readOperationWithFluxResponse() { load(FluxResponseEndpointConfiguration.class, - (client) -> client.get().uri("/flux").exchange().expectStatus().isOk().expectBody().jsonPath("[0].a") - .isEqualTo("alpha").jsonPath("[1].b").isEqualTo("bravo").jsonPath("[2].c") - .isEqualTo("charlie")); + (client) -> client.get() + .uri("/flux") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("[0].a") + .isEqualTo("alpha") + .jsonPath("[1].b") + .isEqualTo("bravo") + .jsonPath("[2].c") + .isEqualTo("charlie")); } @Test void readOperationWithCustomMediaType() { - load(CustomMediaTypesEndpointConfiguration.class, (client) -> client.get().uri("/custommediatypes").exchange() - .expectStatus().isOk().expectHeader().valueMatches("Content-Type", "text/plain(;charset=.*)?")); + load(CustomMediaTypesEndpointConfiguration.class, + (client) -> client.get() + .uri("/custommediatypes") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueMatches("Content-Type", "text/plain(;charset=.*)?")); } @Test void readOperationWithMissingRequiredParametersReturnsBadRequestResponse() { load(RequiredParameterEndpointConfiguration.class, (client) -> { - WebTestClient.BodyContentSpec body = client.get().uri("/requiredparameters") - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isBadRequest().expectBody(); + WebTestClient.BodyContentSpec body = client.get() + .uri("/requiredparameters") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isBadRequest() + .expectBody(); validateErrorBody(body, HttpStatus.BAD_REQUEST, "/endpoints/requiredparameters", "Missing parameters: foo"); }); } @@ -301,33 +448,65 @@ public abstract class AbstractWebEndpointIntegrationTests client.get().uri("/test").exchange().expectStatus().isOk() - .expectHeader().valueMatches("Content-Type", ACTUATOR_MEDIA_TYPE_PATTERN)); + load(TestEndpointConfiguration.class, + (client) -> client.get() + .uri("/test") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueMatches("Content-Type", ACTUATOR_MEDIA_TYPE_PATTERN)); } @Test void endpointsProduceSecondaryMediaTypeWhenRequested() { - load(TestEndpointConfiguration.class, (client) -> client.get().uri("/test").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectHeader().valueMatches("Content-Type", JSON_MEDIA_TYPE_PATTERN)); + load(TestEndpointConfiguration.class, + (client) -> client.get() + .uri("/test") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueMatches("Content-Type", JSON_MEDIA_TYPE_PATTERN)); } @Test void linksProducesPrimaryMediaTypeByDefault() { - load(TestEndpointConfiguration.class, (client) -> client.get().uri("").exchange().expectStatus().isOk() - .expectHeader().valueMatches("Content-Type", ACTUATOR_MEDIA_TYPE_PATTERN)); + load(TestEndpointConfiguration.class, + (client) -> client.get() + .uri("") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueMatches("Content-Type", ACTUATOR_MEDIA_TYPE_PATTERN)); } @Test void linksProducesSecondaryMediaTypeWhenRequested() { - load(TestEndpointConfiguration.class, (client) -> client.get().uri("").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectHeader().valueMatches("Content-Type", JSON_MEDIA_TYPE_PATTERN)); + load(TestEndpointConfiguration.class, + (client) -> client.get() + .uri("") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueMatches("Content-Type", JSON_MEDIA_TYPE_PATTERN)); } @Test void principalIsNullWhenRequestHasNoPrincipal() { load(PrincipalEndpointConfiguration.class, - (client) -> client.get().uri("/principal").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isOk().expectBody(String.class).isEqualTo("None")); + (client) -> client.get() + .uri("/principal") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("None")); } @Test @@ -335,8 +514,14 @@ public abstract class AbstractWebEndpointIntegrationTests { this.authenticatedContextCustomizer.accept(context); context.register(PrincipalEndpointConfiguration.class); - }, (client) -> client.get().uri("/principal").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isOk().expectBody(String.class).isEqualTo("Alice")); + }, (client) -> client.get() + .uri("/principal") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("Alice")); } @Test @@ -344,15 +529,27 @@ public abstract class AbstractWebEndpointIntegrationTests { this.authenticatedContextCustomizer.accept(context); context.register(PrincipalQueryEndpointConfiguration.class); - }, (client) -> client.get().uri("/principalquery?principal=Zoe").accept(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isOk().expectBody(String.class).isEqualTo("Zoe")); + }, (client) -> client.get() + .uri("/principalquery?principal=Zoe") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("Zoe")); } @Test void securityContextIsAvailableAndHasNullPrincipalWhenRequestHasNoPrincipal() { load(SecurityContextEndpointConfiguration.class, - (client) -> client.get().uri("/securitycontext").accept(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isOk().expectBody(String.class).isEqualTo("None")); + (client) -> client.get() + .uri("/securitycontext") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("None")); } @Test @@ -360,15 +557,27 @@ public abstract class AbstractWebEndpointIntegrationTests { this.authenticatedContextCustomizer.accept(context); context.register(SecurityContextEndpointConfiguration.class); - }, (client) -> client.get().uri("/securitycontext").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isOk().expectBody(String.class).isEqualTo("Alice")); + }, (client) -> client.get() + .uri("/securitycontext") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("Alice")); } @Test void userInRoleReturnsFalseWhenRequestHasNoPrincipal() { load(UserInRoleEndpointConfiguration.class, - (client) -> client.get().uri("/userinrole?role=ADMIN").accept(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isOk().expectBody(String.class).isEqualTo("ADMIN: false")); + (client) -> client.get() + .uri("/userinrole?role=ADMIN") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("ADMIN: false")); } @Test @@ -376,8 +585,14 @@ public abstract class AbstractWebEndpointIntegrationTests { this.authenticatedContextCustomizer.accept(context); context.register(UserInRoleEndpointConfiguration.class); - }, (client) -> client.get().uri("/userinrole?role=ADMIN").accept(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isOk().expectBody(String.class).isEqualTo("ADMIN: false")); + }, (client) -> client.get() + .uri("/userinrole?role=ADMIN") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("ADMIN: false")); } @Test @@ -385,8 +600,14 @@ public abstract class AbstractWebEndpointIntegrationTests { this.authenticatedContextCustomizer.accept(context); context.register(UserInRoleEndpointConfiguration.class); - }, (client) -> client.get().uri("/userinrole?role=ACTUATOR").accept(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isOk().expectBody(String.class).isEqualTo("ACTUATOR: true")); + }, (client) -> client.get() + .uri("/userinrole?role=ACTUATOR") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("ACTUATOR: true")); } @Test @@ -399,8 +620,14 @@ public abstract class AbstractWebEndpointIntegrationTests configuration, BiConsumer consumer) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java index 94021c018c..769d55fa7f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ class ControllerEndpointDiscovererTests { @Test void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run(assertDiscoverer((discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty())); + .run(assertDiscoverer((discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty())); } @Test @@ -71,59 +71,60 @@ class ControllerEndpointDiscovererTests { @Test void getEndpointsShouldDiscoverProxyControllerEndpoints() { this.contextRunner.withUserConfiguration(TestProxyControllerEndpoint.class) - .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) - .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer.getEndpoints(); - assertThat(endpoints).hasSize(1); - ExposableControllerEndpoint endpoint = endpoints.iterator().next(); - assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testcontroller")); - assertThat(endpoint.getController()).isInstanceOf(TestProxyControllerEndpoint.class); - assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); - })); + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) + .run(assertDiscoverer((discoverer) -> { + Collection endpoints = discoverer.getEndpoints(); + assertThat(endpoints).hasSize(1); + ExposableControllerEndpoint endpoint = endpoints.iterator().next(); + assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testcontroller")); + assertThat(endpoint.getController()).isInstanceOf(TestProxyControllerEndpoint.class); + assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); + })); } @Test void getEndpointsShouldIncludeRestControllerEndpoints() { this.contextRunner.withUserConfiguration(TestRestControllerEndpoint.class) - .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer.getEndpoints(); - assertThat(endpoints).hasSize(1); - ExposableControllerEndpoint endpoint = endpoints.iterator().next(); - assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testrestcontroller")); - assertThat(endpoint.getController()).isInstanceOf(TestRestControllerEndpoint.class); - })); + .run(assertDiscoverer((discoverer) -> { + Collection endpoints = discoverer.getEndpoints(); + assertThat(endpoints).hasSize(1); + ExposableControllerEndpoint endpoint = endpoints.iterator().next(); + assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testrestcontroller")); + assertThat(endpoint.getController()).isInstanceOf(TestRestControllerEndpoint.class); + })); } @Test void getEndpointsShouldDiscoverProxyRestControllerEndpoints() { this.contextRunner.withUserConfiguration(TestProxyRestControllerEndpoint.class) - .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) - .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer.getEndpoints(); - assertThat(endpoints).hasSize(1); - ExposableControllerEndpoint endpoint = endpoints.iterator().next(); - assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testrestcontroller")); - assertThat(endpoint.getController()).isInstanceOf(TestProxyRestControllerEndpoint.class); - assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); - })); + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) + .run(assertDiscoverer((discoverer) -> { + Collection endpoints = discoverer.getEndpoints(); + assertThat(endpoints).hasSize(1); + ExposableControllerEndpoint endpoint = endpoints.iterator().next(); + assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testrestcontroller")); + assertThat(endpoint.getController()).isInstanceOf(TestProxyRestControllerEndpoint.class); + assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); + })); } @Test void getEndpointsShouldNotDiscoverRegularEndpoints() { this.contextRunner.withUserConfiguration(WithRegularEndpointConfiguration.class) - .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer.getEndpoints(); - List ids = endpoints.stream().map(ExposableControllerEndpoint::getEndpointId) - .collect(Collectors.toList()); - assertThat(ids).containsOnly(EndpointId.of("testcontroller"), EndpointId.of("testrestcontroller")); - })); + .run(assertDiscoverer((discoverer) -> { + Collection endpoints = discoverer.getEndpoints(); + List ids = endpoints.stream() + .map(ExposableControllerEndpoint::getEndpointId) + .collect(Collectors.toList()); + assertThat(ids).containsOnly(EndpointId.of("testcontroller"), EndpointId.of("testrestcontroller")); + })); } @Test void getEndpointWhenEndpointHasOperationsShouldThrowException() { - this.contextRunner.withUserConfiguration(TestControllerWithOperation.class).run( - assertDiscoverer((discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) - .withMessageContaining("ControllerEndpoints must not declare operations"))); + this.contextRunner.withUserConfiguration(TestControllerWithOperation.class) + .run(assertDiscoverer((discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) + .withMessageContaining("ControllerEndpoints must not declare operations"))); } private ContextConsumer assertDiscoverer( diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/RequestPredicateFactoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/RequestPredicateFactoryTests.java index 17170e19dc..5723c5daa9 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/RequestPredicateFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/RequestPredicateFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,16 +48,16 @@ class RequestPredicateFactoryTests { void getRequestPredicateWhenHasMoreThanOneMatchAllThrowsException() { DiscoveredOperationMethod operationMethod = getDiscoveredOperationMethod(MoreThanOneMatchAll.class); assertThatIllegalStateException() - .isThrownBy(() -> this.factory.getRequestPredicate(this.rootPath, operationMethod)) - .withMessage("@Selector annotation with Match.ALL_REMAINING must be unique"); + .isThrownBy(() -> this.factory.getRequestPredicate(this.rootPath, operationMethod)) + .withMessage("@Selector annotation with Match.ALL_REMAINING must be unique"); } @Test void getRequestPredicateWhenMatchAllIsNotLastParameterThrowsException() { DiscoveredOperationMethod operationMethod = getDiscoveredOperationMethod(MatchAllIsNotLastParameter.class); assertThatIllegalStateException() - .isThrownBy(() -> this.factory.getRequestPredicate(this.rootPath, operationMethod)) - .withMessage("@Selector annotation with Match.ALL_REMAINING must be the last parameter"); + .isThrownBy(() -> this.factory.getRequestPredicate(this.rootPath, operationMethod)) + .withMessage("@Selector annotation with Match.ALL_REMAINING must be the last parameter"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java index 745465ccae..2cc2695e74 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,7 +62,7 @@ class ServletEndpointDiscovererTests { @Test void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run(assertDiscoverer((discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty())); + .run(assertDiscoverer((discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty())); } @Test @@ -80,54 +80,55 @@ class ServletEndpointDiscovererTests { @Test void getEndpointsShouldDiscoverProxyServletEndpoints() { this.contextRunner.withUserConfiguration(TestProxyServletEndpoint.class) - .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) - .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer.getEndpoints(); - assertThat(endpoints).hasSize(1); - ExposableServletEndpoint endpoint = endpoints.iterator().next(); - assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testservlet")); - assertThat(endpoint.getEndpointServlet()).isNotNull(); - assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); - })); + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) + .run(assertDiscoverer((discoverer) -> { + Collection endpoints = discoverer.getEndpoints(); + assertThat(endpoints).hasSize(1); + ExposableServletEndpoint endpoint = endpoints.iterator().next(); + assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testservlet")); + assertThat(endpoint.getEndpointServlet()).isNotNull(); + assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); + })); } @Test void getEndpointsShouldNotDiscoverRegularEndpoints() { this.contextRunner.withUserConfiguration(WithRegularEndpointConfiguration.class) - .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer.getEndpoints(); - List ids = endpoints.stream().map(ExposableServletEndpoint::getEndpointId) - .collect(Collectors.toList()); - assertThat(ids).containsOnly(EndpointId.of("testservlet")); - })); + .run(assertDiscoverer((discoverer) -> { + Collection endpoints = discoverer.getEndpoints(); + List ids = endpoints.stream() + .map(ExposableServletEndpoint::getEndpointId) + .collect(Collectors.toList()); + assertThat(ids).containsOnly(EndpointId.of("testservlet")); + })); } @Test void getEndpointWhenEndpointHasOperationsShouldThrowException() { - this.contextRunner.withUserConfiguration(TestServletEndpointWithOperation.class).run( - assertDiscoverer((discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) - .withMessageContaining("ServletEndpoints must not declare operations"))); + this.contextRunner.withUserConfiguration(TestServletEndpointWithOperation.class) + .run(assertDiscoverer((discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) + .withMessageContaining("ServletEndpoints must not declare operations"))); } @Test void getEndpointWhenEndpointNotASupplierShouldThrowException() { this.contextRunner.withUserConfiguration(TestServletEndpointNotASupplier.class) - .run(assertDiscoverer((discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining("must be a supplier"))); + .run(assertDiscoverer((discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) + .withMessageContaining("must be a supplier"))); } @Test void getEndpointWhenEndpointSuppliesWrongTypeShouldThrowException() { this.contextRunner.withUserConfiguration(TestServletEndpointSupplierOfWrongType.class) - .run(assertDiscoverer((discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining("must supply an EndpointServlet"))); + .run(assertDiscoverer((discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) + .withMessageContaining("must supply an EndpointServlet"))); } @Test void getEndpointWhenEndpointSuppliesNullShouldThrowException() { this.contextRunner.withUserConfiguration(TestServletEndpointSupplierOfNull.class) - .run(assertDiscoverer((discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining("must not supply null"))); + .run(assertDiscoverer((discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) + .withMessageContaining("must not supply null"))); } private ContextConsumer assertDiscoverer( diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java index 552c7a09cb..7a61d682b4 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,8 +77,7 @@ class WebEndpointDiscovererTests { void getEndpointsWhenWebExtensionIsMissingEndpointShouldThrowException() { load(TestWebEndpointExtensionConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) - .withMessageContaining( - "Invalid extension 'endpointExtension': no endpoint found with id 'test'")); + .withMessageContaining("Invalid extension 'endpointExtension': no endpoint found with id 'test'")); } @Test @@ -127,40 +126,40 @@ class WebEndpointDiscovererTests { void getEndpointsWhenTwoExtensionsHaveTheSameEndpointTypeShouldThrowException() { load(ClashingWebEndpointConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) - .withMessageContaining("Found multiple extensions for the endpoint bean " - + "testEndpoint (testExtensionOne, testExtensionTwo)")); + .withMessageContaining("Found multiple extensions for the endpoint bean " + + "testEndpoint (testExtensionOne, testExtensionTwo)")); } @Test void getEndpointsWhenTwoStandardEndpointsHaveTheSameIdShouldThrowException() { load(ClashingStandardEndpointConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) - .withMessageContaining("Found two endpoints with the id 'test': ")); + .withMessageContaining("Found two endpoints with the id 'test': ")); } @Test void getEndpointsWhenWhenEndpointHasTwoOperationsWithTheSameNameShouldThrowException() { load(ClashingOperationsEndpointConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) - .withMessageContaining("Unable to map duplicate endpoint operations: " - + "[web request predicate GET to path 'test' " - + "produces: application/json] to clashingOperationsEndpoint")); + .withMessageContaining("Unable to map duplicate endpoint operations: " + + "[web request predicate GET to path 'test' " + + "produces: application/json] to clashingOperationsEndpoint")); } @Test void getEndpointsWhenExtensionIsNotCompatibleWithTheEndpointTypeShouldThrowException() { load(InvalidWebExtensionConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) - .withMessageContaining("Endpoint bean 'nonWebEndpoint' cannot support the " - + "extension bean 'nonWebWebEndpointExtension'")); + .withMessageContaining("Endpoint bean 'nonWebEndpoint' cannot support the " + + "extension bean 'nonWebWebEndpointExtension'")); } @Test void getEndpointsWhenWhenExtensionHasTwoOperationsWithTheSameNameShouldThrowException() { load(ClashingSelectorsWebEndpointExtensionConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) - .withMessageContaining("Unable to map duplicate endpoint operations") - .withMessageContaining("to testEndpoint (clashingSelectorsExtension)")); + .withMessageContaining("Unable to map duplicate endpoint operations") + .withMessageContaining("to testEndpoint (clashingSelectorsExtension)")); } @Test @@ -183,8 +182,10 @@ class WebEndpointDiscovererTests { Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("resource")); ExposableWebEndpoint endpoint = endpoints.get(EndpointId.of("resource")); - assertThat(requestPredicates(endpoint)).has(requestPredicates(path("resource") - .httpMethod(WebEndpointHttpMethod.GET).consumes().produces("application/octet-stream"))); + assertThat(requestPredicates(endpoint)) + .has(requestPredicates(path("resource").httpMethod(WebEndpointHttpMethod.GET) + .consumes() + .produces("application/octet-stream"))); }); } @@ -197,8 +198,9 @@ class WebEndpointDiscovererTests { assertThat(requestPredicates(endpoint)).has(requestPredicates( path("custommediatypes").httpMethod(WebEndpointHttpMethod.GET).consumes().produces("text/plain"), path("custommediatypes").httpMethod(WebEndpointHttpMethod.POST).consumes().produces("a/b", "c/d"), - path("custommediatypes").httpMethod(WebEndpointHttpMethod.DELETE).consumes() - .produces("text/plain"))); + path("custommediatypes").httpMethod(WebEndpointHttpMethod.DELETE) + .consumes() + .produces("text/plain"))); }); } @@ -210,8 +212,9 @@ class WebEndpointDiscovererTests { ExposableWebEndpoint endpoint = endpoints.get(EndpointId.of("test")); Condition> expected = requestPredicates( path("custom/test").httpMethod(WebEndpointHttpMethod.GET).consumes().produces("application/json"), - path("custom/test/{id}").httpMethod(WebEndpointHttpMethod.GET).consumes() - .produces("application/json")); + path("custom/test/{id}").httpMethod(WebEndpointHttpMethod.GET) + .consumes() + .produces("application/json")); assertThat(requestPredicates(endpoint)).has(expected); }); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingIntegrationTests.java index 1b7517b661..03e5a94dfa 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,34 +61,51 @@ import org.springframework.web.util.DefaultUriBuilderFactory; class ControllerEndpointHandlerMappingIntegrationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner( - AnnotationConfigReactiveWebServerApplicationContext::new).withUserConfiguration(EndpointConfiguration.class, - ExampleWebFluxEndpoint.class); + AnnotationConfigReactiveWebServerApplicationContext::new) + .withUserConfiguration(EndpointConfiguration.class, ExampleWebFluxEndpoint.class); @Test void get() { - this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get().uri("/actuator/example/one") - .accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isOk().expectHeader() - .contentTypeCompatibleWith(MediaType.TEXT_PLAIN).expectBody(String.class).isEqualTo("One"))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get() + .uri("/actuator/example/one") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentTypeCompatibleWith(MediaType.TEXT_PLAIN) + .expectBody(String.class) + .isEqualTo("One"))); } @Test void getWithUnacceptableContentType() { - this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get().uri("/actuator/example/one") - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isEqualTo(HttpStatus.NOT_ACCEPTABLE))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get() + .uri("/actuator/example/one") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.NOT_ACCEPTABLE))); } @Test void post() { - this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.post().uri("/actuator/example/two") - .bodyValue(Collections.singletonMap("id", "test")).exchange().expectStatus().isCreated().expectHeader() - .valueEquals(HttpHeaders.LOCATION, "/example/test"))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.post() + .uri("/actuator/example/two") + .bodyValue(Collections.singletonMap("id", "test")) + .exchange() + .expectStatus() + .isCreated() + .expectHeader() + .valueEquals(HttpHeaders.LOCATION, "/example/test"))); } private ContextConsumer withWebTestClient( Consumer webClient) { return (context) -> { int port = ((AnnotationConfigReactiveWebServerApplicationContext) context.getSourceApplicationContext()) - .getWebServer().getPort(); + .getWebServer() + .getPort(); WebTestClient webTestClient = createWebTestClient(port); webClient.accept(webTestClient); }; @@ -97,8 +114,10 @@ class ControllerEndpointHandlerMappingIntegrationTests { private WebTestClient createWebTestClient(int port) { DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory("http://localhost:" + port); uriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE); - return WebTestClient.bindToServer().uriBuilderFactory(uriBuilderFactory).responseTimeout(Duration.ofMinutes(5)) - .build(); + return WebTestClient.bindToServer() + .uriBuilderFactory(uriBuilderFactory) + .responseTimeout(Duration.ofMinutes(5)) + .build(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java index 635b58c15d..e307b8d1bc 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +57,7 @@ class ControllerEndpointHandlerMappingTests { ControllerEndpointHandlerMapping mapping = createMapping("", first, second); assertThat(getHandler(mapping, HttpMethod.GET, "/first")).isEqualTo(handlerOf(first.getController(), "get")); assertThat(getHandler(mapping, HttpMethod.POST, "/second")) - .isEqualTo(handlerOf(second.getController(), "save")); + .isEqualTo(handlerOf(second.getController(), "save")); assertThat(getHandler(mapping, HttpMethod.GET, "/third")).isNull(); } @@ -67,9 +67,9 @@ class ControllerEndpointHandlerMappingTests { ExposableControllerEndpoint second = secondEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", first, second); assertThat(getHandler(mapping, HttpMethod.GET, "/actuator/first")) - .isEqualTo(handlerOf(first.getController(), "get")); + .isEqualTo(handlerOf(first.getController(), "get")); assertThat(getHandler(mapping, HttpMethod.POST, "/actuator/second")) - .isEqualTo(handlerOf(second.getController(), "save")); + .isEqualTo(handlerOf(second.getController(), "save")); assertThat(getHandler(mapping, HttpMethod.GET, "/first")).isNull(); assertThat(getHandler(mapping, HttpMethod.GET, "/second")).isNull(); } @@ -79,7 +79,7 @@ class ControllerEndpointHandlerMappingTests { ExposableControllerEndpoint pathless = pathlessEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", pathless); assertThat(getHandler(mapping, HttpMethod.GET, "/actuator/pathless")) - .isEqualTo(handlerOf(pathless.getController(), "get")); + .isEqualTo(handlerOf(pathless.getController(), "get")); assertThat(getHandler(mapping, HttpMethod.GET, "/pathless")).isNull(); assertThat(getHandler(mapping, HttpMethod.GET, "/")).isNull(); } @@ -89,7 +89,7 @@ class ControllerEndpointHandlerMappingTests { ExposableControllerEndpoint first = firstEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", first); assertThatExceptionOfType(MethodNotAllowedException.class) - .isThrownBy(() -> getHandler(mapping, HttpMethod.POST, "/actuator/first")); + .isThrownBy(() -> getHandler(mapping, HttpMethod.POST, "/actuator/first")); } private Object getHandler(ControllerEndpointHandlerMapping mapping, HttpMethod method, String requestURI) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointIntegrationTests.java index b6aaf05a70..f27d667e57 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,20 +77,33 @@ class WebFluxEndpointIntegrationTests @Test void responseToOptionsRequestIncludesCorsHeaders() { load(TestEndpointConfiguration.class, - (client) -> client.options().uri("/test").accept(MediaType.APPLICATION_JSON) - .header("Access-Control-Request-Method", "POST").header("Origin", "https://example.com") - .exchange().expectStatus().isOk().expectHeader() - .valueEquals("Access-Control-Allow-Origin", "https://example.com").expectHeader() - .valueEquals("Access-Control-Allow-Methods", "GET,POST")); + (client) -> client.options() + .uri("/test") + .accept(MediaType.APPLICATION_JSON) + .header("Access-Control-Request-Method", "POST") + .header("Origin", "https://example.com") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueEquals("Access-Control-Allow-Origin", "https://example.com") + .expectHeader() + .valueEquals("Access-Control-Allow-Methods", "GET,POST")); } @Test void readOperationsThatReturnAResourceSupportRangeRequests() { load(ResourceEndpointConfiguration.class, (client) -> { - byte[] responseBody = client.get().uri("/resource").header("Range", "bytes=0-3").exchange().expectStatus() - .isEqualTo(HttpStatus.PARTIAL_CONTENT).expectHeader() - .contentType(MediaType.APPLICATION_OCTET_STREAM).returnResult(byte[].class) - .getResponseBodyContent(); + byte[] responseBody = client.get() + .uri("/resource") + .header("Range", "bytes=0-3") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.PARTIAL_CONTENT) + .expectHeader() + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .returnResult(byte[].class) + .getResponseBodyContent(); assertThat(responseBody).containsExactly(0, 1, 2, 3); }); } @@ -141,9 +154,9 @@ class WebFluxEndpointIntegrationTests @Bean WebFilter webFilter() { - return (exchange, chain) -> chain.filter(exchange).contextWrite( - ReactiveSecurityContextHolder.withAuthentication(new UsernamePasswordAuthenticationToken("Alice", - "secret", Arrays.asList(new SimpleGrantedAuthority("ROLE_ACTUATOR"))))); + return (exchange, chain) -> chain.filter(exchange) + .contextWrite(ReactiveSecurityContextHolder.withAuthentication(new UsernamePasswordAuthenticationToken( + "Alice", "secret", Arrays.asList(new SimpleGrantedAuthority("ROLE_ACTUATOR"))))); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingIntegrationTests.java index bf8b98b736..75b5877794 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,33 +60,50 @@ import org.springframework.web.util.DefaultUriBuilderFactory; class ControllerEndpointHandlerMappingIntegrationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( - AnnotationConfigServletWebServerApplicationContext::new).withUserConfiguration(EndpointConfiguration.class, - ExampleMvcEndpoint.class); + AnnotationConfigServletWebServerApplicationContext::new) + .withUserConfiguration(EndpointConfiguration.class, ExampleMvcEndpoint.class); @Test void get() { - this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get().uri("/actuator/example/one") - .accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isOk().expectHeader() - .contentTypeCompatibleWith(MediaType.TEXT_PLAIN).expectBody(String.class).isEqualTo("One"))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get() + .uri("/actuator/example/one") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentTypeCompatibleWith(MediaType.TEXT_PLAIN) + .expectBody(String.class) + .isEqualTo("One"))); } @Test void getWithUnacceptableContentType() { - this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get().uri("/actuator/example/one") - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isEqualTo(HttpStatus.NOT_ACCEPTABLE))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get() + .uri("/actuator/example/one") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.NOT_ACCEPTABLE))); } @Test void post() { - this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.post().uri("/actuator/example/two") - .bodyValue(Collections.singletonMap("id", "test")).exchange().expectStatus().isCreated().expectHeader() - .valueEquals(HttpHeaders.LOCATION, "/example/test"))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.post() + .uri("/actuator/example/two") + .bodyValue(Collections.singletonMap("id", "test")) + .exchange() + .expectStatus() + .isCreated() + .expectHeader() + .valueEquals(HttpHeaders.LOCATION, "/example/test"))); } private ContextConsumer withWebTestClient(Consumer webClient) { return (context) -> { int port = ((AnnotationConfigServletWebServerApplicationContext) context.getSourceApplicationContext()) - .getWebServer().getPort(); + .getWebServer() + .getPort(); WebTestClient webTestClient = createWebTestClient(port); webClient.accept(webTestClient); }; @@ -95,8 +112,10 @@ class ControllerEndpointHandlerMappingIntegrationTests { private WebTestClient createWebTestClient(int port) { DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory("http://localhost:" + port); uriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE); - return WebTestClient.bindToServer().uriBuilderFactory(uriBuilderFactory).responseTimeout(Duration.ofMinutes(5)) - .build(); + return WebTestClient.bindToServer() + .uriBuilderFactory(uriBuilderFactory) + .responseTimeout(Duration.ofMinutes(5)) + .build(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java index b9b1b09ec5..9a74d68b33 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,9 +53,9 @@ class ControllerEndpointHandlerMappingTests { ExposableControllerEndpoint second = secondEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("", first, second); assertThat(mapping.getHandler(request("GET", "/first")).getHandler()) - .isEqualTo(handlerOf(first.getController(), "get")); + .isEqualTo(handlerOf(first.getController(), "get")); assertThat(mapping.getHandler(request("POST", "/second")).getHandler()) - .isEqualTo(handlerOf(second.getController(), "save")); + .isEqualTo(handlerOf(second.getController(), "save")); assertThat(mapping.getHandler(request("GET", "/third"))).isNull(); } @@ -65,9 +65,9 @@ class ControllerEndpointHandlerMappingTests { ExposableControllerEndpoint second = secondEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", first, second); assertThat(mapping.getHandler(request("GET", "/actuator/first")).getHandler()) - .isEqualTo(handlerOf(first.getController(), "get")); + .isEqualTo(handlerOf(first.getController(), "get")); assertThat(mapping.getHandler(request("POST", "/actuator/second")).getHandler()) - .isEqualTo(handlerOf(second.getController(), "save")); + .isEqualTo(handlerOf(second.getController(), "save")); assertThat(mapping.getHandler(request("GET", "/first"))).isNull(); assertThat(mapping.getHandler(request("GET", "/second"))).isNull(); } @@ -77,7 +77,7 @@ class ControllerEndpointHandlerMappingTests { ExposableControllerEndpoint first = firstEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", first); assertThatExceptionOfType(HttpRequestMethodNotSupportedException.class) - .isThrownBy(() -> mapping.getHandler(request("POST", "/actuator/first"))); + .isThrownBy(() -> mapping.getHandler(request("POST", "/actuator/first"))); } @Test @@ -85,7 +85,7 @@ class ControllerEndpointHandlerMappingTests { ExposableControllerEndpoint pathless = pathlessEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", pathless); assertThat(mapping.getHandler(request("GET", "/actuator/pathless")).getHandler()) - .isEqualTo(handlerOf(pathless.getController(), "get")); + .isEqualTo(handlerOf(pathless.getController(), "get")); assertThat(mapping.getHandler(request("GET", "/pathless"))).isNull(); assertThat(mapping.getHandler(request("GET", "/"))).isNull(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/DefaultWebMvcTagsProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/DefaultWebMvcTagsProviderTests.java index fd5de979ee..d87a187241 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/DefaultWebMvcTagsProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/DefaultWebMvcTagsProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,8 @@ class DefaultWebMvcTagsProviderTests { void givenSomeContributorsWhenTagsAreProvidedThenDefaultTagsAndContributedTagsArePresent() { Map tags = asMap( new DefaultWebMvcTagsProvider(Arrays.asList(new TestWebMvcTagsContributor("alpha"), - new TestWebMvcTagsContributor("bravo", "charlie"))).getTags(null, null, null, null)); + new TestWebMvcTagsContributor("bravo", "charlie"))) + .getTags(null, null, null, null)); assertThat(tags).containsOnlyKeys("exception", "method", "outcome", "status", "uri", "alpha", "bravo", "charlie"); } @@ -66,13 +67,14 @@ class DefaultWebMvcTagsProviderTests { void givenSomeContributorsWhenLongRequestTagsAreProvidedThenDefaultTagsAndContributedTagsArePresent() { Map tags = asMap( new DefaultWebMvcTagsProvider(Arrays.asList(new TestWebMvcTagsContributor("alpha"), - new TestWebMvcTagsContributor("bravo", "charlie"))).getLongRequestTags(null, null)); + new TestWebMvcTagsContributor("bravo", "charlie"))) + .getLongRequestTags(null, null)); assertThat(tags).containsOnlyKeys("method", "uri", "alpha", "bravo", "charlie"); } private Map asMap(Iterable tags) { return StreamSupport.stream(tags.spliterator(), false) - .collect(Collectors.toMap(Tag::getKey, Function.identity())); + .collect(Collectors.toMap(Tag::getKey, Function.identity())); } private static final class TestWebMvcTagsContributor implements WebMvcTagsContributor { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/MvcWebEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/MvcWebEndpointIntegrationTests.java index ce85bb61f0..c72db340ac 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/MvcWebEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/MvcWebEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -89,20 +89,33 @@ class MvcWebEndpointIntegrationTests @Test void responseToOptionsRequestIncludesCorsHeaders() { load(TestEndpointConfiguration.class, - (client) -> client.options().uri("/test").accept(MediaType.APPLICATION_JSON) - .header("Access-Control-Request-Method", "POST").header("Origin", "https://example.com") - .exchange().expectStatus().isOk().expectHeader() - .valueEquals("Access-Control-Allow-Origin", "https://example.com").expectHeader() - .valueEquals("Access-Control-Allow-Methods", "GET,POST")); + (client) -> client.options() + .uri("/test") + .accept(MediaType.APPLICATION_JSON) + .header("Access-Control-Request-Method", "POST") + .header("Origin", "https://example.com") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueEquals("Access-Control-Allow-Origin", "https://example.com") + .expectHeader() + .valueEquals("Access-Control-Allow-Methods", "GET,POST")); } @Test void readOperationsThatReturnAResourceSupportRangeRequests() { load(ResourceEndpointConfiguration.class, (client) -> { - byte[] responseBody = client.get().uri("/resource").header("Range", "bytes=0-3").exchange().expectStatus() - .isEqualTo(HttpStatus.PARTIAL_CONTENT).expectHeader() - .contentType(MediaType.APPLICATION_OCTET_STREAM).returnResult(byte[].class) - .getResponseBodyContent(); + byte[] responseBody = client.get() + .uri("/resource") + .header("Range", "bytes=0-3") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.PARTIAL_CONTENT) + .expectHeader() + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .returnResult(byte[].class) + .getResponseBodyContent(); assertThat(responseBody).containsExactly(0, 1, 2, 3); }); } 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 88fe50f32b..f9251aa1d7 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -143,8 +143,9 @@ class WebEndpointTestInvocationContextProvider implements TestTemplateInvocation @Override public void beforeEach(ExtensionContext extensionContext) throws Exception { List> configurationClasses = Stream - .of(extensionContext.getRequiredTestClass().getDeclaredClasses()).filter(this::isConfiguration) - .collect(Collectors.toList()); + .of(extensionContext.getRequiredTestClass().getDeclaredClasses()) + .filter(this::isConfiguration) + .collect(Collectors.toList()); this.context = this.contextFactory.apply(configurationClasses); } @@ -190,13 +191,17 @@ class WebEndpointTestInvocationContextProvider implements TestTemplateInvocation DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory( "http://localhost:" + determinePort()); uriBuilderFactory.setEncodingMode(EncodingMode.NONE); - return WebTestClient.bindToServer().uriBuilderFactory(uriBuilderFactory).responseTimeout(TIMEOUT) - .codecs((codecs) -> codecs.defaultCodecs().maxInMemorySize(-1)).filter((request, next) -> { - if (HttpMethod.GET == request.method()) { - return next.exchange(request).retry(10); - } - return next.exchange(request); - }).build(); + return WebTestClient.bindToServer() + .uriBuilderFactory(uriBuilderFactory) + .responseTimeout(TIMEOUT) + .codecs((codecs) -> codecs.defaultCodecs().maxInMemorySize(-1)) + .filter((request, next) -> { + if (HttpMethod.GET == request.method()) { + return next.exchange(request).retry(10); + } + return next.exchange(request); + }) + .build(); } private int determinePort() { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointTests.java index 714f81a25d..0129476256 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -97,43 +97,43 @@ class EnvironmentEndpointTests { @Test void sensitiveKeysHaveTheirValuesSanitized() { - TestPropertyValues.of("dbPassword=123456", "apiKey=123456", "mySecret=123456", "myCredentials=123456", - "VCAP_SERVICES=123456").applyToSystemProperties(() -> { - EnvironmentDescriptor descriptor = new EnvironmentEndpoint(new StandardEnvironment()) - .environment(null); - Map systemProperties = propertySources(descriptor) - .get("systemProperties").getProperties(); - assertThat(systemProperties.get("dbPassword").getValue()).isEqualTo("******"); - assertThat(systemProperties.get("apiKey").getValue()).isEqualTo("******"); - assertThat(systemProperties.get("mySecret").getValue()).isEqualTo("******"); - assertThat(systemProperties.get("myCredentials").getValue()).isEqualTo("******"); - assertThat(systemProperties.get("VCAP_SERVICES").getValue()).isEqualTo("******"); - PropertyValueDescriptor command = systemProperties.get("sun.java.command"); - if (command != null) { - assertThat(command.getValue()).isEqualTo("******"); - } - return null; - }); + TestPropertyValues + .of("dbPassword=123456", "apiKey=123456", "mySecret=123456", "myCredentials=123456", "VCAP_SERVICES=123456") + .applyToSystemProperties(() -> { + EnvironmentDescriptor descriptor = new EnvironmentEndpoint(new StandardEnvironment()).environment(null); + Map systemProperties = propertySources(descriptor) + .get("systemProperties") + .getProperties(); + assertThat(systemProperties.get("dbPassword").getValue()).isEqualTo("******"); + assertThat(systemProperties.get("apiKey").getValue()).isEqualTo("******"); + assertThat(systemProperties.get("mySecret").getValue()).isEqualTo("******"); + assertThat(systemProperties.get("myCredentials").getValue()).isEqualTo("******"); + assertThat(systemProperties.get("VCAP_SERVICES").getValue()).isEqualTo("******"); + PropertyValueDescriptor command = systemProperties.get("sun.java.command"); + if (command != null) { + assertThat(command.getValue()).isEqualTo("******"); + } + return null; + }); } @Test void sensitiveKeysMatchingCredentialsPatternHaveTheirValuesSanitized() { TestPropertyValues - .of("my.services.amqp-free.credentials.uri=123456", "credentials.http_api_uri=123456", - "my.services.cleardb-free.credentials=123456", "foo.mycredentials.uri=123456") - .applyToSystemProperties(() -> { - EnvironmentDescriptor descriptor = new EnvironmentEndpoint(new StandardEnvironment()) - .environment(null); - Map systemProperties = propertySources(descriptor) - .get("systemProperties").getProperties(); - assertThat(systemProperties.get("my.services.amqp-free.credentials.uri").getValue()) - .isEqualTo("******"); - assertThat(systemProperties.get("credentials.http_api_uri").getValue()).isEqualTo("******"); - assertThat(systemProperties.get("my.services.cleardb-free.credentials").getValue()) - .isEqualTo("******"); - assertThat(systemProperties.get("foo.mycredentials.uri").getValue()).isEqualTo("******"); - return null; - }); + .of("my.services.amqp-free.credentials.uri=123456", "credentials.http_api_uri=123456", + "my.services.cleardb-free.credentials=123456", "foo.mycredentials.uri=123456") + .applyToSystemProperties(() -> { + EnvironmentDescriptor descriptor = new EnvironmentEndpoint(new StandardEnvironment()).environment(null); + Map systemProperties = propertySources(descriptor) + .get("systemProperties") + .getProperties(); + assertThat(systemProperties.get("my.services.amqp-free.credentials.uri").getValue()) + .isEqualTo("******"); + assertThat(systemProperties.get("credentials.http_api_uri").getValue()).isEqualTo("******"); + assertThat(systemProperties.get("my.services.cleardb-free.credentials").getValue()).isEqualTo("******"); + assertThat(systemProperties.get("foo.mycredentials.uri").getValue()).isEqualTo("******"); + return null; + }); } @Test @@ -143,7 +143,7 @@ class EnvironmentEndpointTests { endpoint.setKeysToSanitize("key"); EnvironmentDescriptor descriptor = endpoint.environment(null); Map systemProperties = propertySources(descriptor).get("systemProperties") - .getProperties(); + .getProperties(); assertThat(systemProperties.get("dbPassword").getValue()).isEqualTo("123456"); assertThat(systemProperties.get("apiKey").getValue()).isEqualTo("******"); return null; @@ -157,7 +157,7 @@ class EnvironmentEndpointTests { endpoint.setKeysToSanitize(".*pass.*"); EnvironmentDescriptor descriptor = endpoint.environment(null); Map systemProperties = propertySources(descriptor).get("systemProperties") - .getProperties(); + .getProperties(); assertThat(systemProperties.get("dbPassword").getValue()).isEqualTo("******"); assertThat(systemProperties.get("apiKey").getValue()).isEqualTo("123456"); return null; @@ -176,11 +176,12 @@ class EnvironmentEndpointTests { return data.withValue("******"); } return data; - })).environment(null); + })) + .environment(null); assertThat(propertySources(descriptor).get("test").getProperties().get("other.service").getValue()) - .isEqualTo("abcde"); + .isEqualTo("abcde"); Map systemProperties = propertySources(descriptor).get("systemProperties") - .getProperties(); + .getProperties(); assertThat(systemProperties.get("system.service").getValue()).isEqualTo("******"); return null; }); @@ -200,7 +201,7 @@ class EnvironmentEndpointTests { TestPropertyValues.of("my.foo: ${bar.blah}").applyTo(environment); EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment).environment(null); assertThat(propertySources(descriptor).get("test").getProperties().get("my.foo").getValue()) - .isEqualTo("${bar.blah}"); + .isEqualTo("${bar.blah}"); } @Test @@ -209,7 +210,7 @@ class EnvironmentEndpointTests { TestPropertyValues.of("my.foo: http://${bar.password}://hello", "bar.password: hello").applyTo(environment); EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment).environment(null); assertThat(propertySources(descriptor).get("test").getProperties().get("my.foo").getValue()) - .isEqualTo("http://******://hello"); + .isEqualTo("http://******://hello"); } @Test @@ -218,7 +219,7 @@ class EnvironmentEndpointTests { TestPropertyValues.of("my.foo: http://${bar.password}://hello").applyTo(environment); EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment).environment(null); assertThat(propertySources(descriptor).get("test").getProperties().get("my.foo").getValue()) - .isEqualTo("http://${bar.password}://hello"); + .isEqualTo("http://${bar.password}://hello"); } @Test @@ -227,16 +228,16 @@ class EnvironmentEndpointTests { TestPropertyValues.of("my.foo: http://${bar.password}://hello", "bar.password: hello").applyTo(environment); EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment, Collections.singletonList((data) -> data.withValue(data.getPropertySource().getName() + "******"))) - .environment(null); + .environment(null); assertThat(propertySources(descriptor).get("test").getProperties().get("my.foo").getValue()) - .isEqualTo("test******"); + .isEqualTo("test******"); } @Test void propertyWithComplexTypeShouldNotFail() { ConfigurableEnvironment environment = emptyEnvironment(); environment.getPropertySources() - .addFirst(singleKeyPropertySource("test", "foo", Collections.singletonMap("bar", "baz"))); + .addFirst(singleKeyPropertySource("test", "foo", Collections.singletonMap("bar", "baz"))); EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment).environment(null); String value = (String) propertySources(descriptor).get("test").getProperties().get("foo").getValue(); assertThat(value).isEqualTo("Complex property type java.util.Collections$SingletonMap"); @@ -272,8 +273,8 @@ class EnvironmentEndpointTests { void propertyEntry() { TestPropertyValues.of("my.foo=another").applyToSystemProperties(() -> { StandardEnvironment environment = new StandardEnvironment(); - TestPropertyValues.of("my.foo=bar", "my.foo2=bar2").applyTo(environment, TestPropertyValues.Type.MAP, - "test"); + TestPropertyValues.of("my.foo=bar", "my.foo2=bar2") + .applyTo(environment, TestPropertyValues.Type.MAP, "test"); EnvironmentEntryDescriptor descriptor = new EnvironmentEndpoint(environment).environmentEntry("my.foo"); assertThat(descriptor).isNotNull(); assertThat(descriptor.getProperty()).isNotNull(); @@ -336,12 +337,12 @@ class EnvironmentEndpointTests { void addressesPropertyWithMultipleEntriesEachWithSensitiveInfo() { ConfigurableEnvironment environment = new StandardEnvironment(); TestPropertyValues - .of("sensitive.addresses=http://user:password@localhost:8080,http://user2:password2@localhost:8082") - .applyTo(environment); + .of("sensitive.addresses=http://user:password@localhost:8080,http://user2:password2@localhost:8082") + .applyTo(environment); EnvironmentEntryDescriptor descriptor = new EnvironmentEndpoint(environment) - .environmentEntry("sensitive.addresses"); + .environmentEntry("sensitive.addresses"); assertThat(descriptor.getProperty().getValue()) - .isEqualTo("http://user:******@localhost:8080,http://user2:******@localhost:8082"); + .isEqualTo("http://user:******@localhost:8080,http://user2:******@localhost:8082"); } private static ConfigurableEnvironment emptyEnvironment() { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebIntegrationTests.java index f46d8d5569..1389584a97 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,14 +45,28 @@ class EnvironmentEndpointWebIntegrationTests { @WebEndpointTest void home() { - this.client.get().uri("/actuator/env").exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources[?(@.name=='systemProperties')]").exists(); + this.client.get() + .uri("/actuator/env") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources[?(@.name=='systemProperties')]") + .exists(); } @WebEndpointTest void sub() { - this.client.get().uri("/actuator/env/foo").exchange().expectStatus().isOk().expectBody() - .jsonPath("property.source").isEqualTo("test").jsonPath("property.value").isEqualTo("bar"); + this.client.get() + .uri("/actuator/env/foo") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("property.source") + .isEqualTo("test") + .jsonPath("property.value") + .isEqualTo("bar"); } @WebEndpointTest @@ -60,20 +74,35 @@ class EnvironmentEndpointWebIntegrationTests { Map map = new HashMap<>(); map.put("food", null); this.context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("null-value", map)); - this.client.get().uri("/actuator/env?pattern=foo.*").exchange().expectStatus().isOk().expectBody() - .jsonPath(forProperty("test", "foo")).isEqualTo("bar").jsonPath(forProperty("test", "fool")) - .isEqualTo("baz"); + this.client.get() + .uri("/actuator/env?pattern=foo.*") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath(forProperty("test", "foo")) + .isEqualTo("bar") + .jsonPath(forProperty("test", "fool")) + .isEqualTo("baz"); } @WebEndpointTest void nestedPathWhenPlaceholderCannotBeResolvedShouldReturnUnresolvedProperty() { Map map = new HashMap<>(); map.put("my.foo", "${my.bar}"); - this.context.getEnvironment().getPropertySources() - .addFirst(new MapPropertySource("unresolved-placeholder", map)); - this.client.get().uri("/actuator/env/my.foo").exchange().expectStatus().isOk().expectBody() - .jsonPath("property.value").isEqualTo("${my.bar}").jsonPath(forPropertyEntry("unresolved-placeholder")) - .isEqualTo("${my.bar}"); + this.context.getEnvironment() + .getPropertySources() + .addFirst(new MapPropertySource("unresolved-placeholder", map)); + this.client.get() + .uri("/actuator/env/my.foo") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("property.value") + .isEqualTo("${my.bar}") + .jsonPath(forPropertyEntry("unresolved-placeholder")) + .isEqualTo("${my.bar}"); } @WebEndpointTest @@ -82,9 +111,16 @@ class EnvironmentEndpointWebIntegrationTests { map.put("my.foo", "${my.password}"); map.put("my.password", "hello"); this.context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("placeholder", map)); - this.client.get().uri("/actuator/env/my.foo").exchange().expectStatus().isOk().expectBody() - .jsonPath("property.value").isEqualTo("******").jsonPath(forPropertyEntry("placeholder")) - .isEqualTo("******"); + this.client.get() + .uri("/actuator/env/my.foo") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("property.value") + .isEqualTo("******") + .jsonPath(forPropertyEntry("placeholder")) + .isEqualTo("******"); } @WebEndpointTest @@ -96,11 +132,17 @@ class EnvironmentEndpointWebIntegrationTests { void nestedPathMatchedByRegexWhenPlaceholderCannotBeResolvedShouldReturnUnresolvedProperty() { Map map = new HashMap<>(); map.put("my.foo", "${my.bar}"); - this.context.getEnvironment().getPropertySources() - .addFirst(new MapPropertySource("unresolved-placeholder", map)); - this.client.get().uri("/actuator/env?pattern=my.*").exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources[?(@.name=='unresolved-placeholder')].properties.['my.foo'].value") - .isEqualTo("${my.bar}"); + this.context.getEnvironment() + .getPropertySources() + .addFirst(new MapPropertySource("unresolved-placeholder", map)); + this.client.get() + .uri("/actuator/env?pattern=my.*") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources[?(@.name=='unresolved-placeholder')].properties.['my.foo'].value") + .isEqualTo("${my.bar}"); } @WebEndpointTest @@ -109,8 +151,14 @@ class EnvironmentEndpointWebIntegrationTests { map.put("my.foo", "${my.password}"); map.put("my.password", "hello"); this.context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("placeholder", map)); - this.client.get().uri("/actuator/env?pattern=my.*").exchange().expectStatus().isOk().expectBody() - .jsonPath(forProperty("placeholder", "my.foo")).isEqualTo("******"); + this.client.get() + .uri("/actuator/env?pattern=my.*") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath(forProperty("placeholder", "my.foo")) + .isEqualTo("******"); } private String forProperty(String source, String name) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/flyway/FlywayEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/flyway/FlywayEndpointTests.java index 7a943253a9..3ad23181da 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/flyway/FlywayEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/flyway/FlywayEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,14 +39,18 @@ import static org.assertj.core.api.Assertions.assertThat; class FlywayEndpointTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) - .withUserConfiguration(EmbeddedDataSourceConfiguration.class).withBean("endpoint", FlywayEndpoint.class); + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) + .withUserConfiguration(EmbeddedDataSourceConfiguration.class) + .withBean("endpoint", FlywayEndpoint.class); @Test void flywayReportIsProduced() { this.contextRunner.run((context) -> { - Map flywayBeans = context.getBean(FlywayEndpoint.class).flywayBeans() - .getContexts().get(context.getId()).getFlywayBeans(); + Map flywayBeans = context.getBean(FlywayEndpoint.class) + .flywayBeans() + .getContexts() + .get(context.getId()) + .getFlywayBeans(); assertThat(flywayBeans).hasSize(1); assertThat(flywayBeans.values().iterator().next().getMigrations()).hasSize(3); }); @@ -55,15 +59,19 @@ class FlywayEndpointTests { @Test void whenFlywayHasBeenBaselinedFlywayReportIsProduced() { this.contextRunner.withPropertyValues("spring.flyway.baseline-version=2") - .withBean(FlywayMigrationStrategy.class, () -> (flyway) -> { - flyway.baseline(); - flyway.migrate(); - }).run((context) -> { - Map flywayBeans = context.getBean(FlywayEndpoint.class).flywayBeans() - .getContexts().get(context.getId()).getFlywayBeans(); - assertThat(flywayBeans).hasSize(1); - assertThat(flywayBeans.values().iterator().next().getMigrations()).hasSize(3); - }); + .withBean(FlywayMigrationStrategy.class, () -> (flyway) -> { + flyway.baseline(); + flyway.migrate(); + }) + .run((context) -> { + Map flywayBeans = context.getBean(FlywayEndpoint.class) + .flywayBeans() + .getContexts() + .get(context.getId()) + .getFlywayBeans(); + assertThat(flywayBeans).hasSize(1); + assertThat(flywayBeans.values().iterator().next().getMigrations()).hasSize(3); + }); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/hazelcast/Hazelcast4HazelcastHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/hazelcast/Hazelcast4HazelcastHealthIndicatorTests.java index 8ad3aa1da2..3f6593361c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/hazelcast/Hazelcast4HazelcastHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/hazelcast/Hazelcast4HazelcastHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,14 +46,15 @@ class Hazelcast4HazelcastHealthIndicatorTests { @Test void hazelcastUp() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)) - .withPropertyValues("spring.hazelcast.config=hazelcast-4.xml").run((context) -> { - HazelcastInstance hazelcast = context.getBean(HazelcastInstance.class); - Health health = new HazelcastHealthIndicator(hazelcast).health(); - assertThat(health.getStatus()).isEqualTo(Status.UP); - assertThat(health.getDetails()).containsOnlyKeys("name", "uuid").containsEntry("name", - "actuator-hazelcast-4"); - assertThat(health.getDetails().get("uuid")).asString().isNotEmpty(); - }); + .withPropertyValues("spring.hazelcast.config=hazelcast-4.xml") + .run((context) -> { + HazelcastInstance hazelcast = context.getBean(HazelcastInstance.class); + Health health = new HazelcastHealthIndicator(hazelcast).health(); + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails()).containsOnlyKeys("name", "uuid") + .containsEntry("name", "actuator-hazelcast-4"); + assertThat(health.getDetails().get("uuid")).asString().isNotEmpty(); + }); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/hazelcast/HazelcastHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/hazelcast/HazelcastHealthIndicatorTests.java index 053db98a3a..d478843988 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/hazelcast/HazelcastHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/hazelcast/HazelcastHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,14 +42,15 @@ class HazelcastHealthIndicatorTests { @Test void hazelcastUp() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)) - .withPropertyValues("spring.hazelcast.config=hazelcast.xml").run((context) -> { - HazelcastInstance hazelcast = context.getBean(HazelcastInstance.class); - Health health = new HazelcastHealthIndicator(hazelcast).health(); - assertThat(health.getStatus()).isEqualTo(Status.UP); - assertThat(health.getDetails()).containsOnlyKeys("name", "uuid").containsEntry("name", - "actuator-hazelcast"); - assertThat(health.getDetails().get("uuid")).asString().isNotEmpty(); - }); + .withPropertyValues("spring.hazelcast.config=hazelcast.xml") + .run((context) -> { + HazelcastInstance hazelcast = context.getBean(HazelcastInstance.class); + Health health = new HazelcastHealthIndicator(hazelcast).health(); + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails()).containsOnlyKeys("name", "uuid") + .containsEntry("name", "actuator-hazelcast"); + assertThat(health.getDetails().get("uuid")).asString().isNotEmpty(); + }); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/AbstractHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/AbstractHealthIndicatorTests.java index c193b36cc7..1f91b03da4 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/AbstractHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/AbstractHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +57,8 @@ class AbstractHealthIndicatorTests { @Test void healthCheckWhenDownWithExceptionConfiguredLogsHealthCheckFailedMessage(CapturedOutput output) { Health heath = new TestHealthIndicator("Test message", - (builder) -> builder.down().withException(new IllegalStateException("Test exception"))).health(); + (builder) -> builder.down().withException(new IllegalStateException("Test exception"))) + .health(); assertThat(heath.getStatus()).isEqualTo(Status.DOWN); assertThat(output).contains("Test message").contains("Test exception"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/AdditionalHealthEndpointPathTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/AdditionalHealthEndpointPathTests.java index a9d02b061b..5ddbb02444 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/AdditionalHealthEndpointPathTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/AdditionalHealthEndpointPathTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,31 +67,31 @@ class AdditionalHealthEndpointPathTests { @Test void fromPathWithMultipleSegmentsShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> AdditionalHealthEndpointPath.from("server:/my-path/my-sub-path")); + .isThrownBy(() -> AdditionalHealthEndpointPath.from("server:/my-path/my-sub-path")); } @Test void fromPathWithMultipleSegmentsNotStartingWithSlashShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> AdditionalHealthEndpointPath.from("server:my-path/my-sub-path")); + .isThrownBy(() -> AdditionalHealthEndpointPath.from("server:my-path/my-sub-path")); } @Test void pathsWithTheSameNamespaceAndValueAreEqual() { assertThat(AdditionalHealthEndpointPath.from("server:/my-path")) - .isEqualTo(AdditionalHealthEndpointPath.from("server:/my-path")); + .isEqualTo(AdditionalHealthEndpointPath.from("server:/my-path")); } @Test void pathsWithTheDifferentNamespaceAndSameValueAreNotEqual() { assertThat(AdditionalHealthEndpointPath.from("server:/my-path")) - .isNotEqualTo((AdditionalHealthEndpointPath.from("management:/my-path"))); + .isNotEqualTo((AdditionalHealthEndpointPath.from("management:/my-path"))); } @Test void pathsWithTheSameNamespaceAndValuesWithNoSlashAreEqual() { assertThat(AdditionalHealthEndpointPath.from("server:/my-path")) - .isEqualTo((AdditionalHealthEndpointPath.from("server:my-path"))); + .isEqualTo((AdditionalHealthEndpointPath.from("server:my-path"))); } @Test @@ -102,13 +102,13 @@ class AdditionalHealthEndpointPathTests { @Test void ofWithNullPathShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> AdditionalHealthEndpointPath.of(WebServerNamespace.SERVER, null)); + .isThrownBy(() -> AdditionalHealthEndpointPath.of(WebServerNamespace.SERVER, null)); } @Test void ofWithMultipleSegmentValueShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> AdditionalHealthEndpointPath.of(WebServerNamespace.SERVER, "/my-path/my-subpath")); + .isThrownBy(() -> AdditionalHealthEndpointPath.of(WebServerNamespace.SERVER, "/my-path/my-subpath")); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthContributorReactiveAdapterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthContributorReactiveAdapterTests.java index ecc87fdb34..1a2916ad08 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthContributorReactiveAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthContributorReactiveAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,14 +34,14 @@ class CompositeHealthContributorReactiveAdapterTests { @Test void createWhenDelegateIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new CompositeHealthContributorReactiveAdapter(null)) - .withMessage("Delegate must not be null"); + .withMessage("Delegate must not be null"); } @Test void iteratorWhenDelegateContainsHealthIndicatorAdaptsDelegate() { HealthIndicator indicator = () -> Health.up().withDetail("spring", "boot").build(); CompositeHealthContributor delegate = CompositeHealthContributor - .fromMap(Collections.singletonMap("test", indicator)); + .fromMap(Collections.singletonMap("test", indicator)); CompositeHealthContributorReactiveAdapter adapter = new CompositeHealthContributorReactiveAdapter(delegate); Iterator> iterator = adapter.iterator(); assertThat(iterator.hasNext()).isTrue(); @@ -57,9 +57,9 @@ class CompositeHealthContributorReactiveAdapterTests { void iteratorWhenDelegateContainsCompositeHealthContributorAdaptsDelegate() { HealthIndicator indicator = () -> Health.up().withDetail("spring", "boot").build(); CompositeHealthContributor composite = CompositeHealthContributor - .fromMap(Collections.singletonMap("test1", indicator)); + .fromMap(Collections.singletonMap("test1", indicator)); CompositeHealthContributor delegate = CompositeHealthContributor - .fromMap(Collections.singletonMap("test2", composite)); + .fromMap(Collections.singletonMap("test2", composite)); CompositeHealthContributorReactiveAdapter adapter = new CompositeHealthContributorReactiveAdapter(delegate); Iterator> iterator = adapter.iterator(); assertThat(iterator.hasNext()).isTrue(); @@ -67,7 +67,7 @@ class CompositeHealthContributorReactiveAdapterTests { assertThat(adapted.getName()).isEqualTo("test2"); assertThat(adapted.getContributor()).isInstanceOf(CompositeReactiveHealthContributor.class); ReactiveHealthContributor nested = ((CompositeReactiveHealthContributor) adapted.getContributor()) - .getContributor("test1"); + .getContributor("test1"); Health health = ((ReactiveHealthIndicator) nested).getHealth(true).block(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails()).containsEntry("spring", "boot"); @@ -77,7 +77,7 @@ class CompositeHealthContributorReactiveAdapterTests { void getContributorAdaptsDelegate() { HealthIndicator indicator = () -> Health.up().withDetail("spring", "boot").build(); CompositeHealthContributor delegate = CompositeHealthContributor - .fromMap(Collections.singletonMap("test", indicator)); + .fromMap(Collections.singletonMap("test", indicator)); CompositeHealthContributorReactiveAdapter adapter = new CompositeHealthContributorReactiveAdapter(delegate); ReactiveHealthContributor adapted = adapter.getContributor("test"); Health health = ((ReactiveHealthIndicator) adapted).getHealth(true).block(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthTests.java index bb2b3d192b..0d8d51112e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,8 @@ class CompositeHealthTests { @Test void createWhenStatusIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new CompositeHealth(ApiVersion.V3, null, Collections.emptyMap())) - .withMessage("Status must not be null"); + .isThrownBy(() -> new CompositeHealth(ApiVersion.V3, null, Collections.emptyMap())) + .withMessage("Status must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultContributorRegistryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultContributorRegistryTests.java index 00e1e6b195..6316adfe62 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultContributorRegistryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultContributorRegistryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,14 +53,14 @@ abstract class DefaultContributorRegistryTests { @Test void createWhenContributorsIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new DefaultContributorRegistry<>(null)) - .withMessage("Contributors must not be null"); + .withMessage("Contributors must not be null"); } @Test void createWhenNameFactoryIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DefaultContributorRegistry<>(Collections.emptyMap(), null)) - .withMessage("NameFactory must not be null"); + .isThrownBy(() -> new DefaultContributorRegistry<>(Collections.emptyMap(), null)) + .withMessage("NameFactory must not be null"); } @Test @@ -80,13 +80,13 @@ abstract class DefaultContributorRegistryTests { @Test void registerContributorWhenNameIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.registry.registerContributor(null, this.one)) - .withMessage("Name must not be null"); + .withMessage("Name must not be null"); } @Test void registerContributorWhenContributorIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.registry.registerContributor("one", null)) - .withMessage("Contributor must not be null"); + .withMessage("Contributor must not be null"); } @Test @@ -102,7 +102,7 @@ abstract class DefaultContributorRegistryTests { void registerContributorWhenNameAlreadyUsedThrowsException() { this.registry.registerContributor("one", this.one); assertThatIllegalStateException().isThrownBy(() -> this.registry.registerContributor("one", this.two)) - .withMessageContaining("A contributor named \"one\" has already been registered"); + .withMessageContaining("A contributor named \"one\" has already been registered"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthContributorNameFactoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthContributorNameFactoryTests.java index e74194bf83..8079461177 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthContributorNameFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthContributorNameFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,9 +47,9 @@ class HealthContributorNameFactoryTests { @Test void applyWhenNameContainsSuffixReturnsName() { assertThat(HealthContributorNameFactory.INSTANCE.apply("testHealthIndicatorTest")) - .isEqualTo("testHealthIndicatorTest"); + .isEqualTo("testHealthIndicatorTest"); assertThat(HealthContributorNameFactory.INSTANCE.apply("testHealthContributorTest")) - .isEqualTo("testHealthContributorTest"); + .isEqualTo("testHealthContributorTest"); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointGroupsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointGroupsTests.java index ba176cb310..a9e8058a56 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointGroupsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointGroupsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,14 +34,14 @@ class HealthEndpointGroupsTests { @Test void ofWhenPrimaryIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> HealthEndpointGroups.of(null, Collections.emptyMap())) - .withMessage("Primary must not be null"); + .withMessage("Primary must not be null"); } @Test void ofWhenAdditionalIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> HealthEndpointGroups.of(mock(HealthEndpointGroup.class), null)) - .withMessage("Additional must not be null"); + .isThrownBy(() -> HealthEndpointGroups.of(mock(HealthEndpointGroup.class), null)) + .withMessage("Additional must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointSupportTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointSupportTests.java index f5985a1fba..50cc381a8c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointSupportTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,13 +64,13 @@ abstract class HealthEndpointSupportTests, @Test void createWhenRegistryIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> create(null, this.groups)) - .withMessage("Registry must not be null"); + .withMessage("Registry must not be null"); } @Test void createWhenGroupsIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> create(this.registry, null)) - .withMessage("Groups must not be null"); + .withMessage("Groups must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointTests.java index 02d20a5955..167ad6a0bc 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,8 @@ class HealthEndpointTests extends void healthWithNoContributorReturnsUp() { assertThat(this.registry).isEmpty(); HealthComponent health = create(this.registry, - HealthEndpointGroups.of(mock(HealthEndpointGroup.class), Collections.emptyMap())).health(); + HealthEndpointGroups.of(mock(HealthEndpointGroup.class), Collections.emptyMap())) + .health(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health).isInstanceOf(Health.class); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebExtensionTests.java index 56f44169ce..f340799faa 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebExtensionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,7 +56,7 @@ class HealthEndpointWebExtensionTests extends assertThat(this.registry).isEmpty(); WebEndpointResponse response = create(this.registry, HealthEndpointGroups.of(mock(HealthEndpointGroup.class), Collections.emptyMap())) - .health(ApiVersion.LATEST, WebServerNamespace.SERVER, SecurityContext.NONE); + .health(ApiVersion.LATEST, WebServerNamespace.SERVER, SecurityContext.NONE); assertThat(response.getStatus()).isEqualTo(200); HealthComponent health = response.getBody(); assertThat(health.getStatus()).isEqualTo(Status.UP); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebIntegrationTests.java index 4db81a4971..12a7d32717 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,32 +51,70 @@ class HealthEndpointWebIntegrationTests { @WebEndpointTest void whenHealthIsUp200ResponseIsReturned(WebTestClient client) { - client.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() - .expectBody().jsonPath("status").isEqualTo("UP").jsonPath("components.alpha.status").isEqualTo("UP") - .jsonPath("components.bravo.status").isEqualTo("UP"); + client.get() + .uri("/actuator/health") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("status") + .isEqualTo("UP") + .jsonPath("components.alpha.status") + .isEqualTo("UP") + .jsonPath("components.bravo.status") + .isEqualTo("UP"); } @WebEndpointTest void whenHealthIsUpAndAcceptsV3Request200ResponseIsReturned(WebTestClient client) { - client.get().uri("/actuator/health").headers((headers) -> headers.set(HttpHeaders.ACCEPT, V3_JSON)).exchange() - .expectStatus().isOk().expectBody().jsonPath("status").isEqualTo("UP") - .jsonPath("components.alpha.status").isEqualTo("UP").jsonPath("components.bravo.status") - .isEqualTo("UP"); + client.get() + .uri("/actuator/health") + .headers((headers) -> headers.set(HttpHeaders.ACCEPT, V3_JSON)) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("status") + .isEqualTo("UP") + .jsonPath("components.alpha.status") + .isEqualTo("UP") + .jsonPath("components.bravo.status") + .isEqualTo("UP"); } @WebEndpointTest void whenHealthIsUpAndAcceptsAllRequest200ResponseIsReturned(WebTestClient client) { - client.get().uri("/actuator/health").headers((headers) -> headers.set(HttpHeaders.ACCEPT, "*/*")).exchange() - .expectStatus().isOk().expectBody().jsonPath("status").isEqualTo("UP") - .jsonPath("components.alpha.status").isEqualTo("UP").jsonPath("components.bravo.status") - .isEqualTo("UP"); + client.get() + .uri("/actuator/health") + .headers((headers) -> headers.set(HttpHeaders.ACCEPT, "*/*")) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("status") + .isEqualTo("UP") + .jsonPath("components.alpha.status") + .isEqualTo("UP") + .jsonPath("components.bravo.status") + .isEqualTo("UP"); } @WebEndpointTest void whenHealthIsUpAndV2Request200ResponseIsReturnedInV2Format(WebTestClient client) { - client.get().uri("/actuator/health").headers((headers) -> headers.set(HttpHeaders.ACCEPT, V2_JSON)).exchange() - .expectStatus().isOk().expectBody().jsonPath("status").isEqualTo("UP").jsonPath("details.alpha.status") - .isEqualTo("UP").jsonPath("details.bravo.status").isEqualTo("UP"); + client.get() + .uri("/actuator/health") + .headers((headers) -> headers.set(HttpHeaders.ACCEPT, V2_JSON)) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("status") + .isEqualTo("UP") + .jsonPath("details.alpha.status") + .isEqualTo("UP") + .jsonPath("details.bravo.status") + .isEqualTo("UP"); } @WebEndpointTest @@ -84,10 +122,21 @@ class HealthEndpointWebIntegrationTests { HealthIndicator healthIndicator = () -> Health.down().build(); ReactiveHealthIndicator reactiveHealthIndicator = () -> Mono.just(Health.down().build()); withHealthContributor(context, "charlie", healthIndicator, reactiveHealthIndicator, - () -> client.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE).expectBody().jsonPath("status").isEqualTo("DOWN") - .jsonPath("components.alpha.status").isEqualTo("UP").jsonPath("components.bravo.status") - .isEqualTo("UP").jsonPath("components.charlie.status").isEqualTo("DOWN")); + () -> client.get() + .uri("/actuator/health") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE) + .expectBody() + .jsonPath("status") + .isEqualTo("DOWN") + .jsonPath("components.alpha.status") + .isEqualTo("UP") + .jsonPath("components.bravo.status") + .isEqualTo("UP") + .jsonPath("components.charlie.status") + .isEqualTo("DOWN")); } @WebEndpointTest @@ -95,23 +144,35 @@ class HealthEndpointWebIntegrationTests { HealthIndicator healthIndicator = () -> Health.down().build(); ReactiveHealthIndicator reactiveHealthIndicator = () -> Mono.just(Health.down().build()); withHealthContributor(context, "charlie", healthIndicator, reactiveHealthIndicator, - () -> client.get().uri("/actuator/health/charlie").accept(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isEqualTo(HttpStatus.SERVICE_UNAVAILABLE).expectBody().jsonPath("status") - .isEqualTo("DOWN")); + () -> client.get() + .uri("/actuator/health/charlie") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE) + .expectBody() + .jsonPath("status") + .isEqualTo("DOWN")); } @WebEndpointTest void whenComponentInstanceHealthIsDown503ResponseIsReturned(ApplicationContext context, WebTestClient client) { HealthIndicator healthIndicator = () -> Health.down().build(); CompositeHealthContributor composite = CompositeHealthContributor - .fromMap(Collections.singletonMap("one", healthIndicator)); + .fromMap(Collections.singletonMap("one", healthIndicator)); ReactiveHealthIndicator reactiveHealthIndicator = () -> Mono.just(Health.down().build()); CompositeReactiveHealthContributor reactiveComposite = CompositeReactiveHealthContributor - .fromMap(Collections.singletonMap("one", reactiveHealthIndicator)); + .fromMap(Collections.singletonMap("one", reactiveHealthIndicator)); withHealthContributor(context, "charlie", composite, reactiveComposite, - () -> client.get().uri("/actuator/health/charlie/one").accept(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isEqualTo(HttpStatus.SERVICE_UNAVAILABLE).expectBody().jsonPath("status") - .isEqualTo("DOWN")); + () -> client.get() + .uri("/actuator/health/charlie/one") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE) + .expectBody() + .jsonPath("status") + .isEqualTo("DOWN")); } private void withHealthContributor(ApplicationContext context, String name, HealthContributor healthContributor, @@ -154,9 +215,19 @@ class HealthEndpointWebIntegrationTests { ReactiveHealthContributor reactiveBravo = (reactiveHealthContributorRegistry != null) ? reactiveHealthContributorRegistry.unregisterContributor(name) : null; try { - client.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() - .expectBody().jsonPath("status").isEqualTo("UP").jsonPath("components.alpha.status").isEqualTo("UP") - .jsonPath("components.bravo.status").doesNotExist(); + client.get() + .uri("/actuator/health") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("status") + .isEqualTo("UP") + .jsonPath("components.alpha.status") + .isEqualTo("UP") + .jsonPath("components.bravo.status") + .doesNotExist(); } finally { healthContributorRegistry.registerContributor(name, bravo); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthIndicatorReactiveAdapterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthIndicatorReactiveAdapterTests.java index 1506c751f9..bfb32465cb 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthIndicatorReactiveAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthIndicatorReactiveAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,8 @@ class HealthIndicatorReactiveAdapterTests { void delegateRunsOnTheElasticScheduler() { String currentThread = Thread.currentThread().getName(); HealthIndicator delegate = () -> Health - .status(Thread.currentThread().getName().equals(currentThread) ? Status.DOWN : Status.UP).build(); + .status(Thread.currentThread().getName().equals(currentThread) ? Status.DOWN : Status.UP) + .build(); HealthIndicatorReactiveAdapter adapter = new HealthIndicatorReactiveAdapter(delegate); StepVerifier.create(adapter.health()).expectNext(Health.status(Status.UP).build()).verifyComplete(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java index 81e88378e1..540ba54e39 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,7 +40,7 @@ class HealthTests { @Test void statusMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new Health.Builder(null, null)) - .withMessageContaining("Status must not be null"); + .withMessageContaining("Status must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/NamedContributorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/NamedContributorTests.java index f357eccc53..a26c1e460e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/NamedContributorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/NamedContributorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,13 +38,13 @@ class NamedContributorTests { @Test void ofWhenNameIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> NamedContributor.of(null, "two")) - .withMessage("Name must not be null"); + .withMessage("Name must not be null"); } @Test void ofWhenContributorIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> NamedContributor.of("one", null)) - .withMessage("Contributor must not be null"); + .withMessage("Contributor must not be null"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/NamedContributorsMapAdapterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/NamedContributorsMapAdapterTests.java index c33214ef1d..9794a32b09 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/NamedContributorsMapAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/NamedContributorsMapAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,39 +39,39 @@ class NamedContributorsMapAdapterTests { @Test void createWhenMapIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(null, Function.identity())) - .withMessage("Map must not be null"); + .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(null, Function.identity())) + .withMessage("Map must not be null"); } @Test void createWhenValueAdapterIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(Collections.emptyMap(), null)) - .withMessage("ValueAdapter must not be null"); + .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(Collections.emptyMap(), null)) + .withMessage("ValueAdapter must not be null"); } @Test void createWhenMapContainsNullValueThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(Collections.singletonMap("test", null), - Function.identity())) - .withMessage("Map must not contain null values"); + .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(Collections.singletonMap("test", null), + Function.identity())) + .withMessage("Map must not contain null values"); } @Test void createWhenMapContainsNullKeyThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(Collections.singletonMap(null, "test"), - Function.identity())) - .withMessage("Map must not contain null keys"); + .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(Collections.singletonMap(null, "test"), + Function.identity())) + .withMessage("Map must not contain null keys"); } @Test void createWhenMapContainsKeyWithSlashThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(Collections.singletonMap("test/key", "test"), - Function.identity())) - .withMessage("Map keys must not contain a '/'"); + .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(Collections.singletonMap("test/key", "test"), + Function.identity())) + .withMessage("Map keys must not contain a '/'"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthContributorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthContributorTests.java index 201d79e0ac..2acf5a61f3 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthContributorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthContributorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ class ReactiveHealthContributorTests { @Test void adaptWhenNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ReactiveHealthContributor.adapt(null)) - .withMessage("HealthContributor must not be null"); + .withMessage("HealthContributor must not be null"); } @Test @@ -50,7 +50,7 @@ class ReactiveHealthContributorTests { void adaptWhenCompositeHealthContributorReturnsCompositeHealthContributorReactiveAdapter() { HealthIndicator indicator = () -> Health.outOfService().build(); CompositeHealthContributor contributor = CompositeHealthContributor - .fromMap(Collections.singletonMap("a", indicator)); + .fromMap(Collections.singletonMap("a", indicator)); ReactiveHealthContributor adapted = ReactiveHealthContributor.adapt(contributor); assertThat(adapted).isInstanceOf(CompositeHealthContributorReactiveAdapter.class); ReactiveHealthContributor contained = ((CompositeReactiveHealthContributor) adapted).getContributor("a"); @@ -60,8 +60,8 @@ class ReactiveHealthContributorTests { @Test void adaptWhenUnknownThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> ReactiveHealthContributor.adapt(mock(HealthContributor.class))) - .withMessage("Unknown HealthContributor type"); + .isThrownBy(() -> ReactiveHealthContributor.adapt(mock(HealthContributor.class))) + .withMessage("Unknown HealthContributor type"); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtensionTests.java index 92c7e00665..60a5958109 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtensionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,8 @@ class ReactiveHealthEndpointWebExtensionTests extends void healthReturnsSystemHealth() { this.registry.registerContributor("test", createContributor(this.up)); WebEndpointResponse response = create(this.registry, this.groups) - .health(ApiVersion.LATEST, null, SecurityContext.NONE).block(); + .health(ApiVersion.LATEST, null, SecurityContext.NONE) + .block(); HealthComponent health = response.getBody(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health).isInstanceOf(SystemHealth.class); @@ -56,7 +57,8 @@ class ReactiveHealthEndpointWebExtensionTests extends assertThat(this.registry).isEmpty(); WebEndpointResponse response = create(this.registry, HealthEndpointGroups.of(mock(HealthEndpointGroup.class), Collections.emptyMap())) - .health(ApiVersion.LATEST, null, SecurityContext.NONE).block(); + .health(ApiVersion.LATEST, null, SecurityContext.NONE) + .block(); assertThat(response.getStatus()).isEqualTo(200); HealthComponent health = response.getBody(); assertThat(health.getStatus()).isEqualTo(Status.UP); @@ -67,7 +69,8 @@ class ReactiveHealthEndpointWebExtensionTests extends void healthWhenPathDoesNotExistReturnsHttp404() { this.registry.registerContributor("test", createContributor(this.up)); WebEndpointResponse response = create(this.registry, this.groups) - .health(ApiVersion.LATEST, null, SecurityContext.NONE, "missing").block(); + .health(ApiVersion.LATEST, null, SecurityContext.NONE, "missing") + .block(); assertThat(response.getBody()).isNull(); assertThat(response.getStatus()).isEqualTo(404); } @@ -76,7 +79,8 @@ class ReactiveHealthEndpointWebExtensionTests extends void healthWhenPathExistsReturnsHealth() { this.registry.registerContributor("test", createContributor(this.up)); WebEndpointResponse response = create(this.registry, this.groups) - .health(ApiVersion.LATEST, null, SecurityContext.NONE, "test").block(); + .health(ApiVersion.LATEST, null, SecurityContext.NONE, "test") + .block(); assertThat(response.getBody()).isEqualTo(this.up); assertThat(response.getStatus()).isEqualTo(200); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorImplementationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorImplementationTests.java index aaf3fd1281..f9f715514f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorImplementationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorImplementationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,23 +39,25 @@ class ReactiveHealthIndicatorImplementationTests { @Test void healthUp(CapturedOutput output) { StepVerifier.create(new SimpleReactiveHealthIndicator().health()) - .consumeNextWith((health) -> assertThat(health).isEqualTo(Health.up().build())).verifyComplete(); + .consumeNextWith((health) -> assertThat(health).isEqualTo(Health.up().build())) + .verifyComplete(); assertThat(output).doesNotContain("Health check failed for simple"); } @Test void healthDownWithCustomErrorMessage(CapturedOutput output) { - StepVerifier.create(new CustomErrorMessageReactiveHealthIndicator().health()).consumeNextWith( - (health) -> assertThat(health).isEqualTo(Health.down(new UnsupportedOperationException()).build())) - .verifyComplete(); + StepVerifier.create(new CustomErrorMessageReactiveHealthIndicator().health()) + .consumeNextWith( + (health) -> assertThat(health).isEqualTo(Health.down(new UnsupportedOperationException()).build())) + .verifyComplete(); assertThat(output).contains("Health check failed for custom"); } @Test void healthDownWithCustomErrorMessageFunction(CapturedOutput output) { StepVerifier.create(new CustomErrorMessageFunctionReactiveHealthIndicator().health()) - .consumeNextWith((health) -> assertThat(health).isEqualTo(Health.down(new RuntimeException()).build())) - .verifyComplete(); + .consumeNextWith((health) -> assertThat(health).isEqualTo(Health.down(new RuntimeException()).build())) + .verifyComplete(); assertThat(output).contains("Health check failed with RuntimeException"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/SimpleHttpCodeStatusMapperTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/SimpleHttpCodeStatusMapperTests.java index 0cc7564b01..7aac9e40eb 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/SimpleHttpCodeStatusMapperTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/SimpleHttpCodeStatusMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ class SimpleHttpCodeStatusMapperTests { assertThat(mapper.getStatusCode(Status.UP)).isEqualTo(WebEndpointResponse.STATUS_OK); assertThat(mapper.getStatusCode(Status.DOWN)).isEqualTo(WebEndpointResponse.STATUS_SERVICE_UNAVAILABLE); assertThat(mapper.getStatusCode(Status.OUT_OF_SERVICE)) - .isEqualTo(WebEndpointResponse.STATUS_SERVICE_UNAVAILABLE); + .isEqualTo(WebEndpointResponse.STATUS_SERVICE_UNAVAILABLE); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/StatusTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/StatusTests.java index 0125682c68..6590588afb 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/StatusTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/StatusTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,13 +32,13 @@ class StatusTests { @Test void createWhenCodeIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new Status(null, "")) - .withMessage("Code must not be null"); + .withMessage("Code must not be null"); } @Test void createWhenDescriptionIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new Status("code", null)) - .withMessage("Description must not be null"); + .withMessage("Description must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointWebIntegrationTests.java index d05a98dc6d..3c88db7276 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,10 +40,21 @@ class InfoEndpointWebIntegrationTests { @WebEndpointTest void info(WebTestClient client) { - client.get().uri("/actuator/info").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() - .expectBody().jsonPath("beanName1.key11").isEqualTo("value11").jsonPath("beanName1.key12") - .isEqualTo("value12").jsonPath("beanName2.key21").isEqualTo("value21").jsonPath("beanName2.key22") - .isEqualTo("value22"); + client.get() + .uri("/actuator/info") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("beanName1.key11") + .isEqualTo("value11") + .jsonPath("beanName1.key12") + .isEqualTo("value12") + .jsonPath("beanName2.key21") + .isEqualTo("value21") + .jsonPath("beanName2.key22") + .isEqualTo("value22"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointWebIntegrationTests.java index 76593213de..6ee57ee54b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,16 +34,29 @@ class IntegrationGraphEndpointWebIntegrationTests { @WebEndpointTest void graph(WebTestClient client) { - client.get().uri("/actuator/integrationgraph").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isOk().expectBody().jsonPath("contentDescriptor.providerVersion").isNotEmpty() - .jsonPath("contentDescriptor.providerFormatVersion").isEqualTo(1.2f) - .jsonPath("contentDescriptor.provider").isEqualTo("spring-integration"); + client.get() + .uri("/actuator/integrationgraph") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contentDescriptor.providerVersion") + .isNotEmpty() + .jsonPath("contentDescriptor.providerFormatVersion") + .isEqualTo(1.2f) + .jsonPath("contentDescriptor.provider") + .isEqualTo("spring-integration"); } @WebEndpointTest void rebuild(WebTestClient client) { - client.post().uri("/actuator/integrationgraph").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isNoContent(); + client.post() + .uri("/actuator/integrationgraph") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isNoContent(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/ldap/LdapHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/ldap/LdapHealthIndicatorTests.java index 9af6b7950a..15653d7eb7 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/ldap/LdapHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/ldap/LdapHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ class LdapHealthIndicatorTests { void ldapIsDown() { LdapTemplate ldapTemplate = mock(LdapTemplate.class); given(ldapTemplate.executeReadOnly((ContextExecutor) any())) - .willThrow(new CommunicationException(new javax.naming.CommunicationException("Connection failed"))); + .willThrow(new CommunicationException(new javax.naming.CommunicationException("Connection failed"))); LdapHealthIndicator healthIndicator = new LdapHealthIndicator(ldapTemplate); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpointTests.java index 4410b30f27..75be5631ef 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,15 +53,17 @@ import static org.assertj.core.api.Assertions.assertThat; class LiquibaseEndpointTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class, LiquibaseAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true"); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, LiquibaseAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test void liquibaseReportIsReturned() { this.contextRunner.withUserConfiguration(Config.class).run((context) -> { - Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class).liquibaseBeans() - .getContexts().get(context.getId()).getLiquibaseBeans(); + Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class) + .liquibaseBeans() + .getContexts() + .get(context.getId()) + .getLiquibaseBeans(); assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); }); } @@ -70,8 +72,11 @@ class LiquibaseEndpointTests { void liquibaseReportIsReturnedForContextHierarchy() { this.contextRunner.withUserConfiguration().run((parent) -> { this.contextRunner.withUserConfiguration(Config.class).withParent(parent).run((context) -> { - Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class).liquibaseBeans() - .getContexts().get(parent.getId()).getLiquibaseBeans(); + Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class) + .liquibaseBeans() + .getContexts() + .get(parent.getId()) + .getLiquibaseBeans(); assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); }); }); @@ -80,23 +85,30 @@ class LiquibaseEndpointTests { @Test void invokeWithCustomSchema() { this.contextRunner.withUserConfiguration(Config.class, DataSourceWithSchemaConfiguration.class) - .withPropertyValues("spring.liquibase.default-schema=CUSTOMSCHEMA").run((context) -> { - Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class) - .liquibaseBeans().getContexts().get(context.getId()).getLiquibaseBeans(); - assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); - }); + .withPropertyValues("spring.liquibase.default-schema=CUSTOMSCHEMA") + .run((context) -> { + Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class) + .liquibaseBeans() + .getContexts() + .get(context.getId()) + .getLiquibaseBeans(); + assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); + }); } @Test void invokeWithCustomTables() { this.contextRunner.withUserConfiguration(Config.class) - .withPropertyValues("spring.liquibase.database-change-log-lock-table=liquibase_database_changelog_lock", - "spring.liquibase.database-change-log-table=liquibase_database_changelog") - .run((context) -> { - Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class) - .liquibaseBeans().getContexts().get(context.getId()).getLiquibaseBeans(); - assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); - }); + .withPropertyValues("spring.liquibase.database-change-log-lock-table=liquibase_database_changelog_lock", + "spring.liquibase.database-change-log-table=liquibase_database_changelog") + .run((context) -> { + Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class) + .liquibaseBeans() + .getContexts() + .get(context.getId()) + .getLiquibaseBeans(); + assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); + }); } @Test @@ -112,16 +124,19 @@ class LiquibaseEndpointTests { @Test void whenMultipleLiquibaseBeansArePresentChangeSetsAreCorrectlyReportedForEachBean() { this.contextRunner.withUserConfiguration(Config.class, MultipleDataSourceLiquibaseConfiguration.class) - .run((context) -> { - Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class) - .liquibaseBeans().getContexts().get(context.getId()).getLiquibaseBeans(); - assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); - assertThat(liquibaseBeans.get("liquibase").getChangeSets().get(0).getChangeLog()) - .isEqualTo("db/changelog/db.changelog-master.yaml"); - assertThat(liquibaseBeans.get("liquibaseBackup").getChangeSets()).hasSize(1); - assertThat(liquibaseBeans.get("liquibaseBackup").getChangeSets().get(0).getChangeLog()) - .isEqualTo("db/changelog/db.changelog-master-backup.yaml"); - }); + .run((context) -> { + Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class) + .liquibaseBeans() + .getContexts() + .get(context.getId()) + .getLiquibaseBeans(); + assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); + assertThat(liquibaseBeans.get("liquibase").getChangeSets().get(0).getChangeLog()) + .isEqualTo("db/changelog/db.changelog-master.yaml"); + assertThat(liquibaseBeans.get("liquibaseBackup").getChangeSets()).hasSize(1); + assertThat(liquibaseBeans.get("liquibaseBackup").getChangeSets().get(0).getChangeLog()) + .isEqualTo("db/changelog/db.changelog-master-backup.yaml"); + }); } private boolean getAutoCommit(DataSource dataSource) throws SQLException { @@ -146,8 +161,9 @@ class LiquibaseEndpointTests { @Bean DataSource dataSource() { DataSource dataSource = new EmbeddedDatabaseBuilder() - .setType(EmbeddedDatabaseConnection.get(getClass().getClassLoader()).getType()) - .setName(UUID.randomUUID().toString()).build(); + .setType(EmbeddedDatabaseConnection.get(getClass().getClassLoader()).getType()) + .setName(UUID.randomUUID().toString()) + .build(); DatabaseInitializationSettings settings = new DatabaseInitializationSettings(); settings.setSchemaLocations(Arrays.asList("classpath:/db/create-custom-schema.sql")); DataSourceScriptDatabaseInitializer initializer = new DataSourceScriptDatabaseInitializer(dataSource, @@ -183,7 +199,8 @@ class LiquibaseEndpointTests { private DataSource createEmbeddedDatabase() { return new EmbeddedDatabaseBuilder().generateUniqueName(true) - .setType(EmbeddedDatabaseConnection.HSQLDB.getType()).build(); + .setType(EmbeddedDatabaseConnection.HSQLDB.getType()) + .build(); } private SpringLiquibase createSpringLiquibase(String changeLog, DataSource dataSource) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointWebIntegrationTests.java index b7566eeace..5f1248f7ff 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,14 +56,29 @@ class LogFileWebEndpointWebIntegrationTests { @WebEndpointTest void getRequestProducesResponseWithLogFile() { - this.client.get().uri("/actuator/logfile").exchange().expectStatus().isOk().expectHeader() - .contentType("text/plain; charset=UTF-8").expectBody(String.class).isEqualTo("--TEST--"); + this.client.get() + .uri("/actuator/logfile") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType("text/plain; charset=UTF-8") + .expectBody(String.class) + .isEqualTo("--TEST--"); } @WebEndpointTest void getRequestThatAcceptsTextPlainProducesResponseWithLogFile() { - this.client.get().uri("/actuator/logfile").accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isOk() - .expectHeader().contentType("text/plain; charset=UTF-8").expectBody(String.class).isEqualTo("--TEST--"); + this.client.get() + .uri("/actuator/logfile") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType("text/plain; charset=UTF-8") + .expectBody(String.class) + .isEqualTo("--TEST--"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointTests.java index 5c7515e3b2..f885d51e49 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,7 +64,7 @@ class LoggersEndpointTests { @SuppressWarnings("unchecked") void loggersShouldReturnLoggerConfigurationsWithNoLoggerGroups() { given(this.loggingSystem.getLoggerConfigurations()) - .willReturn(Collections.singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); + .willReturn(Collections.singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); given(this.loggingSystem.getSupportedLogLevels()).willReturn(EnumSet.allOf(LogLevel.class)); Map result = new LoggersEndpoint(this.loggingSystem, new LoggerGroups()).loggers(); Map loggers = (Map) result.get("loggers"); @@ -82,7 +82,7 @@ class LoggersEndpointTests { @SuppressWarnings("unchecked") void loggersShouldReturnLoggerConfigurationsWithLoggerGroups() { given(this.loggingSystem.getLoggerConfigurations()) - .willReturn(Collections.singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); + .willReturn(Collections.singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); given(this.loggingSystem.getSupportedLogLevels()).willReturn(EnumSet.allOf(LogLevel.class)); Map result = new LoggersEndpoint(this.loggingSystem, this.loggerGroups).loggers(); Map loggerGroups = (Map) result.get("groups"); @@ -102,9 +102,9 @@ class LoggersEndpointTests { @Test void loggerLevelsWhenNameSpecifiedShouldReturnLevels() { given(this.loggingSystem.getLoggerConfiguration("ROOT")) - .willReturn(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG)); + .willReturn(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG)); SingleLoggerLevels levels = (SingleLoggerLevels) new LoggersEndpoint(this.loggingSystem, this.loggerGroups) - .loggerLevels("ROOT"); + .loggerLevels("ROOT"); assertThat(levels.getConfiguredLevel()).isNull(); assertThat(levels.getEffectiveLevel()).isEqualTo("DEBUG"); } @@ -112,7 +112,7 @@ class LoggersEndpointTests { @Test void groupNameSpecifiedShouldReturnConfiguredLevelAndMembers() { GroupLoggerLevels levels = (GroupLoggerLevels) new LoggersEndpoint(this.loggingSystem, this.loggerGroups) - .loggerLevels("test"); + .loggerLevels("test"); assertThat(levels.getConfiguredLevel()).isEqualTo("DEBUG"); assertThat(levels.getMembers()).isEqualTo(Collections.singletonList("test.member")); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointWebIntegrationTests.java index f075cec94c..ad83eb790f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointWebIntegrationTests.java @@ -84,24 +84,48 @@ class LoggersEndpointWebIntegrationTests { void getLoggerShouldReturnAllLoggerConfigurationsWithLoggerGroups() { setLogLevelToDebug("test"); given(this.loggingSystem.getLoggerConfigurations()) - .willReturn(Collections.singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); - this.client.get().uri("/actuator/loggers").exchange().expectStatus().isOk().expectBody().jsonPath("$.length()") - .isEqualTo(3).jsonPath("levels") - .isEqualTo(jsonArrayOf("OFF", "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE")) - .jsonPath("loggers.length()").isEqualTo(1).jsonPath("loggers.ROOT.length()").isEqualTo(2) - .jsonPath("loggers.ROOT.configuredLevel").isEqualTo(null).jsonPath("loggers.ROOT.effectiveLevel") - .isEqualTo("DEBUG").jsonPath("groups.length()").isEqualTo(2).jsonPath("groups.test.configuredLevel") - .isEqualTo("DEBUG"); + .willReturn(Collections.singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); + this.client.get() + .uri("/actuator/loggers") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$.length()") + .isEqualTo(3) + .jsonPath("levels") + .isEqualTo(jsonArrayOf("OFF", "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE")) + .jsonPath("loggers.length()") + .isEqualTo(1) + .jsonPath("loggers.ROOT.length()") + .isEqualTo(2) + .jsonPath("loggers.ROOT.configuredLevel") + .isEqualTo(null) + .jsonPath("loggers.ROOT.effectiveLevel") + .isEqualTo("DEBUG") + .jsonPath("groups.length()") + .isEqualTo(2) + .jsonPath("groups.test.configuredLevel") + .isEqualTo("DEBUG"); } @WebEndpointTest void getLoggerShouldReturnLogLevels() { setLogLevelToDebug("test"); given(this.loggingSystem.getLoggerConfiguration("ROOT")) - .willReturn(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG)); - this.client.get().uri("/actuator/loggers/ROOT").exchange().expectStatus().isOk().expectBody() - .jsonPath("$.length()").isEqualTo(2).jsonPath("configuredLevel").isEqualTo(null) - .jsonPath("effectiveLevel").isEqualTo("DEBUG"); + .willReturn(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG)); + this.client.get() + .uri("/actuator/loggers/ROOT") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$.length()") + .isEqualTo(2) + .jsonPath("configuredLevel") + .isEqualTo(null) + .jsonPath("effectiveLevel") + .isEqualTo("DEBUG"); } @WebEndpointTest @@ -112,88 +136,140 @@ class LoggersEndpointWebIntegrationTests { @WebEndpointTest void getLoggerGroupShouldReturnConfiguredLogLevelAndMembers() { setLogLevelToDebug("test"); - this.client.get().uri("actuator/loggers/test").exchange().expectStatus().isOk().expectBody() - .jsonPath("$.length()").isEqualTo(2).jsonPath("members") - .value(IsIterableContainingInAnyOrder.containsInAnyOrder("test.member1", "test.member2")) - .jsonPath("configuredLevel").isEqualTo("DEBUG"); + this.client.get() + .uri("actuator/loggers/test") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$.length()") + .isEqualTo(2) + .jsonPath("members") + .value(IsIterableContainingInAnyOrder.containsInAnyOrder("test.member1", "test.member2")) + .jsonPath("configuredLevel") + .isEqualTo("DEBUG"); } @WebEndpointTest void setLoggerUsingApplicationJsonShouldSetLogLevel() { - this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.APPLICATION_JSON) - .bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus() - .isNoContent(); + this.client.post() + .uri("/actuator/loggers/ROOT") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(Collections.singletonMap("configuredLevel", "debug")) + .exchange() + .expectStatus() + .isNoContent(); then(this.loggingSystem).should().setLogLevel("ROOT", LogLevel.DEBUG); } @WebEndpointTest void setLoggerUsingActuatorV2JsonShouldSetLogLevel() { - this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(V2_JSON)) - .bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus() - .isNoContent(); + this.client.post() + .uri("/actuator/loggers/ROOT") + .contentType(MediaType.parseMediaType(V2_JSON)) + .bodyValue(Collections.singletonMap("configuredLevel", "debug")) + .exchange() + .expectStatus() + .isNoContent(); then(this.loggingSystem).should().setLogLevel("ROOT", LogLevel.DEBUG); } @WebEndpointTest void setLoggerUsingActuatorV3JsonShouldSetLogLevel() { - this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(V3_JSON)) - .bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus() - .isNoContent(); + this.client.post() + .uri("/actuator/loggers/ROOT") + .contentType(MediaType.parseMediaType(V3_JSON)) + .bodyValue(Collections.singletonMap("configuredLevel", "debug")) + .exchange() + .expectStatus() + .isNoContent(); then(this.loggingSystem).should().setLogLevel("ROOT", LogLevel.DEBUG); } @WebEndpointTest void setLoggerGroupUsingActuatorV2JsonShouldSetLogLevel() { - this.client.post().uri("/actuator/loggers/test").contentType(MediaType.parseMediaType(V2_JSON)) - .bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus() - .isNoContent(); + this.client.post() + .uri("/actuator/loggers/test") + .contentType(MediaType.parseMediaType(V2_JSON)) + .bodyValue(Collections.singletonMap("configuredLevel", "debug")) + .exchange() + .expectStatus() + .isNoContent(); then(this.loggingSystem).should().setLogLevel("test.member1", LogLevel.DEBUG); then(this.loggingSystem).should().setLogLevel("test.member2", LogLevel.DEBUG); } @WebEndpointTest void setLoggerGroupUsingApplicationJsonShouldSetLogLevel() { - this.client.post().uri("/actuator/loggers/test").contentType(MediaType.APPLICATION_JSON) - .bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus() - .isNoContent(); + this.client.post() + .uri("/actuator/loggers/test") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(Collections.singletonMap("configuredLevel", "debug")) + .exchange() + .expectStatus() + .isNoContent(); then(this.loggingSystem).should().setLogLevel("test.member1", LogLevel.DEBUG); then(this.loggingSystem).should().setLogLevel("test.member2", LogLevel.DEBUG); } @WebEndpointTest void setLoggerOrLoggerGroupWithWrongLogLevelResultInBadRequestResponse() { - this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.APPLICATION_JSON) - .bodyValue(Collections.singletonMap("configuredLevel", "other")).exchange().expectStatus() - .isBadRequest(); + this.client.post() + .uri("/actuator/loggers/ROOT") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(Collections.singletonMap("configuredLevel", "other")) + .exchange() + .expectStatus() + .isBadRequest(); then(this.loggingSystem).shouldHaveNoInteractions(); } @WebEndpointTest void setLoggerWithNullLogLevel() { - this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(V3_JSON)) - .bodyValue(Collections.singletonMap("configuredLevel", null)).exchange().expectStatus().isNoContent(); + this.client.post() + .uri("/actuator/loggers/ROOT") + .contentType(MediaType.parseMediaType(V3_JSON)) + .bodyValue(Collections.singletonMap("configuredLevel", null)) + .exchange() + .expectStatus() + .isNoContent(); then(this.loggingSystem).should().setLogLevel("ROOT", null); } @WebEndpointTest void setLoggerWithNoLogLevel() { - this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(V3_JSON)) - .bodyValue(Collections.emptyMap()).exchange().expectStatus().isNoContent(); + this.client.post() + .uri("/actuator/loggers/ROOT") + .contentType(MediaType.parseMediaType(V3_JSON)) + .bodyValue(Collections.emptyMap()) + .exchange() + .expectStatus() + .isNoContent(); then(this.loggingSystem).should().setLogLevel("ROOT", null); } @WebEndpointTest void setLoggerGroupWithNullLogLevel() { - this.client.post().uri("/actuator/loggers/test").contentType(MediaType.parseMediaType(V3_JSON)) - .bodyValue(Collections.singletonMap("configuredLevel", null)).exchange().expectStatus().isNoContent(); + this.client.post() + .uri("/actuator/loggers/test") + .contentType(MediaType.parseMediaType(V3_JSON)) + .bodyValue(Collections.singletonMap("configuredLevel", null)) + .exchange() + .expectStatus() + .isNoContent(); then(this.loggingSystem).should().setLogLevel("test.member1", null); then(this.loggingSystem).should().setLogLevel("test.member2", null); } @WebEndpointTest void setLoggerGroupWithNoLogLevel() { - this.client.post().uri("/actuator/loggers/test").contentType(MediaType.parseMediaType(V3_JSON)) - .bodyValue(Collections.emptyMap()).exchange().expectStatus().isNoContent(); + this.client.post() + .uri("/actuator/loggers/test") + .contentType(MediaType.parseMediaType(V3_JSON)) + .bodyValue(Collections.emptyMap()) + .exchange() + .expectStatus() + .isNoContent(); then(this.loggingSystem).should().setLogLevel("test.member1", null); then(this.loggingSystem).should().setLogLevel("test.member2", null); } @@ -201,18 +277,36 @@ class LoggersEndpointWebIntegrationTests { @WebEndpointTest void logLevelForLoggerWithNameThatCouldBeMistakenForAPathExtension() { given(this.loggingSystem.getLoggerConfiguration("com.png")) - .willReturn(new LoggerConfiguration("com.png", null, LogLevel.DEBUG)); - this.client.get().uri("/actuator/loggers/com.png").exchange().expectStatus().isOk().expectBody() - .jsonPath("$.length()").isEqualTo(2).jsonPath("configuredLevel").isEqualTo(null) - .jsonPath("effectiveLevel").isEqualTo("DEBUG"); + .willReturn(new LoggerConfiguration("com.png", null, LogLevel.DEBUG)); + this.client.get() + .uri("/actuator/loggers/com.png") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$.length()") + .isEqualTo(2) + .jsonPath("configuredLevel") + .isEqualTo(null) + .jsonPath("effectiveLevel") + .isEqualTo("DEBUG"); } @WebEndpointTest void logLevelForLoggerGroupWithNameThatCouldBeMistakenForAPathExtension() { setLogLevelToDebug("group.png"); - this.client.get().uri("/actuator/loggers/group.png").exchange().expectStatus().isOk().expectBody() - .jsonPath("$.length()").isEqualTo(2).jsonPath("configuredLevel").isEqualTo("DEBUG").jsonPath("members") - .value(IsIterableContainingInAnyOrder.containsInAnyOrder("png.member1", "png.member2")); + this.client.get() + .uri("/actuator/loggers/group.png") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$.length()") + .isEqualTo(2) + .jsonPath("configuredLevel") + .isEqualTo("DEBUG") + .jsonPath("members") + .value(IsIterableContainingInAnyOrder.containsInAnyOrder("png.member1", "png.member2")); } private void setLogLevelToDebug(String name) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointWebIntegrationTests.java index c6e58f8650..fc5233a41b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,8 +60,15 @@ class HeapDumpWebEndpointWebIntegrationTests { @WebEndpointTest void getRequestShouldReturnHeapDumpInResponseBody(WebTestClient client) { - client.get().uri("/actuator/heapdump").exchange().expectStatus().isOk().expectHeader() - .contentType(MediaType.APPLICATION_OCTET_STREAM).expectBody(String.class).isEqualTo("HEAPDUMP"); + client.get() + .uri("/actuator/heapdump") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .expectBody(String.class) + .isEqualTo("HEAPDUMP"); assertHeapDumpFileIsDeleted(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointTests.java index 2edb626420..5d9b960893 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -99,20 +99,20 @@ class ThreadDumpEndpointTests { monitor.notifyAll(); } assertThat(threadDump) - .containsPattern(String.format("\t- parking to wait for <[0-9a-z]+> \\(a %s\\$Sync\\)", - CountDownLatch.class.getName().replace(".", "\\."))) - .contains(String.format("\t- locked <%s> (a java.lang.Object)", hexIdentityHashCode(contendedMonitor))) - .contains(String.format("\t- waiting to lock <%s> (a java.lang.Object) owned by \"%s\" t@%d", - hexIdentityHashCode(contendedMonitor), Thread.currentThread().getName(), - Thread.currentThread().getId())) - .satisfiesAnyOf( - (dump) -> dump.contains(String.format("\t- waiting on <%s> (a java.lang.Object)", - hexIdentityHashCode(monitor))), - (dump) -> dump.contains(String.format("\t- parking to wait for <%s> (a java.lang.Object)", - hexIdentityHashCode(monitor)))) - .containsPattern( - String.format("Locked ownable synchronizers:%n\t- Locked <[0-9a-z]+> \\(a %s\\$NonfairSync\\)", - ReentrantReadWriteLock.class.getName().replace(".", "\\."))); + .containsPattern(String.format("\t- parking to wait for <[0-9a-z]+> \\(a %s\\$Sync\\)", + CountDownLatch.class.getName().replace(".", "\\."))) + .contains(String.format("\t- locked <%s> (a java.lang.Object)", hexIdentityHashCode(contendedMonitor))) + .contains(String.format("\t- waiting to lock <%s> (a java.lang.Object) owned by \"%s\" t@%d", + hexIdentityHashCode(contendedMonitor), Thread.currentThread().getName(), + Thread.currentThread().getId())) + .satisfiesAnyOf( + (dump) -> dump.contains( + String.format("\t- waiting on <%s> (a java.lang.Object)", hexIdentityHashCode(monitor))), + (dump) -> dump.contains(String.format("\t- parking to wait for <%s> (a java.lang.Object)", + hexIdentityHashCode(monitor)))) + .containsPattern( + String.format("Locked ownable synchronizers:%n\t- Locked <[0-9a-z]+> \\(a %s\\$NonfairSync\\)", + ReentrantReadWriteLock.class.getName().replace(".", "\\."))); } private String hexIdentityHashCode(Object object) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointWebIntegrationTests.java index 3d4f361940..bbbd44c772 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,15 +34,29 @@ class ThreadDumpEndpointWebIntegrationTests { @WebEndpointTest void getRequestWithJsonAcceptHeaderShouldProduceJsonThreadDumpResponse(WebTestClient client) { - client.get().uri("/actuator/threaddump").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() - .expectHeader().contentType(MediaType.APPLICATION_JSON); + client.get() + .uri("/actuator/threaddump") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.APPLICATION_JSON); } @WebEndpointTest void getRequestWithTextPlainAcceptHeaderShouldProduceTextPlainResponse(WebTestClient client) { - String response = client.get().uri("/actuator/threaddump").accept(MediaType.TEXT_PLAIN).exchange() - .expectStatus().isOk().expectHeader().contentType("text/plain;charset=UTF-8").expectBody(String.class) - .returnResult().getResponseBody(); + String response = client.get() + .uri("/actuator/threaddump") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType("text/plain;charset=UTF-8") + .expectBody(String.class) + .returnResult() + .getResponseBody(); assertThat(response).contains("Full thread dump"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java index 9413ce6804..a5d41e6183 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -132,8 +132,10 @@ class MetricsEndpointTests { this.registry.counter("cache", "host", "1", "region", "east", "result", "hit"); this.registry.counter("cache", "host", "1", "region", "east", "result", "miss"); MetricsEndpoint.MetricResponse response = this.endpoint.metric("cache", Collections.singletonList("host:1")); - assertThat(response.getAvailableTags().stream().filter((t) -> t.getTag().equals("region")) - .flatMap((t) -> t.getValues().stream())).containsExactly("east"); + assertThat(response.getAvailableTags() + .stream() + .filter((t) -> t.getTag().equals("region")) + .flatMap((t) -> t.getValues().stream())).containsExactly("east"); } @Test @@ -149,7 +151,7 @@ class MetricsEndpointTests { @Test void metricWithInvalidTag() { assertThatExceptionOfType(InvalidEndpointRequestException.class) - .isThrownBy(() -> this.endpoint.metric("counter", Collections.singletonList("key"))); + .isThrownBy(() -> this.endpoint.metric("counter", Collections.singletonList("key"))); } @Test @@ -191,14 +193,19 @@ class MetricsEndpointTests { private void assertMetricHasStatisticEqualTo(MeterRegistry registry, String metricName, Statistic stat, Double value) { MetricsEndpoint endpoint = new MetricsEndpoint(registry); - assertThat(endpoint.metric(metricName, Collections.emptyList()).getMeasurements().stream() - .filter((sample) -> sample.getStatistic().equals(stat)).findAny()) - .hasValueSatisfying((sample) -> assertThat(sample.getValue()).isEqualTo(value)); + assertThat(endpoint.metric(metricName, Collections.emptyList()) + .getMeasurements() + .stream() + .filter((sample) -> sample.getStatistic().equals(stat)) + .findAny()).hasValueSatisfying((sample) -> assertThat(sample.getValue()).isEqualTo(value)); } private Optional getCount(MetricsEndpoint.MetricResponse response) { - return response.getMeasurements().stream().filter((sample) -> sample.getStatistic().equals(Statistic.COUNT)) - .findAny().map(MetricsEndpoint.Sample::getValue); + return response.getMeasurements() + .stream() + .filter((sample) -> sample.getStatistic().equals(Statistic.COUNT)) + .findAny() + .map(MetricsEndpoint.Sample::getValue); } private Stream availableTagKeys(MetricsEndpoint.MetricResponse response) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointWebIntegrationTests.java index b29425aeab..43cf42b63a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,22 +49,40 @@ class MetricsEndpointWebIntegrationTests { @WebEndpointTest @SuppressWarnings("unchecked") void listNames(WebTestClient client) throws IOException { - String responseBody = client.get().uri("/actuator/metrics").exchange().expectStatus().isOk() - .expectBody(String.class).returnResult().getResponseBody(); + String responseBody = client.get() + .uri("/actuator/metrics") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .returnResult() + .getResponseBody(); Map> names = this.mapper.readValue(responseBody, Map.class); assertThat(names.get("names")).containsOnlyOnce("jvm.memory.used"); } @WebEndpointTest void selectByName(WebTestClient client) { - client.get().uri("/actuator/metrics/jvm.memory.used").exchange().expectStatus().isOk().expectBody() - .jsonPath("$.name").isEqualTo("jvm.memory.used"); + client.get() + .uri("/actuator/metrics/jvm.memory.used") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$.name") + .isEqualTo("jvm.memory.used"); } @WebEndpointTest void selectByTag(WebTestClient client) { - client.get().uri("/actuator/metrics/jvm.memory.used?tag=id:Compressed%20Class%20Space").exchange() - .expectStatus().isOk().expectBody().jsonPath("$.name").isEqualTo("jvm.memory.used"); + client.get() + .uri("/actuator/metrics/jvm.memory.used?tag=id:Compressed%20Class%20Space") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$.name") + .isEqualTo("jvm.memory.used"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/Cache2kCacheMeterBinderProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/Cache2kCacheMeterBinderProviderTests.java index 38bccbb10d..6c551abbfd 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/Cache2kCacheMeterBinderProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/Cache2kCacheMeterBinderProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ class Cache2kCacheMeterBinderProviderTests { @Test void cache2kCacheProvider() { SpringCache2kCacheManager cacheManager = new SpringCache2kCacheManager() - .addCaches((builder) -> builder.name("test")); + .addCaches((builder) -> builder.name("test")); MeterBinder meterBinder = new Cache2kCacheMeterBinderProvider().getMeterBinder(cacheManager.getCache("test"), Collections.emptyList()); assertThat(meterBinder).isInstanceOf(Cache2kCacheMetrics.class); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrarTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrarTests.java index 150601e176..8b6dbc783a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrarTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,8 @@ class CacheMetricsRegistrarTests { CacheMetricsRegistrar registrar = new CacheMetricsRegistrar(this.meterRegistry, Collections.singleton(new CaffeineCacheMeterBinderProvider())); assertThat(registrar.bindCacheToRegistry( - new TransactionAwareCacheDecorator(new CaffeineCache("test", Caffeine.newBuilder().build())))).isTrue(); + new TransactionAwareCacheDecorator(new CaffeineCache("test", Caffeine.newBuilder().build())))) + .isTrue(); assertThat(this.meterRegistry.get("cache.gets").tags("name", "test").meter()).isNotNull(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/RedisCacheMetricsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/RedisCacheMetricsTests.java index 38d6af150c..907cec99b4 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/RedisCacheMetricsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/RedisCacheMetricsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,10 +54,10 @@ class RedisCacheMetricsTests { private static final Tags TAGS = Tags.of("app", "test").and("cache", "test"); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, CacheAutoConfiguration.class)) - .withUserConfiguration(CachingConfiguration.class).withPropertyValues( - "spring.redis.host=" + redis.getHost(), "spring.redis.port=" + redis.getFirstMappedPort(), - "spring.cache.type=redis", "spring.cache.redis.enable-statistics=true"); + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, CacheAutoConfiguration.class)) + .withUserConfiguration(CachingConfiguration.class) + .withPropertyValues("spring.redis.host=" + redis.getHost(), "spring.redis.port=" + redis.getFirstMappedPort(), + "spring.cache.type=redis", "spring.cache.redis.enable-statistics=true"); @Test void cacheStatisticsAreExposed() { @@ -66,7 +66,7 @@ class RedisCacheMetricsTests { assertThat(meterRegistry.find("cache.gets").tags(TAGS.and("result", "hit")).functionCounter()).isNotNull(); assertThat(meterRegistry.find("cache.gets").tags(TAGS.and("result", "miss")).functionCounter()).isNotNull(); assertThat(meterRegistry.find("cache.gets").tags(TAGS.and("result", "pending")).functionCounter()) - .isNotNull(); + .isNotNull(); assertThat(meterRegistry.find("cache.evictions").tags(TAGS).functionCounter()).isNull(); assertThat(meterRegistry.find("cache.puts").tags(TAGS).functionCounter()).isNotNull(); assertThat(meterRegistry.find("cache.removals").tags(TAGS).functionCounter()).isNotNull(); @@ -83,7 +83,7 @@ class RedisCacheMetricsTests { cache.get(key); cache.get(key); assertThat(meterRegistry.get("cache.gets").tags(TAGS.and("result", "hit")).functionCounter().count()) - .isEqualTo(2.0d); + .isEqualTo(2.0d); })); } @@ -95,7 +95,7 @@ class RedisCacheMetricsTests { cache.get(key); cache.get(key); assertThat(meterRegistry.get("cache.gets").tags(TAGS.and("result", "miss")).functionCounter().count()) - .isEqualTo(3.0d); + .isEqualTo(3.0d); })); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManagerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManagerTests.java index 7bb3ceef2f..3329b79e29 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManagerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,36 +73,42 @@ class PrometheusPushGatewayManagerTests { @Test void createWhenPushGatewayIsNullThrowsException() { - assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(null, this.registry, - this.scheduler, this.pushRate, "job", this.groupingKey, null)) - .withMessage("PushGateway must not be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new PrometheusPushGatewayManager(null, this.registry, this.scheduler, this.pushRate, + "job", this.groupingKey, null)) + .withMessage("PushGateway must not be null"); } @Test void createWhenCollectorRegistryIsNullThrowsException() { - assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, null, - this.scheduler, this.pushRate, "job", this.groupingKey, null)).withMessage("Registry must not be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, null, this.scheduler, this.pushRate, + "job", this.groupingKey, null)) + .withMessage("Registry must not be null"); } @Test void createWhenSchedulerIsNullThrowsException() { - assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, - this.registry, null, this.pushRate, "job", this.groupingKey, null)) - .withMessage("Scheduler must not be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, this.registry, null, this.pushRate, + "job", this.groupingKey, null)) + .withMessage("Scheduler must not be null"); } @Test void createWhenPushRateIsNullThrowsException() { - assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, - this.registry, this.scheduler, null, "job", this.groupingKey, null)) - .withMessage("PushRate must not be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, null, + "job", this.groupingKey, null)) + .withMessage("PushRate must not be null"); } @Test void createWhenJobIsEmptyThrowsException() { - assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, - this.registry, this.scheduler, this.pushRate, "", this.groupingKey, null)) - .withMessage("Job must not be empty"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, + this.pushRate, "", this.groupingKey, null)) + .withMessage("Job must not be empty"); } @Test @@ -180,7 +186,7 @@ class PrometheusPushGatewayManagerTests { @SuppressWarnings({ "unchecked", "rawtypes" }) private T givenScheduleAtFixedRateWillReturnFuture(T scheduler) { given(scheduler.scheduleAtFixedRate(isA(Runnable.class), isA(Duration.class))) - .willReturn((ScheduledFuture) this.future); + .willReturn((ScheduledFuture) this.future); return scheduler; } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusScrapeEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusScrapeEndpointIntegrationTests.java index 1265d82106..d74a63e875 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusScrapeEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusScrapeEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,10 +43,17 @@ class PrometheusScrapeEndpointIntegrationTests { void scrapeHasContentTypeText004ByDefault(WebTestClient client) { String expectedContentType = TextFormat.CONTENT_TYPE_004; assertThat(TextFormat.chooseContentType(null)).isEqualTo(expectedContentType); - client.get().uri("/actuator/prometheus").exchange().expectStatus().isOk().expectHeader() - .contentType(MediaType.parseMediaType(expectedContentType)).expectBody(String.class) - .value((body) -> assertThat(body).contains("counter1_total").contains("counter2_total") - .contains("counter3_total")); + client.get() + .uri("/actuator/prometheus") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.parseMediaType(expectedContentType)) + .expectBody(String.class) + .value((body) -> assertThat(body).contains("counter1_total") + .contains("counter2_total") + .contains("counter3_total")); } @WebEndpointTest @@ -54,34 +61,64 @@ class PrometheusScrapeEndpointIntegrationTests { String expectedContentType = TextFormat.CONTENT_TYPE_004; String accept = "*/*;q=0.8"; assertThat(TextFormat.chooseContentType(accept)).isEqualTo(expectedContentType); - client.get().uri("/actuator/prometheus").accept(MediaType.parseMediaType(accept)).exchange().expectStatus() - .isOk().expectHeader().contentType(MediaType.parseMediaType(expectedContentType)) - .expectBody(String.class).value((body) -> assertThat(body).contains("counter1_total") - .contains("counter2_total").contains("counter3_total")); + client.get() + .uri("/actuator/prometheus") + .accept(MediaType.parseMediaType(accept)) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.parseMediaType(expectedContentType)) + .expectBody(String.class) + .value((body) -> assertThat(body).contains("counter1_total") + .contains("counter2_total") + .contains("counter3_total")); } @WebEndpointTest void scrapeCanProduceOpenMetrics100(WebTestClient client) { MediaType openMetrics = MediaType.parseMediaType(TextFormat.CONTENT_TYPE_OPENMETRICS_100); - client.get().uri("/actuator/prometheus").accept(openMetrics).exchange().expectStatus().isOk().expectHeader() - .contentType(openMetrics).expectBody(String.class).value((body) -> assertThat(body) - .contains("counter1_total").contains("counter2_total").contains("counter3_total")); + client.get() + .uri("/actuator/prometheus") + .accept(openMetrics) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(openMetrics) + .expectBody(String.class) + .value((body) -> assertThat(body).contains("counter1_total") + .contains("counter2_total") + .contains("counter3_total")); } @WebEndpointTest void scrapePrefersToProduceOpenMetrics100(WebTestClient client) { MediaType openMetrics = MediaType.parseMediaType(TextFormat.CONTENT_TYPE_OPENMETRICS_100); MediaType textPlain = MediaType.parseMediaType(TextFormat.CONTENT_TYPE_004); - client.get().uri("/actuator/prometheus").accept(openMetrics, textPlain).exchange().expectStatus().isOk() - .expectHeader().contentType(openMetrics); + client.get() + .uri("/actuator/prometheus") + .accept(openMetrics, textPlain) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(openMetrics); } @WebEndpointTest void scrapeWithIncludedNames(WebTestClient client) { - client.get().uri("/actuator/prometheus?includedNames=counter1_total,counter2_total").exchange().expectStatus() - .isOk().expectHeader().contentType(MediaType.parseMediaType(TextFormat.CONTENT_TYPE_004)) - .expectBody(String.class).value((body) -> assertThat(body).contains("counter1_total") - .contains("counter2_total").doesNotContain("counter3_total")); + client.get() + .uri("/actuator/prometheus?includedNames=counter1_total,counter2_total") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.parseMediaType(TextFormat.CONTENT_TYPE_004)) + .expectBody(String.class) + .value((body) -> assertThat(body).contains("counter1_total") + .contains("counter2_total") + .doesNotContain("counter3_total")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/graphql/GraphQlTagsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/graphql/GraphQlTagsTests.java index c9d04d2732..d58195dc4f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/graphql/GraphQlTagsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/graphql/GraphQlTagsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,24 +58,30 @@ class GraphQlTagsTests { @Test void errorTypeShouldBeDefinedIfPresent() { - GraphQLError error = GraphqlErrorBuilder.newError().errorType(ErrorType.DataFetchingException) - .message("test error").build(); + GraphQLError error = GraphqlErrorBuilder.newError() + .errorType(ErrorType.DataFetchingException) + .message("test error") + .build(); Tag errorTypeTag = GraphQlTags.errorType(error); assertThat(errorTypeTag).isEqualTo(Tag.of("error.type", "DataFetchingException")); } @Test void errorPathShouldUseJsonPathFormat() { - GraphQLError error = GraphqlErrorBuilder.newError().path(Arrays.asList("project", "name")).message("test error") - .build(); + GraphQLError error = GraphqlErrorBuilder.newError() + .path(Arrays.asList("project", "name")) + .message("test error") + .build(); Tag errorPathTag = GraphQlTags.errorPath(error); assertThat(errorPathTag).isEqualTo(Tag.of("error.path", "$.project.name")); } @Test void errorPathShouldUseJsonPathFormatForIndices() { - GraphQLError error = GraphqlErrorBuilder.newError().path(Arrays.asList("issues", "42", "title")) - .message("test error").build(); + GraphQLError error = GraphqlErrorBuilder.newError() + .path(Arrays.asList("issues", "42", "title")) + .message("test error") + .build(); Tag errorPathTag = GraphQlTags.errorPath(error); assertThat(errorPathTag).isEqualTo(Tag.of("error.path", "$.issues[*].title")); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetricsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetricsTests.java index 34764a4053..77fd731283 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetricsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetricsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,12 +43,12 @@ class DataSourcePoolMetricsTests { @Test void dataSourceIsInstrumented() { new ApplicationContextRunner().withUserConfiguration(DataSourceConfig.class, MetricsApp.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true", "metrics.use-global-registry=false") - .run((context) -> { - context.getBean(DataSource.class).getConnection().getMetaData(); - context.getBean(MeterRegistry.class).get("jdbc.connections.max").meter(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true", "metrics.use-global-registry=false") + .run((context) -> { + context.getBean(DataSource.class).getConnection().getMetaData(); + context.getBean(MeterRegistry.class).get("jdbc.connections.max").meter(); + }); } @Configuration(proxyBeanMethods = false) @@ -67,7 +67,7 @@ class DataSourcePoolMetricsTests { DataSourceConfig(DataSource dataSource, Collection metadataProviders, MeterRegistry registry) { new DataSourcePoolMetrics(dataSource, metadataProviders, "data.source", Collections.emptyList()) - .bindTo(registry); + .bindTo(registry); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/startup/StartupTimeMetricsListenerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/startup/StartupTimeMetricsListenerTests.java index 19a435860d..f124e1797f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/startup/StartupTimeMetricsListenerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/startup/StartupTimeMetricsListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -118,9 +118,10 @@ class StartupTimeMetricsListenerTests { private void assertMetricExistsWithCustomTagsAndValue(String metricName, Tags expectedCustomTags, Long expectedValueInMillis) { assertThat(this.registry.find(metricName) - .tags(Tags.concat(expectedCustomTags, "main.application.class", TestMainApplication.class.getName())) - .timeGauge()).isNotNull().extracting((m) -> m.value(TimeUnit.MILLISECONDS)) - .isEqualTo(expectedValueInMillis.doubleValue()); + .tags(Tags.concat(expectedCustomTags, "main.application.class", TestMainApplication.class.getName())) + .timeGauge()).isNotNull() + .extracting((m) -> m.value(TimeUnit.MILLISECONDS)) + .isEqualTo(expectedValueInMillis.doubleValue()); } static class TestMainApplication { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/MetricsRestTemplateCustomizerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/MetricsRestTemplateCustomizerTests.java index c833b0c99a..7e7b29ee09 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/MetricsRestTemplateCustomizerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/MetricsRestTemplateCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -78,13 +78,15 @@ class MetricsRestTemplateCustomizerTests { @Test void interceptRestTemplate() { this.mockServer.expect(MockRestRequestMatchers.requestTo("/test/123")) - .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) - .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); + .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) + .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); String result = this.restTemplate.getForObject("/test/{id}", String.class, 123); assertThat(this.registry.find("http.client.requests").meters()) - .anySatisfy((m) -> assertThat(m.getId().getTags().stream().map(Tag::getKey)).doesNotContain("bucket")); - assertThat(this.registry.get("http.client.requests").tags("method", "GET", "uri", "/test/{id}", "status", "200") - .timer().count()).isEqualTo(1); + .anySatisfy((m) -> assertThat(m.getId().getTags().stream().map(Tag::getKey)).doesNotContain("bucket")); + assertThat(this.registry.get("http.client.requests") + .tags("method", "GET", "uri", "/test/{id}", "status", "200") + .timer() + .count()).isEqualTo(1); assertThat(result).isEqualTo("OK"); this.mockServer.verify(); } @@ -100,8 +102,8 @@ class MetricsRestTemplateCustomizerTests { @Test void normalizeUriToContainLeadingSlash() { this.mockServer.expect(MockRestRequestMatchers.requestTo("/test/123")) - .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) - .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); + .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) + .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); String result = this.restTemplate.getForObject("test/{id}", String.class, 123); this.registry.get("http.client.requests").tags("uri", "/test/{id}").timer(); assertThat(result).isEqualTo("OK"); @@ -111,8 +113,8 @@ class MetricsRestTemplateCustomizerTests { @Test void interceptRestTemplateWithUri() throws URISyntaxException { this.mockServer.expect(MockRestRequestMatchers.requestTo("http://localhost/test/123")) - .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) - .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); + .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) + .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); String result = this.restTemplate.getForObject(new URI("http://localhost/test/123"), String.class); assertThat(result).isEqualTo("OK"); this.registry.get("http.client.requests").tags("uri", "/test/123").timer(); @@ -122,14 +124,14 @@ class MetricsRestTemplateCustomizerTests { @Test void interceptNestedRequest() { this.mockServer.expect(MockRestRequestMatchers.requestTo("/test/123")) - .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) - .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); + .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) + .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); RestTemplate nestedRestTemplate = new RestTemplate(); MockRestServiceServer nestedMockServer = MockRestServiceServer.createServer(nestedRestTemplate); nestedMockServer.expect(MockRestRequestMatchers.requestTo("/nestedTest/124")) - .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) - .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); + .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) + .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); this.customizer.customize(nestedRestTemplate); TestInterceptor testInterceptor = new TestInterceptor(nestedRestTemplate); @@ -149,10 +151,11 @@ class MetricsRestTemplateCustomizerTests { environment.setProperty("local.server.port", "8443"); LocalHostUriTemplateHandler uriTemplateHandler = new LocalHostUriTemplateHandler(environment, "https"); RestTemplate restTemplate = new RestTemplateBuilder(this.customizer).uriTemplateHandler(uriTemplateHandler) - .build(); + .build(); assertThat(restTemplate.getUriTemplateHandler()) - .asInstanceOf(InstanceOfAssertFactories.type(RootUriTemplateHandler.class)) - .extracting(RootUriTemplateHandler::getRootUri).isEqualTo("https://localhost:8443"); + .asInstanceOf(InstanceOfAssertFactories.type(RootUriTemplateHandler.class)) + .extracting(RootUriTemplateHandler::getRootUri) + .isEqualTo("https://localhost:8443"); } @Test @@ -171,14 +174,15 @@ class MetricsRestTemplateCustomizerTests { }; RestTemplate restTemplate = new RestTemplateBuilder(new MetricsRestTemplateCustomizer(this.registry, - new DefaultRestTemplateExchangeTagsProvider(), "http.client.requests", autoTimer)).build(); + new DefaultRestTemplateExchangeTagsProvider(), "http.client.requests", autoTimer)) + .build(); MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate); mockServer.expect(MockRestRequestMatchers.requestTo("/first/123")) - .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) - .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); + .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) + .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); mockServer.expect(MockRestRequestMatchers.requestTo("/second/456")) - .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) - .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); + .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) + .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); assertThat(restTemplate.getForObject("/first/{id}", String.class, 123)).isEqualTo("OK"); assertThat(this.registry.find("http.client.requests").timer()).isNull(); enabled.set(true); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProviderTests.java index f30dd37f26..be2ab04c92 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,8 @@ class DefaultWebClientExchangeTagsProviderTests { @BeforeEach void setup() { this.request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")) - .attribute(URI_TEMPLATE_ATTRIBUTE, "https://example.org/projects/{project}").build(); + .attribute(URI_TEMPLATE_ATTRIBUTE, "https://example.org/projects/{project}") + .build(); this.response = mock(ClientResponse.class); given(this.response.rawStatusCode()).willReturn(HttpStatus.OK.value()); } @@ -67,7 +68,8 @@ class DefaultWebClientExchangeTagsProviderTests { @Test void tagsWhenNoUriTemplateShouldProvideUriPath() { ClientRequest request = ClientRequest - .create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")).build(); + .create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")) + .build(); Iterable tags = this.tagsProvider.tags(request, this.response, null); assertThat(tags).containsExactlyInAnyOrder(Tag.of("method", "GET"), Tag.of("uri", "/projects/spring-boot"), Tag.of("client.name", "example.org"), Tag.of("status", "200"), Tag.of("outcome", "SUCCESS")); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunctionTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunctionTests.java index ffc17f49fe..88e6447eed 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunctionTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunctionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,87 +79,109 @@ class MetricsWebClientFilterFunctionTests { @Test void filterShouldRecordTimer() { ClientRequest request = ClientRequest - .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")).build(); + .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")) + .build(); given(this.response.rawStatusCode()).willReturn(HttpStatus.OK.value()); this.filterFunction.filter(request, this.exchange).block(Duration.ofSeconds(5)); assertThat(this.registry.get("http.client.requests") - .tags("method", "GET", "uri", "/projects/spring-boot", "status", "200").timer().count()).isEqualTo(1); + .tags("method", "GET", "uri", "/projects/spring-boot", "status", "200") + .timer() + .count()).isEqualTo(1); } @Test void filterWhenUriTemplatePresentShouldRecordTimer() { ClientRequest request = ClientRequest - .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")) - .attribute(URI_TEMPLATE_ATTRIBUTE, "/projects/{project}").build(); + .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")) + .attribute(URI_TEMPLATE_ATTRIBUTE, "/projects/{project}") + .build(); given(this.response.rawStatusCode()).willReturn(HttpStatus.OK.value()); this.filterFunction.filter(request, this.exchange).block(Duration.ofSeconds(5)); assertThat(this.registry.get("http.client.requests") - .tags("method", "GET", "uri", "/projects/{project}", "status", "200").timer().count()).isEqualTo(1); + .tags("method", "GET", "uri", "/projects/{project}", "status", "200") + .timer() + .count()).isEqualTo(1); } @Test void filterWhenIoExceptionThrownShouldRecordTimer() { ClientRequest request = ClientRequest - .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")).build(); + .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")) + .build(); ExchangeFunction errorExchange = (r) -> Mono.error(new IOException()); - this.filterFunction.filter(request, errorExchange).onErrorResume(IOException.class, (t) -> Mono.empty()) - .block(Duration.ofSeconds(5)); + this.filterFunction.filter(request, errorExchange) + .onErrorResume(IOException.class, (t) -> Mono.empty()) + .block(Duration.ofSeconds(5)); assertThat(this.registry.get("http.client.requests") - .tags("method", "GET", "uri", "/projects/spring-boot", "status", "IO_ERROR").timer().count()) - .isEqualTo(1); + .tags("method", "GET", "uri", "/projects/spring-boot", "status", "IO_ERROR") + .timer() + .count()).isEqualTo(1); } @Test void filterWhenExceptionThrownShouldRecordTimer() { ClientRequest request = ClientRequest - .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")).build(); + .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")) + .build(); ExchangeFunction exchange = (r) -> Mono.error(new IllegalArgumentException()); - this.filterFunction.filter(request, exchange).onErrorResume(IllegalArgumentException.class, (t) -> Mono.empty()) - .block(Duration.ofSeconds(5)); + this.filterFunction.filter(request, exchange) + .onErrorResume(IllegalArgumentException.class, (t) -> Mono.empty()) + .block(Duration.ofSeconds(5)); assertThat(this.registry.get("http.client.requests") - .tags("method", "GET", "uri", "/projects/spring-boot", "status", "CLIENT_ERROR").timer().count()) - .isEqualTo(1); + .tags("method", "GET", "uri", "/projects/spring-boot", "status", "CLIENT_ERROR") + .timer() + .count()).isEqualTo(1); } @Test void filterWhenCancelThrownShouldRecordTimer() { ClientRequest request = ClientRequest - .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")).build(); + .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")) + .build(); given(this.response.rawStatusCode()).willReturn(HttpStatus.OK.value()); Mono filter = this.filterFunction.filter(request, this.exchange); StepVerifier.create(filter).thenCancel().verify(Duration.ofSeconds(5)); assertThat(this.registry.get("http.client.requests") - .tags("method", "GET", "uri", "/projects/spring-boot", "status", "CLIENT_ERROR").timer().count()) - .isEqualTo(1); + .tags("method", "GET", "uri", "/projects/spring-boot", "status", "CLIENT_ERROR") + .timer() + .count()).isEqualTo(1); assertThatThrownBy(() -> this.registry.get("http.client.requests") - .tags("method", "GET", "uri", "/projects/spring-boot", "status", "200").timer()) - .isInstanceOf(MeterNotFoundException.class); + .tags("method", "GET", "uri", "/projects/spring-boot", "status", "200") + .timer()).isInstanceOf(MeterNotFoundException.class); } @Test void filterWhenCancelAfterResponseThrownShouldNotRecordTimer() { ClientRequest request = ClientRequest - .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")).build(); + .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")) + .build(); given(this.response.rawStatusCode()).willReturn(HttpStatus.OK.value()); Mono filter = this.filterFunction.filter(request, this.exchange); StepVerifier.create(filter).expectNextCount(1).thenCancel().verify(Duration.ofSeconds(5)); assertThat(this.registry.get("http.client.requests") - .tags("method", "GET", "uri", "/projects/spring-boot", "status", "200").timer().count()).isEqualTo(1); + .tags("method", "GET", "uri", "/projects/spring-boot", "status", "200") + .timer() + .count()).isEqualTo(1); assertThatThrownBy(() -> this.registry.get("http.client.requests") - .tags("method", "GET", "uri", "/projects/spring-boot", "status", "CLIENT_ERROR").timer()) - .isInstanceOf(MeterNotFoundException.class); + .tags("method", "GET", "uri", "/projects/spring-boot", "status", "CLIENT_ERROR") + .timer()).isInstanceOf(MeterNotFoundException.class); } @Test void filterWhenExceptionAndRetryShouldNotAccumulateRecordTime() { ClientRequest request = ClientRequest - .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")).build(); + .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")) + .build(); ExchangeFunction exchange = (r) -> Mono.error(new IllegalArgumentException()) - .delaySubscription(Duration.ofMillis(1000)).cast(ClientResponse.class); - this.filterFunction.filter(request, exchange).retry(1) - .onErrorResume(IllegalArgumentException.class, (t) -> Mono.empty()).block(Duration.ofSeconds(5)); + .delaySubscription(Duration.ofMillis(1000)) + .cast(ClientResponse.class); + this.filterFunction.filter(request, exchange) + .retry(1) + .onErrorResume(IllegalArgumentException.class, (t) -> Mono.empty()) + .block(Duration.ofSeconds(5)); Timer timer = this.registry.get("http.client.requests") - .tags("method", "GET", "uri", "/projects/spring-boot", "status", "CLIENT_ERROR").timer(); + .tags("method", "GET", "uri", "/projects/spring-boot", "status", "CLIENT_ERROR") + .timer(); assertThat(timer.count()).isEqualTo(2); assertThat(timer.max(TimeUnit.MILLISECONDS)).isLessThan(2000); } @@ -167,7 +189,8 @@ class MetricsWebClientFilterFunctionTests { @Test void whenMetricsRecordingFailsThenFilteringSucceeds() { ClientRequest request = ClientRequest - .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")).build(); + .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")) + .build(); given(this.response.rawStatusCode()).willReturn(HttpStatus.OK.value()); this.tagsProvider.failOnce(); this.filterFunction.filter(request, this.exchange).block(Duration.ofSeconds(5)); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsTests.java index 1a7b5538e6..73749cadde 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,8 @@ class WebClientExchangeTagsTests { @BeforeEach void setup() { this.request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")) - .attribute(URI_TEMPLATE_ATTRIBUTE, "https://example.org/projects/{project}").build(); + .attribute(URI_TEMPLATE_ATTRIBUTE, "https://example.org/projects/{project}") + .build(); this.response = mock(ClientResponse.class); } @@ -67,23 +68,25 @@ class WebClientExchangeTagsTests { @Test void uriWhenRelativeTemplateIsAvailableShouldReturnTemplate() { this.request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")) - .attribute(URI_TEMPLATE_ATTRIBUTE, "/projects/{project}").build(); + .attribute(URI_TEMPLATE_ATTRIBUTE, "/projects/{project}") + .build(); assertThat(WebClientExchangeTags.uri(this.request)).isEqualTo(Tag.of("uri", "/projects/{project}")); } @Test void uriWhenTemplateIsMissingShouldReturnPath() { this.request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")) - .build(); + .build(); assertThat(WebClientExchangeTags.uri(this.request)).isEqualTo(Tag.of("uri", "/projects/spring-boot")); } @Test void uriWhenTemplateIsMissingShouldReturnPathWithQueryParams() { this.request = ClientRequest - .create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot?section=docs")).build(); + .create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot?section=docs")) + .build(); assertThat(WebClientExchangeTags.uri(this.request)) - .isEqualTo(Tag.of("uri", "/projects/spring-boot?section=docs")); + .isEqualTo(Tag.of("uri", "/projects/spring-boot?section=docs")); } @Test @@ -105,7 +108,7 @@ class WebClientExchangeTagsTests { @Test void statusWhenClientException() { assertThat(WebClientExchangeTags.status(null, new IllegalArgumentException())) - .isEqualTo(Tag.of("status", "CLIENT_ERROR")); + .isEqualTo(Tag.of("status", "CLIENT_ERROR")); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/DefaultWebFluxTagsProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/DefaultWebFluxTagsProviderTests.java index ae2138346c..044431ff2c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/DefaultWebFluxTagsProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/DefaultWebFluxTagsProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,14 +51,15 @@ class DefaultWebFluxTagsProviderTests { ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/test")); Map tags = asMap( new DefaultWebFluxTagsProvider(Arrays.asList(new TestWebFluxTagsContributor("alpha"), - new TestWebFluxTagsContributor("bravo", "charlie"))).httpRequestTags(exchange, null)); + new TestWebFluxTagsContributor("bravo", "charlie"))) + .httpRequestTags(exchange, null)); assertThat(tags).containsOnlyKeys("exception", "method", "outcome", "status", "uri", "alpha", "bravo", "charlie"); } private Map asMap(Iterable tags) { return StreamSupport.stream(tags.spliterator(), false) - .collect(Collectors.toMap(Tag::getKey, Function.identity())); + .collect(Collectors.toMap(Tag::getKey, Function.identity())); } private static final class TestWebFluxTagsContributor implements WebFluxTagsContributor { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilterTests.java index 267279dcec..f4bae33486 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,7 +72,7 @@ class MetricsWebFilterTests { void filterAddsTagsToRegistry() { MockServerWebExchange exchange = createExchange("/projects/spring-boot", "/projects/{project}"); this.webFilter.filter(exchange, (serverWebExchange) -> exchange.getResponse().setComplete()) - .block(Duration.ofSeconds(30)); + .block(Duration.ofSeconds(30)); assertMetricsContainsTag("uri", "/projects/{project}"); assertMetricsContainsTag("status", "200"); } @@ -81,10 +81,11 @@ class MetricsWebFilterTests { void filterAddsTagsToRegistryForExceptions() { MockServerWebExchange exchange = createExchange("/projects/spring-boot", "/projects/{project}"); this.webFilter.filter(exchange, (serverWebExchange) -> Mono.error(new IllegalStateException("test error"))) - .onErrorResume((t) -> { - exchange.getResponse().setRawStatusCode(500); - return exchange.getResponse().setComplete(); - }).block(Duration.ofSeconds(30)); + .onErrorResume((t) -> { + exchange.getResponse().setRawStatusCode(500); + return exchange.getResponse().setComplete(); + }) + .block(Duration.ofSeconds(30)); assertMetricsContainsTag("uri", "/projects/{project}"); assertMetricsContainsTag("status", "500"); assertMetricsContainsTag("exception", "IllegalStateException"); @@ -133,11 +134,11 @@ class MetricsWebFilterTests { MockServerWebExchange exchange1 = createExchange("/projects/spring-boot", "/projects/{project}"); MockServerWebExchange exchange2 = createExchange("/projects/spring-boot", "/projects/{project}/"); this.webFilter.filter(exchange1, (serverWebExchange) -> exchange1.getResponse().setComplete()) - .block(Duration.ofSeconds(30)); + .block(Duration.ofSeconds(30)); this.webFilter.filter(exchange2, (serverWebExchange) -> exchange2.getResponse().setComplete()) - .block(Duration.ofSeconds(30)); + .block(Duration.ofSeconds(30)); assertThat(this.registry.get(REQUEST_METRICS_NAME).tag("uri", "/projects/{project}").timer().count()) - .isEqualTo(2); + .isEqualTo(2); assertThat(this.registry.get(REQUEST_METRICS_NAME).tag("status", "200").timer().count()).isEqualTo(2); } @@ -156,11 +157,11 @@ class MetricsWebFilterTests { void disconnectedExceptionShouldProduceMetrics() { MockServerWebExchange exchange = createExchange("/projects/spring-boot", "/projects/{project}"); Mono processing = this.webFilter - .filter(exchange, (serverWebExchange) -> Mono.error(new EOFException("Disconnected"))) - .onErrorResume((t) -> { - exchange.getResponse().setRawStatusCode(500); - return exchange.getResponse().setComplete(); - }); + .filter(exchange, (serverWebExchange) -> Mono.error(new EOFException("Disconnected"))) + .onErrorResume((t) -> { + exchange.getResponse().setRawStatusCode(500); + return exchange.getResponse().setComplete(); + }); StepVerifier.create(processing).expectComplete().verify(Duration.ofSeconds(5)); assertMetricsContainsTag("uri", "/projects/{project}"); assertMetricsContainsTag("status", "500"); @@ -171,7 +172,7 @@ class MetricsWebFilterTests { void filterAddsStandardTags() { MockServerWebExchange exchange = createTimedHandlerMethodExchange("timed"); this.webFilter.filter(exchange, (serverWebExchange) -> exchange.getResponse().setComplete()) - .block(Duration.ofSeconds(30)); + .block(Duration.ofSeconds(30)); assertMetricsContainsTag("uri", "/projects/{project}"); assertMetricsContainsTag("status", "200"); } @@ -180,7 +181,7 @@ class MetricsWebFilterTests { void filterAddsExtraTags() { MockServerWebExchange exchange = createTimedHandlerMethodExchange("timedExtraTags"); this.webFilter.filter(exchange, (serverWebExchange) -> exchange.getResponse().setComplete()) - .block(Duration.ofSeconds(30)); + .block(Duration.ofSeconds(30)); assertMetricsContainsTag("uri", "/projects/{project}"); assertMetricsContainsTag("status", "200"); assertMetricsContainsTag("tag1", "value1"); @@ -191,10 +192,11 @@ class MetricsWebFilterTests { void filterAddsExtraTagsAndException() { MockServerWebExchange exchange = createTimedHandlerMethodExchange("timedExtraTags"); this.webFilter.filter(exchange, (serverWebExchange) -> Mono.error(new IllegalStateException("test error"))) - .onErrorResume((ex) -> { - exchange.getResponse().setRawStatusCode(500); - return exchange.getResponse().setComplete(); - }).block(Duration.ofSeconds(30)); + .onErrorResume((ex) -> { + exchange.getResponse().setRawStatusCode(500); + return exchange.getResponse().setComplete(); + }) + .block(Duration.ofSeconds(30)); assertMetricsContainsTag("uri", "/projects/{project}"); assertMetricsContainsTag("status", "500"); assertMetricsContainsTag("exception", "IllegalStateException"); @@ -206,7 +208,7 @@ class MetricsWebFilterTests { void filterAddsPercentileMeters() { MockServerWebExchange exchange = createTimedHandlerMethodExchange("timedPercentiles"); this.webFilter.filter(exchange, (serverWebExchange) -> exchange.getResponse().setComplete()) - .block(Duration.ofSeconds(30)); + .block(Duration.ofSeconds(30)); assertMetricsContainsTag("uri", "/projects/{project}"); assertMetricsContainsTag("status", "200"); assertThat(this.registry.get(REQUEST_METRICS_NAME_PERCENTILE).tag("phi", "0.95").gauge().value()).isNotZero(); @@ -218,13 +220,14 @@ class MetricsWebFilterTests { MockServerWebExchange exchange = createExchange("/projects/spring-boot", "/projects/{project}"); this.tagsProvider.failOnce(); this.webFilter.filter(exchange, (serverWebExchange) -> exchange.getResponse().setComplete()) - .block(Duration.ofSeconds(30)); + .block(Duration.ofSeconds(30)); } private MockServerWebExchange createTimedHandlerMethodExchange(String methodName) { MockServerWebExchange exchange = createExchange("/projects/spring-boot", "/projects/{project}"); - exchange.getAttributes().put(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE, - new HandlerMethod(this, ReflectionUtils.findMethod(Handlers.class, methodName))); + exchange.getAttributes() + .put(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE, + new HandlerMethod(this, ReflectionUtils.findMethod(Handlers.class, methodName))); return exchange; } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTagsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTagsTests.java index 7273b9b0f4..90bf64e7ba 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTagsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTagsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,8 +56,8 @@ class WebFluxTagsTests { @Test void uriTagValueIsBestMatchingPatternWhenAvailable() { - this.exchange.getAttributes().put(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, - this.parser.parse("/spring/")); + this.exchange.getAttributes() + .put(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, this.parser.parse("/spring/")); this.exchange.getResponse().setStatusCode(HttpStatus.MOVED_PERMANENTLY); Tag tag = WebFluxTags.uri(this.exchange); assertThat(tag.getValue()).isEqualTo("/spring/"); @@ -73,8 +73,8 @@ class WebFluxTagsTests { @Test void uriTagValueWithBestMatchingPatternAndIgnoreTrailingSlashRemoveTrailingSlash() { - this.exchange.getAttributes().put(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, - this.parser.parse("/spring/")); + this.exchange.getAttributes() + .put(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, this.parser.parse("/spring/")); Tag tag = WebFluxTags.uri(this.exchange, true); assertThat(tag.getValue()).isEqualTo("/spring"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptorTests.java index 68420af8b9..d30a0878df 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -90,11 +90,12 @@ class LongTaskTimingHandlerInterceptorTests { @Test void asyncRequestThatThrowsUncheckedException() throws Exception { MvcResult result = this.mvc.perform(get("/api/c1/completableFutureException")) - .andExpect(request().asyncStarted()).andReturn(); + .andExpect(request().asyncStarted()) + .andReturn(); assertThat(this.registry.get("my.long.request.exception").longTaskTimer().activeTasks()).isEqualTo(1); assertThatExceptionOfType(NestedServletException.class) - .isThrownBy(() -> this.mvc.perform(asyncDispatch(result))) - .withRootCauseInstanceOf(RuntimeException.class); + .isThrownBy(() -> this.mvc.perform(asyncDispatch(result))) + .withRootCauseInstanceOf(RuntimeException.class); assertThat(this.registry.get("my.long.request.exception").longTaskTimer().activeTasks()).isEqualTo(0); } @@ -103,8 +104,8 @@ class LongTaskTimingHandlerInterceptorTests { AtomicReference result = new AtomicReference<>(); Thread backgroundRequest = new Thread(() -> { try { - result.set( - this.mvc.perform(get("/api/c1/callable/10")).andExpect(request().asyncStarted()).andReturn()); + result + .set(this.mvc.perform(get("/api/c1/callable/10")).andExpect(request().asyncStarted()).andReturn()); } catch (Exception ex) { fail("Failed to execute async request", ex); @@ -113,12 +114,12 @@ class LongTaskTimingHandlerInterceptorTests { backgroundRequest.start(); this.callableBarrier.await(); assertThat(this.registry.get("my.long.request").tags("region", "test").longTaskTimer().activeTasks()) - .isEqualTo(1); + .isEqualTo(1); this.callableBarrier.await(); backgroundRequest.join(); this.mvc.perform(asyncDispatch(result.get())).andExpect(status().isOk()); assertThat(this.registry.get("my.long.request").tags("region", "test").longTaskTimer().activeTasks()) - .isEqualTo(0); + .isEqualTo(0); } @Test @@ -127,8 +128,8 @@ class LongTaskTimingHandlerInterceptorTests { AtomicReference result = new AtomicReference<>(); Thread backgroundRequest = new Thread(() -> { try { - result.set( - this.mvc.perform(get("/api/c1/callable/10")).andExpect(request().asyncStarted()).andReturn()); + result + .set(this.mvc.perform(get("/api/c1/callable/10")).andExpect(request().asyncStarted()).andReturn()); } catch (Exception ex) { fail("Failed to execute async request", ex); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterTests.java index 0aafe796a0..df58c13721 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -127,22 +127,27 @@ class WebMvcMetricsFilterTests { @BeforeEach void setupMockMvc() { - this.mvc = MockMvcBuilders.webAppContextSetup(this.context).addFilters(this.filter, new CustomBehaviorFilter()) - .build(); + this.mvc = MockMvcBuilders.webAppContextSetup(this.context) + .addFilters(this.filter, new CustomBehaviorFilter()) + .build(); } @Test void timedMethod() throws Exception { this.mvc.perform(get("/api/c1/10")).andExpect(status().isOk()); assertThat(this.registry.get("http.server.requests") - .tags("status", "200", "uri", "/api/c1/{id}", "public", "true").timer().count()).isEqualTo(1); + .tags("status", "200", "uri", "/api/c1/{id}", "public", "true") + .timer() + .count()).isEqualTo(1); } @Test void subclassedTimedMethod() throws Exception { this.mvc.perform(get("/api/c1/metaTimed/10")).andExpect(status().isOk()); - assertThat(this.registry.get("http.server.requests").tags("status", "200", "uri", "/api/c1/metaTimed/{id}") - .timer().count()).isEqualTo(1L); + assertThat(this.registry.get("http.server.requests") + .tags("status", "200", "uri", "/api/c1/metaTimed/{id}") + .timer() + .count()).isEqualTo(1L); } @Test @@ -166,40 +171,41 @@ class WebMvcMetricsFilterTests { @Test void redirectRequest() throws Exception { this.mvc.perform(get("/api/redirect").header(CustomBehaviorFilter.TEST_STATUS_HEADER, "302")) - .andExpect(status().is3xxRedirection()); + .andExpect(status().is3xxRedirection()); assertThat(this.registry.get("http.server.requests").tags("uri", "REDIRECTION").tags("status", "302").timer()) - .isNotNull(); + .isNotNull(); } @Test void notFoundRequest() throws Exception { this.mvc.perform(get("/api/not/found").header(CustomBehaviorFilter.TEST_STATUS_HEADER, "404")) - .andExpect(status().is4xxClientError()); + .andExpect(status().is4xxClientError()); assertThat(this.registry.get("http.server.requests").tags("uri", "NOT_FOUND").tags("status", "404").timer()) - .isNotNull(); + .isNotNull(); } @Test void unhandledError() { assertThatCode(() -> this.mvc.perform(get("/api/c1/unhandledError/10"))) - .hasRootCauseInstanceOf(RuntimeException.class); + .hasRootCauseInstanceOf(RuntimeException.class); assertThat(this.registry.get("http.server.requests").tags("exception", "RuntimeException").timer().count()) - .isEqualTo(1L); + .isEqualTo(1L); } @Test void unhandledServletException() { assertThatCode(() -> this.mvc - .perform(get("/api/filterError").header(CustomBehaviorFilter.TEST_SERVLET_EXCEPTION_HEADER, "throw"))) - .isInstanceOf(ServletException.class); + .perform(get("/api/filterError").header(CustomBehaviorFilter.TEST_SERVLET_EXCEPTION_HEADER, "throw"))) + .isInstanceOf(ServletException.class); Id meterId = this.registry.get("http.server.requests").tags("exception", "ServletException").timer().getId(); assertThat(meterId.getTag("status")).isEqualTo("500"); } @Test void streamingError() throws Exception { - MvcResult result = this.mvc.perform(get("/api/c1/streamingError")).andExpect(request().asyncStarted()) - .andReturn(); + MvcResult result = this.mvc.perform(get("/api/c1/streamingError")) + .andExpect(request().asyncStarted()) + .andReturn(); assertThatIOException().isThrownBy(() -> this.mvc.perform(asyncDispatch(result)).andReturn()); Id meterId = this.registry.get("http.server.requests").tags("exception", "IOException").timer().getId(); // Response is committed before error occurs so status is 200 (OK) @@ -219,8 +225,10 @@ class WebMvcMetricsFilterTests { } catch (Throwable ignore) { } - Id meterId = this.registry.get("http.server.requests").tag("uri", "/api/c1/anonymousError/{id}").timer() - .getId(); + Id meterId = this.registry.get("http.server.requests") + .tag("uri", "/api/c1/anonymousError/{id}") + .timer() + .getId(); assertThat(meterId.getTag("exception")).endsWith("$1"); assertThat(meterId.getTag("status")).isEqualTo("500"); } @@ -230,8 +238,8 @@ class WebMvcMetricsFilterTests { AtomicReference result = new AtomicReference<>(); Thread backgroundRequest = new Thread(() -> { try { - result.set( - this.mvc.perform(get("/api/c1/callable/10")).andExpect(request().asyncStarted()).andReturn()); + result + .set(this.mvc.perform(get("/api/c1/callable/10")).andExpect(request().asyncStarted()).andReturn()); } catch (Exception ex) { fail("Failed to execute async request", ex); @@ -239,26 +247,33 @@ class WebMvcMetricsFilterTests { }); backgroundRequest.start(); assertThat(this.registry.find("http.server.requests").tags("uri", "/api/c1/async").timer()) - .describedAs("Request isn't prematurely recorded as complete").isNull(); + .describedAs("Request isn't prematurely recorded as complete") + .isNull(); // once the mapping completes, we can gather information about status, etc. this.callableBarrier.await(); MockClock.clock(this.registry).add(Duration.ofSeconds(2)); this.callableBarrier.await(); backgroundRequest.join(); this.mvc.perform(asyncDispatch(result.get())).andExpect(status().isOk()); - assertThat(this.registry.get("http.server.requests").tags("status", "200").tags("uri", "/api/c1/callable/{id}") - .timer().totalTime(TimeUnit.SECONDS)).isEqualTo(2L); + assertThat(this.registry.get("http.server.requests") + .tags("status", "200") + .tags("uri", "/api/c1/callable/{id}") + .timer() + .totalTime(TimeUnit.SECONDS)).isEqualTo(2L); } @Test void asyncRequestThatThrowsUncheckedException() throws Exception { MvcResult result = this.mvc.perform(get("/api/c1/completableFutureException")) - .andExpect(request().asyncStarted()).andReturn(); + .andExpect(request().asyncStarted()) + .andReturn(); assertThatExceptionOfType(NestedServletException.class) - .isThrownBy(() -> this.mvc.perform(asyncDispatch(result))) - .withRootCauseInstanceOf(RuntimeException.class); - assertThat(this.registry.get("http.server.requests").tags("uri", "/api/c1/completableFutureException").timer() - .count()).isEqualTo(1); + .isThrownBy(() -> this.mvc.perform(asyncDispatch(result))) + .withRootCauseInstanceOf(RuntimeException.class); + assertThat(this.registry.get("http.server.requests") + .tags("uri", "/api/c1/completableFutureException") + .timer() + .count()).isEqualTo(1); } @Test @@ -267,7 +282,8 @@ class WebMvcMetricsFilterTests { Thread backgroundRequest = new Thread(() -> { try { result.set(this.mvc.perform(get("/api/c1/completableFuture/{id}", 1)) - .andExpect(request().asyncStarted()).andReturn()); + .andExpect(request().asyncStarted()) + .andReturn()); } catch (Exception ex) { fail("Failed to execute async request", ex); @@ -279,15 +295,19 @@ class WebMvcMetricsFilterTests { this.completableFutureBarrier.await(); backgroundRequest.join(); this.mvc.perform(asyncDispatch(result.get())).andExpect(status().isOk()); - assertThat(this.registry.get("http.server.requests").tags("uri", "/api/c1/completableFuture/{id}").timer() - .totalTime(TimeUnit.SECONDS)).isEqualTo(2); + assertThat(this.registry.get("http.server.requests") + .tags("uri", "/api/c1/completableFuture/{id}") + .timer() + .totalTime(TimeUnit.SECONDS)).isEqualTo(2); } @Test void endpointThrowsError() throws Exception { this.mvc.perform(get("/api/c1/error/10")).andExpect(status().is4xxClientError()); - assertThat(this.registry.get("http.server.requests").tags("status", "422", "exception", "IllegalStateException") - .timer().count()).isEqualTo(1L); + assertThat(this.registry.get("http.server.requests") + .tags("status", "422", "exception", "IllegalStateException") + .timer() + .count()).isEqualTo(1L); } @Test @@ -295,7 +315,7 @@ class WebMvcMetricsFilterTests { this.mvc.perform(get("/api/c1/regex/.abc")).andExpect(status().isOk()); assertThat( this.registry.get("http.server.requests").tags("uri", "/api/c1/regex/{id:\\.[a-z]+}").timer().count()) - .isEqualTo(1L); + .isEqualTo(1L); } @Test @@ -316,8 +336,10 @@ class WebMvcMetricsFilterTests { void trailingSlashShouldNotRecordDuplicateMetrics() throws Exception { this.mvc.perform(get("/api/c1/simple/10")).andExpect(status().isOk()); this.mvc.perform(get("/api/c1/simple/10/")).andExpect(status().isOk()); - assertThat(this.registry.get("http.server.requests").tags("status", "200", "uri", "/api/c1/simple/{id}").timer() - .count()).isEqualTo(2); + assertThat(this.registry.get("http.server.requests") + .tags("status", "200", "uri", "/api/c1/simple/{id}") + .timer() + .count()).isEqualTo(2); } @Target({ ElementType.METHOD }) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsIntegrationTests.java index e7d4d383b5..19ee3d6189 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -80,16 +80,20 @@ class WebMvcMetricsIntegrationTests { @Test void handledExceptionIsRecordedInMetricTag() throws Exception { this.mvc.perform(get("/api/handledError")).andExpect(status().is5xxServerError()); - assertThat(this.registry.get("http.server.requests").tags("exception", "Exception1", "status", "500").timer() - .count()).isEqualTo(1L); + assertThat(this.registry.get("http.server.requests") + .tags("exception", "Exception1", "status", "500") + .timer() + .count()).isEqualTo(1L); } @Test void rethrownExceptionIsRecordedInMetricTag() { assertThatExceptionOfType(NestedServletException.class) - .isThrownBy(() -> this.mvc.perform(get("/api/rethrownError")).andReturn()); - assertThat(this.registry.get("http.server.requests").tags("exception", "Exception2", "status", "500").timer() - .count()).isEqualTo(1L); + .isThrownBy(() -> this.mvc.perform(get("/api/rethrownError")).andReturn()); + assertThat(this.registry.get("http.server.requests") + .tags("exception", "Exception2", "status", "500") + .timer() + .count()).isEqualTo(1L); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicatorTests.java index 582dc58507..9b1e549d02 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +57,7 @@ class MongoReactiveHealthIndicatorTests { void testMongoIsDown() { ReactiveMongoTemplate reactiveMongoTemplate = mock(ReactiveMongoTemplate.class); given(reactiveMongoTemplate.executeCommand("{ buildInfo: 1 }")) - .willThrow(new MongoException("Connection failed")); + .willThrow(new MongoException("Connection failed")); MongoReactiveHealthIndicator mongoReactiveHealthIndicator = new MongoReactiveHealthIndicator( reactiveMongoTemplate); Mono health = mongoReactiveHealthIndicator.health(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicatorIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicatorIntegrationTests.java index 46911127d1..e1f78865c6 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicatorIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicatorIntegrationTests.java @@ -50,7 +50,8 @@ public class Neo4jReactiveHealthIndicatorIntegrationTests { @Container private static final Neo4jContainer neo4jServer = new Neo4jContainer<>(DockerImageNames.neo4j()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void neo4jProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointTests.java index a7a8e3388c..10bf07a064 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -92,14 +92,20 @@ class QuartzEndpointTests { private static final JobDetail jobThree = JobBuilder.newJob(Job.class).withIdentity("jobThree", "samples").build(); - private static final Trigger triggerOne = TriggerBuilder.newTrigger().forJob(jobOne).withIdentity("triggerOne") - .build(); + private static final Trigger triggerOne = TriggerBuilder.newTrigger() + .forJob(jobOne) + .withIdentity("triggerOne") + .build(); - private static final Trigger triggerTwo = TriggerBuilder.newTrigger().forJob(jobOne).withIdentity("triggerTwo") - .build(); + private static final Trigger triggerTwo = TriggerBuilder.newTrigger() + .forJob(jobOne) + .withIdentity("triggerTwo") + .build(); - private static final Trigger triggerThree = TriggerBuilder.newTrigger().forJob(jobThree) - .withIdentity("triggerThree", "samples").build(); + private static final Trigger triggerThree = TriggerBuilder.newTrigger() + .forJob(jobThree) + .withIdentity("triggerThree", "samples") + .build(); private final Scheduler scheduler; @@ -146,9 +152,9 @@ class QuartzEndpointTests { Map jobGroups = this.endpoint.quartzJobGroups().getGroups(); assertThat(jobGroups).containsOnlyKeys("DEFAULT", "samples"); assertThat(jobGroups).extractingByKey("DEFAULT", nestedMap()) - .containsOnly(entry("jobs", Arrays.asList("jobOne", "jobTwo"))); + .containsOnly(entry("jobs", Arrays.asList("jobOne", "jobTwo"))); assertThat(jobGroups).extractingByKey("samples", nestedMap()) - .containsOnly(entry("jobs", Collections.singletonList("jobThree"))); + .containsOnly(entry("jobs", Collections.singletonList("jobThree"))); } @Test @@ -164,10 +170,10 @@ class QuartzEndpointTests { given(this.scheduler.getPausedTriggerGroups()).willReturn(Collections.singleton("samples")); Map triggerGroups = this.endpoint.quartzTriggerGroups().getGroups(); assertThat(triggerGroups).containsOnlyKeys("DEFAULT", "samples"); - assertThat(triggerGroups).extractingByKey("DEFAULT", nestedMap()).containsOnly(entry("paused", false), - entry("triggers", Arrays.asList("triggerOne", "triggerTwo"))); - assertThat(triggerGroups).extractingByKey("samples", nestedMap()).containsOnly(entry("paused", true), - entry("triggers", Collections.singletonList("triggerThree"))); + assertThat(triggerGroups).extractingByKey("DEFAULT", nestedMap()) + .containsOnly(entry("paused", false), entry("triggers", Arrays.asList("triggerOne", "triggerTwo"))); + assertThat(triggerGroups).extractingByKey("samples", nestedMap()) + .containsOnly(entry("paused", true), entry("triggers", Collections.singletonList("triggerThree"))); } @Test @@ -217,7 +223,7 @@ class QuartzEndpointTests { void quartzTriggerGroupSummaryWithEmptyGroup() throws SchedulerException { given(this.scheduler.getTriggerGroupNames()).willReturn(Collections.singletonList("samples")); given(this.scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals("samples"))) - .willReturn(Collections.emptySet()); + .willReturn(Collections.emptySet()); QuartzTriggerGroupSummary summary = this.endpoint.quartzTriggerGroupSummary("samples"); assertThat(summary).isNotNull(); assertThat(summary.getGroup()).isEqualTo("samples"); @@ -231,8 +237,10 @@ class QuartzEndpointTests { @Test void quartzTriggerGroupSummaryWithCronTrigger() throws SchedulerException { - CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("3am-every-day", "samples") - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)).build(); + CronTrigger cronTrigger = TriggerBuilder.newTrigger() + .withIdentity("3am-every-day", "samples") + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)) + .build(); mockTriggers(cronTrigger); QuartzTriggerGroupSummary summary = this.endpoint.quartzTriggerGroupSummary("samples"); assertThat(summary.getGroup()).isEqualTo("samples"); @@ -249,23 +257,28 @@ class QuartzEndpointTests { Date previousFireTime = Date.from(Instant.parse("2020-11-30T03:00:00Z")); Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); TimeZone timeZone = TimeZone.getTimeZone("Europe/Paris"); - CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("3am-every-day", "samples").withPriority(3) - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0).inTimeZone(timeZone)).build(); + CronTrigger cronTrigger = TriggerBuilder.newTrigger() + .withIdentity("3am-every-day", "samples") + .withPriority(3) + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0).inTimeZone(timeZone)) + .build(); ((OperableTrigger) cronTrigger).setPreviousFireTime(previousFireTime); ((OperableTrigger) cronTrigger).setNextFireTime(nextFireTime); mockTriggers(cronTrigger); QuartzTriggerGroupSummary summary = this.endpoint.quartzTriggerGroupSummary("samples"); Map triggers = summary.getTriggers().getCron(); assertThat(triggers).containsOnlyKeys("3am-every-day"); - assertThat(triggers).extractingByKey("3am-every-day", nestedMap()).containsOnly( - entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), entry("priority", 3), - entry("expression", "0 0 3 ? * *"), entry("timeZone", timeZone)); + assertThat(triggers).extractingByKey("3am-every-day", nestedMap()) + .containsOnly(entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), + entry("priority", 3), entry("expression", "0 0 3 ? * *"), entry("timeZone", timeZone)); } @Test void quartzTriggerGroupSummaryWithSimpleTrigger() throws SchedulerException { - SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger().withIdentity("every-hour", "samples") - .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(1)).build(); + SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger() + .withIdentity("every-hour", "samples") + .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(1)) + .build(); mockTriggers(simpleTrigger); QuartzTriggerGroupSummary summary = this.endpoint.quartzTriggerGroupSummary("samples"); assertThat(summary.getGroup()).isEqualTo("samples"); @@ -281,25 +294,30 @@ class QuartzEndpointTests { void quartzTriggerGroupSummaryWithSimpleTriggerDetails() throws SchedulerException { Date previousFireTime = Date.from(Instant.parse("2020-11-30T03:00:00Z")); Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); - SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger().withIdentity("every-hour", "samples").withPriority(7) - .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(1)).build(); + SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger() + .withIdentity("every-hour", "samples") + .withPriority(7) + .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(1)) + .build(); ((OperableTrigger) simpleTrigger).setPreviousFireTime(previousFireTime); ((OperableTrigger) simpleTrigger).setNextFireTime(nextFireTime); mockTriggers(simpleTrigger); QuartzTriggerGroupSummary summary = this.endpoint.quartzTriggerGroupSummary("samples"); Map triggers = summary.getTriggers().getSimple(); assertThat(triggers).containsOnlyKeys("every-hour"); - assertThat(triggers).extractingByKey("every-hour", nestedMap()).containsOnly( - entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), entry("priority", 7), - entry("interval", 3600000L)); + assertThat(triggers).extractingByKey("every-hour", nestedMap()) + .containsOnly(entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), + entry("priority", 7), entry("interval", 3600000L)); } @Test void quartzTriggerGroupSummaryWithDailyIntervalTrigger() throws SchedulerException { - DailyTimeIntervalTrigger trigger = TriggerBuilder.newTrigger().withIdentity("every-hour-9am", "samples") - .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() - .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)).withInterval(1, IntervalUnit.HOUR)) - .build(); + DailyTimeIntervalTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("every-hour-9am", "samples") + .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() + .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)) + .withInterval(1, IntervalUnit.HOUR)) + .build(); mockTriggers(trigger); QuartzTriggerGroupSummary summary = this.endpoint.quartzTriggerGroupSummary("samples"); assertThat(summary.getGroup()).isEqualTo("samples"); @@ -315,31 +333,34 @@ class QuartzEndpointTests { void quartzTriggerGroupSummaryWithDailyIntervalTriggerDetails() throws SchedulerException { Date previousFireTime = Date.from(Instant.parse("2020-11-30T03:00:00Z")); Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); - DailyTimeIntervalTrigger trigger = TriggerBuilder.newTrigger().withIdentity("every-hour-tue-thu", "samples") - .withPriority(4) - .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() - .onDaysOfTheWeek(Calendar.TUESDAY, Calendar.THURSDAY) - .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)) - .endingDailyAt(TimeOfDay.hourAndMinuteOfDay(18, 0)).withInterval(1, IntervalUnit.HOUR)) - .build(); + DailyTimeIntervalTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("every-hour-tue-thu", "samples") + .withPriority(4) + .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() + .onDaysOfTheWeek(Calendar.TUESDAY, Calendar.THURSDAY) + .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)) + .endingDailyAt(TimeOfDay.hourAndMinuteOfDay(18, 0)) + .withInterval(1, IntervalUnit.HOUR)) + .build(); ((OperableTrigger) trigger).setPreviousFireTime(previousFireTime); ((OperableTrigger) trigger).setNextFireTime(nextFireTime); mockTriggers(trigger); QuartzTriggerGroupSummary summary = this.endpoint.quartzTriggerGroupSummary("samples"); Map triggers = summary.getTriggers().getDailyTimeInterval(); assertThat(triggers).containsOnlyKeys("every-hour-tue-thu"); - assertThat(triggers).extractingByKey("every-hour-tue-thu", nestedMap()).containsOnly( - entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), entry("priority", 4), - entry("interval", 3600000L), entry("startTimeOfDay", LocalTime.of(9, 0)), - entry("endTimeOfDay", LocalTime.of(18, 0)), - entry("daysOfWeek", new LinkedHashSet<>(Arrays.asList(3, 5)))); + assertThat(triggers).extractingByKey("every-hour-tue-thu", nestedMap()) + .containsOnly(entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), + entry("priority", 4), entry("interval", 3600000L), entry("startTimeOfDay", LocalTime.of(9, 0)), + entry("endTimeOfDay", LocalTime.of(18, 0)), + entry("daysOfWeek", new LinkedHashSet<>(Arrays.asList(3, 5)))); } @Test void quartzTriggerGroupSummaryWithCalendarIntervalTrigger() throws SchedulerException { - CalendarIntervalTrigger trigger = TriggerBuilder.newTrigger().withIdentity("once-a-week", "samples") - .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(1)) - .build(); + CalendarIntervalTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("once-a-week", "samples") + .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(1)) + .build(); mockTriggers(trigger); QuartzTriggerGroupSummary summary = this.endpoint.quartzTriggerGroupSummary("samples"); assertThat(summary.getGroup()).isEqualTo("samples"); @@ -356,19 +377,22 @@ class QuartzEndpointTests { TimeZone timeZone = TimeZone.getTimeZone("Europe/Paris"); Date previousFireTime = Date.from(Instant.parse("2020-11-30T03:00:00Z")); Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); - CalendarIntervalTrigger trigger = TriggerBuilder.newTrigger().withIdentity("once-a-week", "samples") - .withPriority(8).withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule() - .withIntervalInWeeks(1).inTimeZone(timeZone)) - .build(); + CalendarIntervalTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("once-a-week", "samples") + .withPriority(8) + .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule() + .withIntervalInWeeks(1) + .inTimeZone(timeZone)) + .build(); ((OperableTrigger) trigger).setPreviousFireTime(previousFireTime); ((OperableTrigger) trigger).setNextFireTime(nextFireTime); mockTriggers(trigger); QuartzTriggerGroupSummary summary = this.endpoint.quartzTriggerGroupSummary("samples"); Map triggers = summary.getTriggers().getCalendarInterval(); assertThat(triggers).containsOnlyKeys("once-a-week"); - assertThat(triggers).extractingByKey("once-a-week", nestedMap()).containsOnly( - entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), entry("priority", 8), - entry("interval", 604800000L), entry("timeZone", timeZone)); + assertThat(triggers).extractingByKey("once-a-week", nestedMap()) + .containsOnly(entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), + entry("priority", 8), entry("interval", 604800000L), entry("timeZone", timeZone)); } @Test @@ -399,9 +423,9 @@ class QuartzEndpointTests { QuartzTriggerGroupSummary summary = this.endpoint.quartzTriggerGroupSummary("samples"); Map triggers = summary.getTriggers().getCustom(); assertThat(triggers).containsOnlyKeys("custom"); - assertThat(triggers).extractingByKey("custom", nestedMap()).containsOnly( - entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), entry("priority", 9), - entry("trigger", trigger.toString())); + assertThat(triggers).extractingByKey("custom", nestedMap()) + .containsOnly(entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), + entry("priority", 9), entry("trigger", trigger.toString())); } @Test @@ -409,14 +433,17 @@ class QuartzEndpointTests { Date previousFireTime = Date.from(Instant.parse("2020-11-30T03:00:00Z")); Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); TimeZone timeZone = TimeZone.getTimeZone("Europe/Paris"); - CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("3am-every-day", "samples").withPriority(3) - .withDescription("Sample description") - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0).inTimeZone(timeZone)).build(); + CronTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("3am-every-day", "samples") + .withPriority(3) + .withDescription("Sample description") + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0).inTimeZone(timeZone)) + .build(); ((OperableTrigger) trigger).setPreviousFireTime(previousFireTime); ((OperableTrigger) trigger).setNextFireTime(nextFireTime); mockTriggers(trigger); given(this.scheduler.getTriggerState(TriggerKey.triggerKey("3am-every-day", "samples"))) - .willReturn(TriggerState.NORMAL); + .willReturn(TriggerState.NORMAL); Map triggerDetails = this.endpoint.quartzTrigger("samples", "3am-every-day"); assertThat(triggerDetails).contains(entry("group", "samples"), entry("name", "3am-every-day"), entry("description", "Sample description"), entry("type", "cron"), entry("state", TriggerState.NORMAL), @@ -424,8 +451,8 @@ class QuartzEndpointTests { assertThat(triggerDetails).contains(entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime)); assertThat(triggerDetails).doesNotContainKeys("simple", "dailyTimeInterval", "calendarInterval", "custom"); - assertThat(triggerDetails).extractingByKey("cron", nestedMap()).containsOnly(entry("expression", "0 0 3 ? * *"), - entry("timeZone", timeZone)); + assertThat(triggerDetails).extractingByKey("cron", nestedMap()) + .containsOnly(entry("expression", "0 0 3 ? * *"), entry("timeZone", timeZone)); } @Test @@ -434,15 +461,19 @@ class QuartzEndpointTests { Date previousFireTime = Date.from(Instant.parse("2020-11-30T03:00:00Z")); Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); Date endTime = Date.from(Instant.parse("2020-01-31T09:00:00Z")); - SimpleTrigger trigger = TriggerBuilder.newTrigger().withIdentity("every-hour", "samples").withPriority(20) - .withDescription("Every hour").startAt(startTime).endAt(endTime) - .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInHours(1).withRepeatCount(2000)) - .build(); + SimpleTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("every-hour", "samples") + .withPriority(20) + .withDescription("Every hour") + .startAt(startTime) + .endAt(endTime) + .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInHours(1).withRepeatCount(2000)) + .build(); ((OperableTrigger) trigger).setPreviousFireTime(previousFireTime); ((OperableTrigger) trigger).setNextFireTime(nextFireTime); mockTriggers(trigger); given(this.scheduler.getTriggerState(TriggerKey.triggerKey("every-hour", "samples"))) - .willReturn(TriggerState.COMPLETE); + .willReturn(TriggerState.COMPLETE); Map triggerDetails = this.endpoint.quartzTrigger("samples", "every-hour"); assertThat(triggerDetails).contains(entry("group", "samples"), entry("name", "every-hour"), entry("description", "Every hour"), entry("type", "simple"), entry("state", TriggerState.COMPLETE), @@ -450,26 +481,29 @@ class QuartzEndpointTests { assertThat(triggerDetails).contains(entry("startTime", startTime), entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), entry("endTime", endTime)); assertThat(triggerDetails).doesNotContainKeys("cron", "dailyTimeInterval", "calendarInterval", "custom"); - assertThat(triggerDetails).extractingByKey("simple", nestedMap()).containsOnly(entry("interval", 3600000L), - entry("repeatCount", 2000), entry("timesTriggered", 0)); + assertThat(triggerDetails).extractingByKey("simple", nestedMap()) + .containsOnly(entry("interval", 3600000L), entry("repeatCount", 2000), entry("timesTriggered", 0)); } @Test void quartzTriggerWithDailyTimeIntervalTrigger() throws SchedulerException { Date previousFireTime = Date.from(Instant.parse("2020-11-30T03:00:00Z")); Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); - DailyTimeIntervalTrigger trigger = TriggerBuilder.newTrigger().withIdentity("every-hour-mon-wed", "samples") - .withDescription("Every working hour Mon Wed").withPriority(4) - .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() - .onDaysOfTheWeek(Calendar.MONDAY, Calendar.WEDNESDAY) - .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)) - .endingDailyAt(TimeOfDay.hourAndMinuteOfDay(18, 0)).withInterval(1, IntervalUnit.HOUR)) - .build(); + DailyTimeIntervalTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("every-hour-mon-wed", "samples") + .withDescription("Every working hour Mon Wed") + .withPriority(4) + .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() + .onDaysOfTheWeek(Calendar.MONDAY, Calendar.WEDNESDAY) + .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)) + .endingDailyAt(TimeOfDay.hourAndMinuteOfDay(18, 0)) + .withInterval(1, IntervalUnit.HOUR)) + .build(); ((OperableTrigger) trigger).setPreviousFireTime(previousFireTime); ((OperableTrigger) trigger).setNextFireTime(nextFireTime); mockTriggers(trigger); given(this.scheduler.getTriggerState(TriggerKey.triggerKey("every-hour-mon-wed", "samples"))) - .willReturn(TriggerState.NORMAL); + .willReturn(TriggerState.NORMAL); Map triggerDetails = this.endpoint.quartzTrigger("samples", "every-hour-mon-wed"); assertThat(triggerDetails).contains(entry("group", "samples"), entry("name", "every-hour-mon-wed"), entry("description", "Every working hour Mon Wed"), entry("type", "dailyTimeInterval"), @@ -477,11 +511,11 @@ class QuartzEndpointTests { assertThat(triggerDetails).contains(entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime)); assertThat(triggerDetails).doesNotContainKeys("cron", "simple", "calendarInterval", "custom"); - assertThat(triggerDetails).extractingByKey("dailyTimeInterval", nestedMap()).containsOnly( - entry("interval", 3600000L), entry("startTimeOfDay", LocalTime.of(9, 0)), - entry("endTimeOfDay", LocalTime.of(18, 0)), - entry("daysOfWeek", new LinkedHashSet<>(Arrays.asList(2, 4))), entry("repeatCount", -1), - entry("timesTriggered", 0)); + assertThat(triggerDetails).extractingByKey("dailyTimeInterval", nestedMap()) + .containsOnly(entry("interval", 3600000L), entry("startTimeOfDay", LocalTime.of(9, 0)), + entry("endTimeOfDay", LocalTime.of(18, 0)), + entry("daysOfWeek", new LinkedHashSet<>(Arrays.asList(2, 4))), entry("repeatCount", -1), + entry("timesTriggered", 0)); } @Test @@ -489,16 +523,20 @@ class QuartzEndpointTests { TimeZone timeZone = TimeZone.getTimeZone("Europe/Paris"); Date previousFireTime = Date.from(Instant.parse("2020-11-30T03:00:00Z")); Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); - CalendarIntervalTrigger trigger = TriggerBuilder.newTrigger().withIdentity("once-a-week", "samples") - .withDescription("Once a week").withPriority(8) - .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(1) - .inTimeZone(timeZone).preserveHourOfDayAcrossDaylightSavings(true)) - .build(); + CalendarIntervalTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("once-a-week", "samples") + .withDescription("Once a week") + .withPriority(8) + .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule() + .withIntervalInWeeks(1) + .inTimeZone(timeZone) + .preserveHourOfDayAcrossDaylightSavings(true)) + .build(); ((OperableTrigger) trigger).setPreviousFireTime(previousFireTime); ((OperableTrigger) trigger).setNextFireTime(nextFireTime); mockTriggers(trigger); given(this.scheduler.getTriggerState(TriggerKey.triggerKey("once-a-week", "samples"))) - .willReturn(TriggerState.BLOCKED); + .willReturn(TriggerState.BLOCKED); Map triggerDetails = this.endpoint.quartzTrigger("samples", "once-a-week"); assertThat(triggerDetails).contains(entry("group", "samples"), entry("name", "once-a-week"), entry("description", "Once a week"), entry("type", "calendarInterval"), @@ -506,10 +544,10 @@ class QuartzEndpointTests { assertThat(triggerDetails).contains(entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime)); assertThat(triggerDetails).doesNotContainKeys("cron", "simple", "dailyTimeInterval", "custom"); - assertThat(triggerDetails).extractingByKey("calendarInterval", nestedMap()).containsOnly( - entry("interval", 604800000L), entry("timeZone", timeZone), - entry("preserveHourOfDayAcrossDaylightSavings", true), entry("skipDayIfHourDoesNotExist", false), - entry("timesTriggered", 0)); + assertThat(triggerDetails).extractingByKey("calendarInterval", nestedMap()) + .containsOnly(entry("interval", 604800000L), entry("timeZone", timeZone), + entry("preserveHourOfDayAcrossDaylightSavings", true), entry("skipDayIfHourDoesNotExist", false), + entry("timesTriggered", 0)); } @Test @@ -523,7 +561,7 @@ class QuartzEndpointTests { given(trigger.getPriority()).willReturn(9); mockTriggers(trigger); given(this.scheduler.getTriggerState(TriggerKey.triggerKey("custom", "samples"))) - .willReturn(TriggerState.ERROR); + .willReturn(TriggerState.ERROR); Map triggerDetails = this.endpoint.quartzTrigger("samples", "custom"); assertThat(triggerDetails).contains(entry("group", "samples"), entry("name", "custom"), entry("type", "custom"), entry("state", TriggerState.ERROR), entry("priority", 9)); @@ -531,32 +569,38 @@ class QuartzEndpointTests { entry("nextFireTime", nextFireTime)); assertThat(triggerDetails).doesNotContainKeys("cron", "simple", "calendarInterval", "dailyTimeInterval"); assertThat(triggerDetails).extractingByKey("custom", nestedMap()) - .containsOnly(entry("trigger", trigger.toString())); + .containsOnly(entry("trigger", trigger.toString())); } @Test void quartzTriggerWithDataMap() throws SchedulerException { - CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("3am-every-day", "samples") - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)).usingJobData("user", "user") - .usingJobData("password", "secret").usingJobData("url", "https://user:secret@example.com").build(); + CronTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("3am-every-day", "samples") + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)) + .usingJobData("user", "user") + .usingJobData("password", "secret") + .usingJobData("url", "https://user:secret@example.com") + .build(); mockTriggers(trigger); given(this.scheduler.getTriggerState(TriggerKey.triggerKey("3am-every-day", "samples"))) - .willReturn(TriggerState.NORMAL); + .willReturn(TriggerState.NORMAL); Map triggerDetails = this.endpoint.quartzTrigger("samples", "3am-every-day"); - assertThat(triggerDetails).extractingByKey("data", nestedMap()).containsOnly(entry("user", "user"), - entry("password", "******"), entry("url", "https://user:******@example.com")); + assertThat(triggerDetails).extractingByKey("data", nestedMap()) + .containsOnly(entry("user", "user"), entry("password", "******"), + entry("url", "https://user:******@example.com")); } @ParameterizedTest(name = "unit {1}") @MethodSource("intervalUnitParameters") void canConvertIntervalUnit(int amount, IntervalUnit unit, Duration expectedDuration) throws SchedulerException { - CalendarIntervalTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger", "samples") - .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withInterval(amount, unit)) - .build(); + CalendarIntervalTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("trigger", "samples") + .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withInterval(amount, unit)) + .build(); mockTriggers(trigger); Map triggerDetails = this.endpoint.quartzTrigger("samples", "trigger"); assertThat(triggerDetails).extractingByKey("calendarInterval", nestedMap()) - .contains(entry("interval", expectedDuration.toMillis())); + .contains(entry("interval", expectedDuration.toMillis())); } static Stream intervalUnitParameters() { @@ -572,8 +616,12 @@ class QuartzEndpointTests { @Test void quartzJobWithoutTrigger() throws SchedulerException { - JobDetail job = JobBuilder.newJob(Job.class).withIdentity("hello", "samples").withDescription("A sample job") - .storeDurably().requestRecovery(false).build(); + JobDetail job = JobBuilder.newJob(Job.class) + .withIdentity("hello", "samples") + .withDescription("A sample job") + .storeDurably() + .requestRecovery(false) + .build(); mockJobs(job); QuartzJobDetails jobDetails = this.endpoint.quartzJob("samples", "hello"); assertThat(jobDetails.getGroup()).isEqualTo("samples"); @@ -592,14 +640,17 @@ class QuartzEndpointTests { Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); JobDetail job = JobBuilder.newJob(Job.class).withIdentity("hello", "samples").build(); TimeZone timeZone = TimeZone.getTimeZone("Europe/Paris"); - Trigger trigger = TriggerBuilder.newTrigger().withIdentity("3am-every-day", "samples").withPriority(4) - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0).inTimeZone(timeZone)).build(); + Trigger trigger = TriggerBuilder.newTrigger() + .withIdentity("3am-every-day", "samples") + .withPriority(4) + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0).inTimeZone(timeZone)) + .build(); ((OperableTrigger) trigger).setPreviousFireTime(previousFireTime); ((OperableTrigger) trigger).setNextFireTime(nextFireTime); mockJobs(job); mockTriggers(trigger); given(this.scheduler.getTriggersOfJob(JobKey.jobKey("hello", "samples"))) - .willAnswer((invocation) -> Collections.singletonList(trigger)); + .willAnswer((invocation) -> Collections.singletonList(trigger)); QuartzJobDetails jobDetails = this.endpoint.quartzJob("samples", "hello"); assertThat(jobDetails.getTriggers()).hasSize(1); Map triggerDetails = jobDetails.getTriggers().get(0); @@ -612,16 +663,22 @@ class QuartzEndpointTests { JobDetail job = JobBuilder.newJob(Job.class).withIdentity("hello", "samples").build(); mockJobs(job); Date triggerOneNextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); - CronTrigger triggerOne = TriggerBuilder.newTrigger().withIdentity("one", "samples").withPriority(5) - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)).build(); + CronTrigger triggerOne = TriggerBuilder.newTrigger() + .withIdentity("one", "samples") + .withPriority(5) + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)) + .build(); ((OperableTrigger) triggerOne).setNextFireTime(triggerOneNextFireTime); Date triggerTwoNextFireTime = Date.from(Instant.parse("2020-12-01T02:00:00Z")); - CronTrigger triggerTwo = TriggerBuilder.newTrigger().withIdentity("two", "samples").withPriority(10) - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(2, 0)).build(); + CronTrigger triggerTwo = TriggerBuilder.newTrigger() + .withIdentity("two", "samples") + .withPriority(10) + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(2, 0)) + .build(); ((OperableTrigger) triggerTwo).setNextFireTime(triggerTwoNextFireTime); mockTriggers(triggerOne, triggerTwo); given(this.scheduler.getTriggersOfJob(JobKey.jobKey("hello", "samples"))) - .willAnswer((invocation) -> Arrays.asList(triggerOne, triggerTwo)); + .willAnswer((invocation) -> Arrays.asList(triggerOne, triggerTwo)); QuartzJobDetails jobDetails = this.endpoint.quartzJob("samples", "hello"); assertThat(jobDetails.getTriggers()).hasSize(2); assertThat(jobDetails.getTriggers().get(0)).containsEntry("name", "two"); @@ -633,15 +690,21 @@ class QuartzEndpointTests { JobDetail job = JobBuilder.newJob(Job.class).withIdentity("hello", "samples").build(); mockJobs(job); Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); - CronTrigger triggerOne = TriggerBuilder.newTrigger().withIdentity("one", "samples").withPriority(3) - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)).build(); + CronTrigger triggerOne = TriggerBuilder.newTrigger() + .withIdentity("one", "samples") + .withPriority(3) + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)) + .build(); ((OperableTrigger) triggerOne).setNextFireTime(nextFireTime); - CronTrigger triggerTwo = TriggerBuilder.newTrigger().withIdentity("two", "samples").withPriority(7) - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)).build(); + CronTrigger triggerTwo = TriggerBuilder.newTrigger() + .withIdentity("two", "samples") + .withPriority(7) + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)) + .build(); ((OperableTrigger) triggerTwo).setNextFireTime(nextFireTime); mockTriggers(triggerOne, triggerTwo); given(this.scheduler.getTriggersOfJob(JobKey.jobKey("hello", "samples"))) - .willAnswer((invocation) -> Arrays.asList(triggerOne, triggerTwo)); + .willAnswer((invocation) -> Arrays.asList(triggerOne, triggerTwo)); QuartzJobDetails jobDetails = this.endpoint.quartzJob("samples", "hello"); assertThat(jobDetails.getTriggers()).hasSize(2); assertThat(jobDetails.getTriggers().get(0)).containsEntry("name", "two"); @@ -650,8 +713,12 @@ class QuartzEndpointTests { @Test void quartzJobWithSensitiveDataMap() throws SchedulerException { - JobDetail job = JobBuilder.newJob(Job.class).withIdentity("hello", "samples").usingJobData("user", "user") - .usingJobData("password", "secret").usingJobData("url", "https://user:secret@example.com").build(); + JobDetail job = JobBuilder.newJob(Job.class) + .withIdentity("hello", "samples") + .usingJobData("user", "user") + .usingJobData("password", "secret") + .usingJobData("url", "https://user:secret@example.com") + .build(); mockJobs(job); QuartzJobDetails jobDetails = this.endpoint.quartzJob("samples", "hello"); assertThat(jobDetails.getData()).containsOnly(entry("user", "user"), entry("password", "******"), @@ -660,8 +727,11 @@ class QuartzEndpointTests { @Test void quartzJobWithSensitiveDataMapAndCustomSanitizer() throws SchedulerException { - JobDetail job = JobBuilder.newJob(Job.class).withIdentity("hello", "samples").usingJobData("test", "value") - .usingJobData("secret", "value").build(); + JobDetail job = JobBuilder.newJob(Job.class) + .withIdentity("hello", "samples") + .usingJobData("test", "value") + .usingJobData("secret", "value") + .build(); mockJobs(job); Sanitizer sanitizer = mock(Sanitizer.class); given(sanitizer.sanitize("test", "value")).willReturn("value"); @@ -683,7 +753,7 @@ class QuartzEndpointTests { given(this.scheduler.getJobGroupNames()).willReturn(new ArrayList<>(jobKeys.keySet())); for (Entry> entry : jobKeys.entrySet()) { given(this.scheduler.getJobKeys(GroupMatcher.jobGroupEquals(entry.getKey()))) - .willReturn(new LinkedHashSet<>(entry.getValue())); + .willReturn(new LinkedHashSet<>(entry.getValue())); } } @@ -697,7 +767,7 @@ class QuartzEndpointTests { given(this.scheduler.getTriggerGroupNames()).willReturn(new ArrayList<>(triggerKeys.keySet())); for (Entry> entry : triggerKeys.entrySet()) { given(this.scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(entry.getKey()))) - .willReturn(new LinkedHashSet<>(entry.getValue())); + .willReturn(new LinkedHashSet<>(entry.getValue())); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointWebIntegrationTests.java index cd58eddaa3..9e3e2c847f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,47 +61,80 @@ import static org.mockito.Mockito.mock; */ class QuartzEndpointWebIntegrationTests { - private static final JobDetail jobOne = JobBuilder.newJob(Job.class).withIdentity("jobOne", "samples") - .usingJobData(new JobDataMap(Collections.singletonMap("name", "test"))).withDescription("A sample job") - .build(); + private static final JobDetail jobOne = JobBuilder.newJob(Job.class) + .withIdentity("jobOne", "samples") + .usingJobData(new JobDataMap(Collections.singletonMap("name", "test"))) + .withDescription("A sample job") + .build(); - private static final JobDetail jobTwo = JobBuilder.newJob(DelegatingJob.class).withIdentity("jobTwo", "samples") - .build(); + private static final JobDetail jobTwo = JobBuilder.newJob(DelegatingJob.class) + .withIdentity("jobTwo", "samples") + .build(); private static final JobDetail jobThree = JobBuilder.newJob(Job.class).withIdentity("jobThree").build(); - private static final CronTrigger triggerOne = TriggerBuilder.newTrigger().withDescription("Once a day 3AM") - .withIdentity("triggerOne").withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)).build(); + private static final CronTrigger triggerOne = TriggerBuilder.newTrigger() + .withDescription("Once a day 3AM") + .withIdentity("triggerOne") + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)) + .build(); - private static final SimpleTrigger triggerTwo = TriggerBuilder.newTrigger().withDescription("Once a day") - .withIdentity("triggerTwo", "tests").withSchedule(SimpleScheduleBuilder.repeatHourlyForever(24)).build(); + private static final SimpleTrigger triggerTwo = TriggerBuilder.newTrigger() + .withDescription("Once a day") + .withIdentity("triggerTwo", "tests") + .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(24)) + .build(); private static final CalendarIntervalTrigger triggerThree = TriggerBuilder.newTrigger() - .withDescription("Once a week").withIdentity("triggerThree", "tests") - .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(1)).build(); + .withDescription("Once a week") + .withIdentity("triggerThree", "tests") + .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(1)) + .build(); @WebEndpointTest void quartzReport(WebTestClient client) { - client.get().uri("/actuator/quartz").exchange().expectStatus().isOk().expectBody().jsonPath("jobs.groups") - .isEqualTo(new JSONArray().appendElement("samples").appendElement("DEFAULT")) - .jsonPath("triggers.groups").isEqualTo(new JSONArray().appendElement("DEFAULT").appendElement("tests")); + client.get() + .uri("/actuator/quartz") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("jobs.groups") + .isEqualTo(new JSONArray().appendElement("samples").appendElement("DEFAULT")) + .jsonPath("triggers.groups") + .isEqualTo(new JSONArray().appendElement("DEFAULT").appendElement("tests")); } @WebEndpointTest void quartzJobNames(WebTestClient client) { - client.get().uri("/actuator/quartz/jobs").exchange().expectStatus().isOk().expectBody() - .jsonPath("groups.samples.jobs") - .isEqualTo(new JSONArray().appendElement("jobOne").appendElement("jobTwo")) - .jsonPath("groups.DEFAULT.jobs").isEqualTo(new JSONArray().appendElement("jobThree")); + client.get() + .uri("/actuator/quartz/jobs") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("groups.samples.jobs") + .isEqualTo(new JSONArray().appendElement("jobOne").appendElement("jobTwo")) + .jsonPath("groups.DEFAULT.jobs") + .isEqualTo(new JSONArray().appendElement("jobThree")); } @WebEndpointTest void quartzTriggerNames(WebTestClient client) { - client.get().uri("/actuator/quartz/triggers").exchange().expectStatus().isOk().expectBody() - .jsonPath("groups.DEFAULT.paused").isEqualTo(false).jsonPath("groups.DEFAULT.triggers") - .isEqualTo(new JSONArray().appendElement("triggerOne")).jsonPath("groups.tests.paused").isEqualTo(false) - .jsonPath("groups.tests.triggers") - .isEqualTo(new JSONArray().appendElement("triggerTwo").appendElement("triggerThree")); + client.get() + .uri("/actuator/quartz/triggers") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("groups.DEFAULT.paused") + .isEqualTo(false) + .jsonPath("groups.DEFAULT.triggers") + .isEqualTo(new JSONArray().appendElement("triggerOne")) + .jsonPath("groups.tests.paused") + .isEqualTo(false) + .jsonPath("groups.tests.triggers") + .isEqualTo(new JSONArray().appendElement("triggerTwo").appendElement("triggerThree")); } @WebEndpointTest @@ -111,9 +144,18 @@ class QuartzEndpointWebIntegrationTests { @WebEndpointTest void quartzJobGroupSummary(WebTestClient client) { - client.get().uri("/actuator/quartz/jobs/samples").exchange().expectStatus().isOk().expectBody() - .jsonPath("group").isEqualTo("samples").jsonPath("jobs.jobOne.className").isEqualTo(Job.class.getName()) - .jsonPath("jobs.jobTwo.className").isEqualTo(DelegatingJob.class.getName()); + client.get() + .uri("/actuator/quartz/jobs/samples") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("group") + .isEqualTo("samples") + .jsonPath("jobs.jobOne.className") + .isEqualTo(Job.class.getName()) + .jsonPath("jobs.jobTwo.className") + .isEqualTo(DelegatingJob.class.getName()); } @WebEndpointTest @@ -123,12 +165,26 @@ class QuartzEndpointWebIntegrationTests { @WebEndpointTest void quartzTriggerGroupSummary(WebTestClient client) { - client.get().uri("/actuator/quartz/triggers/tests").exchange().expectStatus().isOk().expectBody() - .jsonPath("group").isEqualTo("tests").jsonPath("paused").isEqualTo("false").jsonPath("triggers.cron") - .isEmpty().jsonPath("triggers.simple.triggerTwo.interval").isEqualTo(86400000) - .jsonPath("triggers.dailyTimeInterval").isEmpty() - .jsonPath("triggers.calendarInterval.triggerThree.interval").isEqualTo(604800000) - .jsonPath("triggers.custom").isEmpty(); + client.get() + .uri("/actuator/quartz/triggers/tests") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("group") + .isEqualTo("tests") + .jsonPath("paused") + .isEqualTo("false") + .jsonPath("triggers.cron") + .isEmpty() + .jsonPath("triggers.simple.triggerTwo.interval") + .isEqualTo(86400000) + .jsonPath("triggers.dailyTimeInterval") + .isEmpty() + .jsonPath("triggers.calendarInterval.triggerThree.interval") + .isEqualTo(604800000) + .jsonPath("triggers.custom") + .isEmpty(); } @WebEndpointTest @@ -138,9 +194,18 @@ class QuartzEndpointWebIntegrationTests { @WebEndpointTest void quartzJobDetail(WebTestClient client) { - client.get().uri("/actuator/quartz/jobs/samples/jobOne").exchange().expectStatus().isOk().expectBody() - .jsonPath("group").isEqualTo("samples").jsonPath("name").isEqualTo("jobOne").jsonPath("data.name") - .isEqualTo("test"); + client.get() + .uri("/actuator/quartz/jobs/samples/jobOne") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("group") + .isEqualTo("samples") + .jsonPath("name") + .isEqualTo("jobOne") + .jsonPath("data.name") + .isEqualTo("test"); } @WebEndpointTest @@ -150,11 +215,32 @@ class QuartzEndpointWebIntegrationTests { @WebEndpointTest void quartzTriggerDetail(WebTestClient client) { - client.get().uri("/actuator/quartz/triggers/DEFAULT/triggerOne").exchange().expectStatus().isOk().expectBody() - .jsonPath("group").isEqualTo("DEFAULT").jsonPath("name").isEqualTo("triggerOne").jsonPath("description") - .isEqualTo("Once a day 3AM").jsonPath("state").isEqualTo("NORMAL").jsonPath("type").isEqualTo("cron") - .jsonPath("simple").doesNotExist().jsonPath("calendarInterval").doesNotExist().jsonPath("dailyInterval") - .doesNotExist().jsonPath("custom").doesNotExist().jsonPath("cron.expression").isEqualTo("0 0 3 ? * *"); + client.get() + .uri("/actuator/quartz/triggers/DEFAULT/triggerOne") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("group") + .isEqualTo("DEFAULT") + .jsonPath("name") + .isEqualTo("triggerOne") + .jsonPath("description") + .isEqualTo("Once a day 3AM") + .jsonPath("state") + .isEqualTo("NORMAL") + .jsonPath("type") + .isEqualTo("cron") + .jsonPath("simple") + .doesNotExist() + .jsonPath("calendarInterval") + .doesNotExist() + .jsonPath("dailyInterval") + .doesNotExist() + .jsonPath("custom") + .doesNotExist() + .jsonPath("cron.expression") + .isEqualTo("0 0 3 ? * *"); } @WebEndpointTest @@ -193,7 +279,7 @@ class QuartzEndpointWebIntegrationTests { given(scheduler.getJobGroupNames()).willReturn(new ArrayList<>(jobKeys.keySet())); for (Entry> entry : jobKeys.entrySet()) { given(scheduler.getJobKeys(GroupMatcher.jobGroupEquals(entry.getKey()))) - .willReturn(new LinkedHashSet<>(entry.getValue())); + .willReturn(new LinkedHashSet<>(entry.getValue())); } } @@ -208,7 +294,7 @@ class QuartzEndpointWebIntegrationTests { given(scheduler.getTriggerGroupNames()).willReturn(new ArrayList<>(triggerKeys.keySet())); for (Entry> entry : triggerKeys.entrySet()) { given(scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(entry.getKey()))) - .willReturn(new LinkedHashSet<>(entry.getValue())); + .willReturn(new LinkedHashSet<>(entry.getValue())); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/r2dbc/ConnectionFactoryHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/r2dbc/ConnectionFactoryHealthIndicatorTests.java index f22484d7a4..2f57add1bb 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/r2dbc/ConnectionFactoryHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/r2dbc/ConnectionFactoryHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -100,9 +100,11 @@ class ConnectionFactoryHealthIndicatorTests { String customValidationQuery = "SELECT COUNT(*) from HEALTH_TEST"; String createTableStatement = "CREATE TABLE HEALTH_TEST (id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY)"; Mono.from(connectionFactory.create()) - .flatMapMany((it) -> Flux.from(it.createStatement(createTableStatement).execute()) - .flatMap(Result::getRowsUpdated).thenMany(it.close())) - .as(StepVerifier::create).verifyComplete(); + .flatMapMany((it) -> Flux.from(it.createStatement(createTableStatement).execute()) + .flatMap(Result::getRowsUpdated) + .thenMany(it.close())) + .as(StepVerifier::create) + .verifyComplete(); ReactiveHealthIndicator healthIndicator = new ConnectionFactoryHealthIndicator(connectionFactory, customValidationQuery); healthIndicator.health().as(StepVerifier::create).assertNext((actual) -> { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicatorTests.java index f45b25eb92..e28aed8a65 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -113,8 +113,9 @@ class RedisReactiveHealthIndicatorTests { given(redisConnection.closeLater()).willReturn(Mono.empty()); RedisReactiveHealthIndicator healthIndicator = createHealthIndicator(redisConnection, commands); Mono health = healthIndicator.health(); - StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) - .verifyComplete(); + StepVerifier.create(health) + .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) + .verifyComplete(); then(redisConnection).should().closeLater(); } @@ -122,11 +123,12 @@ class RedisReactiveHealthIndicatorTests { void redisConnectionIsDown() { ReactiveRedisConnectionFactory redisConnectionFactory = mock(ReactiveRedisConnectionFactory.class); given(redisConnectionFactory.getReactiveConnection()) - .willThrow(new RedisConnectionException("Unable to connect to localhost:6379")); + .willThrow(new RedisConnectionException("Unable to connect to localhost:6379")); RedisReactiveHealthIndicator healthIndicator = new RedisReactiveHealthIndicator(redisConnectionFactory); Mono health = healthIndicator.health(); - StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) - .verifyComplete(); + StepVerifier.create(health) + .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) + .verifyComplete(); } private RedisReactiveHealthIndicator createHealthIndicator(ReactiveRedisConnection redisConnection, diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpointTests.java index 7fb2bffe0c..1faf5d747d 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ScheduledTasksEndpointTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(BaseConfiguration.class); + .withUserConfiguration(BaseConfiguration.class); @Test void cronScheduledMethodIsReported() { @@ -89,7 +89,7 @@ class ScheduledTasksEndpointTests { assertThat(description.getInitialDelay()).isEqualTo(2); assertThat(description.getInterval()).isEqualTo(1); assertThat(description.getRunnable().getTarget()) - .isEqualTo(FixedDelayScheduledMethod.class.getName() + ".fixedDelay"); + .isEqualTo(FixedDelayScheduledMethod.class.getName() + ".fixedDelay"); }); } @@ -118,7 +118,7 @@ class ScheduledTasksEndpointTests { assertThat(description.getInitialDelay()).isEqualTo(4); assertThat(description.getInterval()).isEqualTo(3); assertThat(description.getRunnable().getTarget()) - .isEqualTo(FixedRateScheduledMethod.class.getName() + ".fixedRate"); + .isEqualTo(FixedRateScheduledMethod.class.getName() + ".fixedRate"); }); } @@ -151,7 +151,7 @@ class ScheduledTasksEndpointTests { private void run(Class configuration, Consumer consumer) { this.contextRunner.withUserConfiguration(configuration) - .run((context) -> consumer.accept(context.getBean(ScheduledTasksEndpoint.class).scheduledTasks())); + .run((context) -> consumer.accept(context.getBean(ScheduledTasksEndpoint.class).scheduledTasks())); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointTests.java index 5095187a56..eb1647e389 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ class SessionsEndpointTests { @Test void sessionsForUsername() { given(this.repository.findByPrincipalName("user")) - .willReturn(Collections.singletonMap(session.getId(), session)); + .willReturn(Collections.singletonMap(session.getId(), session)); List result = this.endpoint.sessionsForUsername("user").getSessions(); assertThat(result).hasSize(1); assertThat(result.get(0).getId()).isEqualTo(session.getId()); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointWebIntegrationTests.java index 26b1f0757f..0a6b28dd83 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,29 +47,46 @@ class SessionsEndpointWebIntegrationTests { @WebEndpointTest void sessionsForUsernameWithoutUsernameParam(WebTestClient client) { - client.get().uri((builder) -> builder.path("/actuator/sessions").build()).exchange().expectStatus() - .isBadRequest(); + client.get() + .uri((builder) -> builder.path("/actuator/sessions").build()) + .exchange() + .expectStatus() + .isBadRequest(); } @WebEndpointTest void sessionsForUsernameNoResults(WebTestClient client) { given(repository.findByPrincipalName("user")).willReturn(Collections.emptyMap()); - client.get().uri((builder) -> builder.path("/actuator/sessions").queryParam("username", "user").build()) - .exchange().expectStatus().isOk().expectBody().jsonPath("sessions").isEmpty(); + client.get() + .uri((builder) -> builder.path("/actuator/sessions").queryParam("username", "user").build()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("sessions") + .isEmpty(); } @WebEndpointTest void sessionsForUsernameFound(WebTestClient client) { given(repository.findByPrincipalName("user")).willReturn(Collections.singletonMap(session.getId(), session)); - client.get().uri((builder) -> builder.path("/actuator/sessions").queryParam("username", "user").build()) - .exchange().expectStatus().isOk().expectBody().jsonPath("sessions.[*].id") - .isEqualTo(new JSONArray().appendElement(session.getId())); + client.get() + .uri((builder) -> builder.path("/actuator/sessions").queryParam("username", "user").build()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("sessions.[*].id") + .isEqualTo(new JSONArray().appendElement(session.getId())); } @WebEndpointTest void sessionForIdNotFound(WebTestClient client) { - client.get().uri((builder) -> builder.path("/actuator/sessions/session-id-not-found").build()).exchange() - .expectStatus().isNotFound(); + client.get() + .uri((builder) -> builder.path("/actuator/sessions/session-id-not-found").build()) + .exchange() + .expectStatus() + .isNotFound(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/solr/SolrHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/solr/SolrHealthIndicatorTests.java index 31223253ac..2c27c55454 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/solr/SolrHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/solr/SolrHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,7 +69,7 @@ class SolrHealthIndicatorTests { void healthWhenSolrStatusUpAndBaseUrlPointsToParticularCoreReturnsUp() throws Exception { SolrClient solrClient = mock(SolrClient.class); given(solrClient.request(any(CoreAdminRequest.class), isNull())) - .willThrow(new RemoteSolrException("mock", 404, "", null)); + .willThrow(new RemoteSolrException("mock", 404, "", null)); given(solrClient.ping()).willReturn(mockPingResponse(0)); SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient); assertHealth(healthIndicator, Status.UP, 0, "particular core"); @@ -82,7 +82,7 @@ class SolrHealthIndicatorTests { void healthWhenSolrStatusDownAndBaseUrlPointsToParticularCoreReturnsDown() throws Exception { SolrClient solrClient = mock(SolrClient.class); given(solrClient.request(any(CoreAdminRequest.class), isNull())) - .willThrow(new RemoteSolrException("mock", 404, "", null)); + .willThrow(new RemoteSolrException("mock", 404, "", null)); given(solrClient.ping()).willReturn(mockPingResponse(400)); SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient); assertHealth(healthIndicator, Status.DOWN, 400, "particular core"); @@ -95,7 +95,7 @@ class SolrHealthIndicatorTests { void healthWhenSolrConnectionFailsReturnsDown() throws Exception { SolrClient solrClient = mock(SolrClient.class); given(solrClient.request(any(CoreAdminRequest.class), isNull())) - .willThrow(new IOException("Connection failed")); + .willThrow(new IOException("Connection failed")); SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); @@ -108,7 +108,7 @@ class SolrHealthIndicatorTests { void healthWhenMakingMultipleCallsRemembersStatusStrategy() throws Exception { SolrClient solrClient = mock(SolrClient.class); given(solrClient.request(any(CoreAdminRequest.class), isNull())) - .willThrow(new RemoteSolrException("mock", 404, "", null)); + .willThrow(new RemoteSolrException("mock", 404, "", null)); given(solrClient.ping()).willReturn(mockPingResponse(0)); SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient); healthIndicator.health(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/startup/StartupEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/startup/StartupEndpointTests.java index 6e9ae9e5b2..cf55d89824 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/startup/StartupEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/startup/StartupEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,7 @@ class StartupEndpointTests { StartupResponse startup = startupEndpoint.startup(); assertThat(startup.getSpringBootVersion()).isEqualTo(SpringBootVersion.getVersion()); assertThat(startup.getTimeline().getStartTime()) - .isEqualTo(applicationStartup.getBufferedTimeline().getStartTime()); + .isEqualTo(applicationStartup.getBufferedTimeline().getStartTime()); }); } @@ -71,8 +71,8 @@ class StartupEndpointTests { private void testStartupEndpoint(ApplicationStartup applicationStartup, Consumer startupEndpoint) { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withInitializer((context) -> context.setApplicationStartup(applicationStartup)) - .withUserConfiguration(EndpointConfiguration.class); + .withInitializer((context) -> context.setApplicationStartup(applicationStartup)) + .withUserConfiguration(EndpointConfiguration.class); contextRunner.run((context) -> { assertThat(context).hasSingleBean(StartupEndpoint.class); startupEndpoint.accept(context.getBean(StartupEndpoint.class)); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracerTests.java index 3b8a35fa6c..5d342f7c43 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -117,8 +117,8 @@ class HttpExchangeTracerTests { @Test void authorizationHeaderCanBeIncluded() { HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS, Include.AUTHORIZATION_HEADER)) - .receivedRequest( - createRequest(Collections.singletonMap(HttpHeaders.AUTHORIZATION, Arrays.asList("secret")))); + .receivedRequest( + createRequest(Collections.singletonMap(HttpHeaders.AUTHORIZATION, Arrays.asList("secret")))); Request request = trace.getRequest(); assertThat(request.getHeaders()).containsOnlyKeys(HttpHeaders.AUTHORIZATION); } @@ -126,16 +126,16 @@ class HttpExchangeTracerTests { @Test void mixedCaseAuthorizationHeaderCanBeIncluded() { HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS, Include.AUTHORIZATION_HEADER)) - .receivedRequest(createRequest( - Collections.singletonMap(mixedCase(HttpHeaders.AUTHORIZATION), Arrays.asList("secret")))); + .receivedRequest(createRequest( + Collections.singletonMap(mixedCase(HttpHeaders.AUTHORIZATION), Arrays.asList("secret")))); Request request = trace.getRequest(); assertThat(request.getHeaders()).containsOnlyKeys(mixedCase(HttpHeaders.AUTHORIZATION)); } @Test void cookieHeaderIsNotIncludedByDefault() { - HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS)).receivedRequest( - createRequest(Collections.singletonMap(HttpHeaders.COOKIE, Arrays.asList("test=test")))); + HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS)) + .receivedRequest(createRequest(Collections.singletonMap(HttpHeaders.COOKIE, Arrays.asList("test=test")))); Request request = trace.getRequest(); assertThat(request.getHeaders()).isEmpty(); } @@ -151,7 +151,7 @@ class HttpExchangeTracerTests { @Test void cookieHeaderCanBeIncluded() { HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS, Include.COOKIE_HEADERS)) - .receivedRequest(createRequest(Collections.singletonMap(HttpHeaders.COOKIE, Arrays.asList("value")))); + .receivedRequest(createRequest(Collections.singletonMap(HttpHeaders.COOKIE, Arrays.asList("value")))); Request request = trace.getRequest(); assertThat(request.getHeaders()).containsOnlyKeys(HttpHeaders.COOKIE); } @@ -159,8 +159,8 @@ class HttpExchangeTracerTests { @Test void mixedCaseCookieHeaderCanBeIncluded() { HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS, Include.COOKIE_HEADERS)) - .receivedRequest( - createRequest(Collections.singletonMap(mixedCase(HttpHeaders.COOKIE), Arrays.asList("value")))); + .receivedRequest( + createRequest(Collections.singletonMap(mixedCase(HttpHeaders.COOKIE), Arrays.asList("value")))); Request request = trace.getRequest(); assertThat(request.getHeaders()).containsOnlyKeys(mixedCase(HttpHeaders.COOKIE)); } @@ -327,8 +327,8 @@ class HttpExchangeTracerTests { private String mixedCase(String input) { StringBuilder output = new StringBuilder(); for (int i = 0; i < input.length(); i++) { - output.append( - (i % 2 != 0) ? Character.toUpperCase(input.charAt(i)) : Character.toLowerCase(input.charAt(i))); + output + .append((i % 2 != 0) ? Character.toUpperCase(input.charAt(i)) : Character.toLowerCase(input.charAt(i))); } return output.toString(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterIntegrationTests.java index a46547c046..570963a48f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,13 +52,18 @@ import static org.springframework.web.reactive.function.server.RouterFunctions.r class HttpTraceWebFilterIntegrationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withUserConfiguration(Config.class); + .withUserConfiguration(Config.class); @Test void traceForNotFoundResponseHas404Status() { this.contextRunner.run((context) -> { - WebTestClient.bindToApplicationContext(context).build().get().uri("/").exchange().expectStatus() - .isNotFound(); + WebTestClient.bindToApplicationContext(context) + .build() + .get() + .uri("/") + .exchange() + .expectStatus() + .isNotFound(); HttpTraceRepository repository = context.getBean(HttpTraceRepository.class); assertThat(repository.findAll()).hasSize(1); assertThat(repository.findAll().get(0).getResponse().getStatus()).isEqualTo(404); @@ -68,8 +73,13 @@ class HttpTraceWebFilterIntegrationTests { @Test void traceForMonoErrorWithRuntimeExceptionHas500Status() { this.contextRunner.run((context) -> { - WebTestClient.bindToApplicationContext(context).build().get().uri("/mono-error").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); + WebTestClient.bindToApplicationContext(context) + .build() + .get() + .uri("/mono-error") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); HttpTraceRepository repository = context.getBean(HttpTraceRepository.class); assertThat(repository.findAll()).hasSize(1); assertThat(repository.findAll().get(0).getResponse().getStatus()).isEqualTo(500); @@ -79,8 +89,13 @@ class HttpTraceWebFilterIntegrationTests { @Test void traceForThrownRuntimeExceptionHas500Status() { this.contextRunner.run((context) -> { - WebTestClient.bindToApplicationContext(context).build().get().uri("/thrown").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); + WebTestClient.bindToApplicationContext(context) + .build() + .get() + .uri("/thrown") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); HttpTraceRepository repository = context.getBean(HttpTraceRepository.class); assertThat(repository.findAll()).hasSize(1); assertThat(repository.findAll().get(0).getResponse().getStatus()).isEqualTo(500); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterTests.java index afecd178f8..e9c1065809 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,8 +62,9 @@ class HttpTraceWebFilterTests { @Test void filterCapturesSessionIdWhenSessionIsUsed() { executeFilter(MockServerWebExchange.from(MockServerHttpRequest.get("https://api.example.com")), - (exchange) -> exchange.getSession().doOnNext((session) -> session.getAttributes().put("a", "alpha")) - .then()); + (exchange) -> exchange.getSession() + .doOnNext((session) -> session.getAttributes().put("a", "alpha")) + .then()); assertThat(this.repository.findAll()).hasSize(1); Session session = this.repository.findAll().get(0).getSession(); assertThat(session).isNotNull(); @@ -95,15 +96,16 @@ class HttpTraceWebFilterTests { }, (exchange) -> exchange.getSession().doOnNext((session) -> session.getAttributes().put("a", "alpha")).then()); assertThat(this.repository.findAll()).hasSize(1); org.springframework.boot.actuate.trace.http.HttpTrace.Principal tracedPrincipal = this.repository.findAll() - .get(0).getPrincipal(); + .get(0) + .getPrincipal(); assertThat(tracedPrincipal).isNotNull(); assertThat(tracedPrincipal.getName()).isEqualTo("alice"); } private void executeFilter(ServerWebExchange exchange, WebFilterChain chain) { - StepVerifier.create( - this.filter.filter(exchange, chain).then(Mono.defer(() -> exchange.getResponse().setComplete()))) - .verifyComplete(); + StepVerifier + .create(this.filter.filter(exchange, chain).then(Mono.defer(() -> exchange.getResponse().setComplete()))) + .verifyComplete(); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/servlet/HttpTraceFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/servlet/HttpTraceFilterTests.java index bda27e8bd8..1bdf2aa54c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/servlet/HttpTraceFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/servlet/HttpTraceFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -93,7 +93,8 @@ class HttpTraceFilterTests { this.filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); assertThat(this.repository.findAll()).hasSize(1); org.springframework.boot.actuate.trace.http.HttpTrace.Principal tracedPrincipal = this.repository.findAll() - .get(0).getPrincipal(); + .get(0) + .getPrincipal(); assertThat(tracedPrincipal).isNotNull(); assertThat(tracedPrincipal.getName()).isEqualTo("alice"); } @@ -109,10 +110,11 @@ class HttpTraceFilterTests { throw new IOException(); } - }))).satisfies((ex) -> { - assertThat(this.repository.findAll()).hasSize(1); - assertThat(this.repository.findAll().get(0).getResponse().getStatus()).isEqualTo(500); - }); + }))) + .satisfies((ex) -> { + assertThat(this.repository.findAll()).hasSize(1); + assertThat(this.repository.findAll().get(0).getResponse().getStatus()).isEqualTo(500); + }); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/MappingsEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/MappingsEndpointTests.java index ef3349a5eb..a608c6c201 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/MappingsEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/MappingsEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,60 +79,63 @@ class MappingsEndpointTests { void servletWebMappings() { Supplier contextSupplier = prepareContextSupplier(); new WebApplicationContextRunner(contextSupplier) - .withUserConfiguration(EndpointConfiguration.class, ServletWebConfiguration.class).run((context) -> { - ContextMappings contextMappings = contextMappings(context); - assertThat(contextMappings.getParentId()).isNull(); - assertThat(contextMappings.getMappings()).containsOnlyKeys("dispatcherServlets", "servletFilters", - "servlets"); - Map> dispatcherServlets = mappings( - contextMappings, "dispatcherServlets"); - assertThat(dispatcherServlets).containsOnlyKeys("dispatcherServlet"); - List handlerMappings = dispatcherServlets - .get("dispatcherServlet"); - assertThat(handlerMappings).hasSize(1); - List servlets = mappings(contextMappings, "servlets"); - assertThat(servlets).hasSize(1); - List filters = mappings(contextMappings, "servletFilters"); - assertThat(filters).hasSize(1); - }); + .withUserConfiguration(EndpointConfiguration.class, ServletWebConfiguration.class) + .run((context) -> { + ContextMappings contextMappings = contextMappings(context); + assertThat(contextMappings.getParentId()).isNull(); + assertThat(contextMappings.getMappings()).containsOnlyKeys("dispatcherServlets", "servletFilters", + "servlets"); + Map> dispatcherServlets = mappings(contextMappings, + "dispatcherServlets"); + assertThat(dispatcherServlets).containsOnlyKeys("dispatcherServlet"); + List handlerMappings = dispatcherServlets.get("dispatcherServlet"); + assertThat(handlerMappings).hasSize(1); + List servlets = mappings(contextMappings, "servlets"); + assertThat(servlets).hasSize(1); + List filters = mappings(contextMappings, "servletFilters"); + assertThat(filters).hasSize(1); + }); } @Test void servletWebMappingsWithPathPatternParser() { Supplier contextSupplier = prepareContextSupplier(); - new WebApplicationContextRunner(contextSupplier).withUserConfiguration(EndpointConfiguration.class, - ServletWebConfiguration.class, PathPatternParserConfiguration.class).run((context) -> { - ContextMappings contextMappings = contextMappings(context); - assertThat(contextMappings.getParentId()).isNull(); - assertThat(contextMappings.getMappings()).containsOnlyKeys("dispatcherServlets", "servletFilters", - "servlets"); - Map> dispatcherServlets = mappings( - contextMappings, "dispatcherServlets"); - assertThat(dispatcherServlets).containsOnlyKeys("dispatcherServlet"); - List handlerMappings = dispatcherServlets - .get("dispatcherServlet"); - assertThat(handlerMappings).hasSize(1); - List servlets = mappings(contextMappings, "servlets"); - assertThat(servlets).hasSize(1); - List filters = mappings(contextMappings, "servletFilters"); - assertThat(filters).hasSize(1); - }); + new WebApplicationContextRunner(contextSupplier) + .withUserConfiguration(EndpointConfiguration.class, ServletWebConfiguration.class, + PathPatternParserConfiguration.class) + .run((context) -> { + ContextMappings contextMappings = contextMappings(context); + assertThat(contextMappings.getParentId()).isNull(); + assertThat(contextMappings.getMappings()).containsOnlyKeys("dispatcherServlets", "servletFilters", + "servlets"); + Map> dispatcherServlets = mappings(contextMappings, + "dispatcherServlets"); + assertThat(dispatcherServlets).containsOnlyKeys("dispatcherServlet"); + List handlerMappings = dispatcherServlets.get("dispatcherServlet"); + assertThat(handlerMappings).hasSize(1); + List servlets = mappings(contextMappings, "servlets"); + assertThat(servlets).hasSize(1); + List filters = mappings(contextMappings, "servletFilters"); + assertThat(filters).hasSize(1); + }); } @Test void servletWebMappingsWithAdditionalDispatcherServlets() { Supplier contextSupplier = prepareContextSupplier(); - new WebApplicationContextRunner(contextSupplier).withUserConfiguration(EndpointConfiguration.class, - ServletWebConfiguration.class, CustomDispatcherServletConfiguration.class).run((context) -> { - ContextMappings contextMappings = contextMappings(context); - Map> dispatcherServlets = mappings( - contextMappings, "dispatcherServlets"); - assertThat(dispatcherServlets).containsOnlyKeys("dispatcherServlet", - "customDispatcherServletRegistration", "anotherDispatcherServletRegistration"); - assertThat(dispatcherServlets.get("dispatcherServlet")).hasSize(1); - assertThat(dispatcherServlets.get("customDispatcherServletRegistration")).hasSize(1); - assertThat(dispatcherServlets.get("anotherDispatcherServletRegistration")).hasSize(1); - }); + new WebApplicationContextRunner(contextSupplier) + .withUserConfiguration(EndpointConfiguration.class, ServletWebConfiguration.class, + CustomDispatcherServletConfiguration.class) + .run((context) -> { + ContextMappings contextMappings = contextMappings(context); + Map> dispatcherServlets = mappings(contextMappings, + "dispatcherServlets"); + assertThat(dispatcherServlets).containsOnlyKeys("dispatcherServlet", + "customDispatcherServletRegistration", "anotherDispatcherServletRegistration"); + assertThat(dispatcherServlets.get("dispatcherServlet")).hasSize(1); + assertThat(dispatcherServlets.get("customDispatcherServletRegistration")).hasSize(1); + assertThat(dispatcherServlets.get("anotherDispatcherServletRegistration")).hasSize(1); + }); } @SuppressWarnings("unchecked") @@ -142,10 +145,10 @@ class MappingsEndpointTests { given(servletContext.getAttributeNames()).willReturn(Collections.emptyEnumeration()); FilterRegistration filterRegistration = mock(FilterRegistration.class); given((Map) servletContext.getFilterRegistrations()) - .willReturn(Collections.singletonMap("testFilter", filterRegistration)); + .willReturn(Collections.singletonMap("testFilter", filterRegistration)); ServletRegistration servletRegistration = mock(ServletRegistration.class); given((Map) servletContext.getServletRegistrations()) - .willReturn(Collections.singletonMap("testServlet", servletRegistration)); + .willReturn(Collections.singletonMap("testServlet", servletRegistration)); return () -> { AnnotationConfigServletWebApplicationContext context = new AnnotationConfigServletWebApplicationContext(); context.setServletContext(servletContext); @@ -156,16 +159,17 @@ class MappingsEndpointTests { @Test void reactiveWebMappings() { new ReactiveWebApplicationContextRunner() - .withUserConfiguration(EndpointConfiguration.class, ReactiveWebConfiguration.class).run((context) -> { - ContextMappings contextMappings = contextMappings(context); - assertThat(contextMappings.getParentId()).isNull(); - assertThat(contextMappings.getMappings()).containsOnlyKeys("dispatcherHandlers"); - Map> dispatcherHandlers = mappings( - contextMappings, "dispatcherHandlers"); - assertThat(dispatcherHandlers).containsOnlyKeys("webHandler"); - List handlerMappings = dispatcherHandlers.get("webHandler"); - assertThat(handlerMappings).hasSize(4); - }); + .withUserConfiguration(EndpointConfiguration.class, ReactiveWebConfiguration.class) + .run((context) -> { + ContextMappings contextMappings = contextMappings(context); + assertThat(contextMappings.getParentId()).isNull(); + assertThat(contextMappings.getMappings()).containsOnlyKeys("dispatcherHandlers"); + Map> dispatcherHandlers = mappings(contextMappings, + "dispatcherHandlers"); + assertThat(dispatcherHandlers).containsOnlyKeys("webHandler"); + List handlerMappings = dispatcherHandlers.get("webHandler"); + assertThat(handlerMappings).hasSize(4); + }); } private ContextMappings contextMappings(ApplicationContext context) { 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..206efd7367 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,8 +79,8 @@ public abstract class AbstractDependsOnBeanFactoryPostProcessor implements BeanF this.beanClass = beanClass; this.factoryBeanClass = factoryBeanClass; this.dependsOn = (beanFactory) -> Arrays.stream(dependencyTypes) - .flatMap((dependencyType) -> getBeanNames(beanFactory, dependencyType).stream()) - .collect(Collectors.toSet()); + .flatMap((dependencyType) -> getBeanNames(beanFactory, dependencyType).stream()) + .collect(Collectors.toSet()); } /** diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilter.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilter.java index 53d8919970..73e3bc30ea 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilter.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +57,7 @@ public class AutoConfigurationExcludeFilter implements TypeFilter, BeanClassLoad private boolean isAutoConfiguration(MetadataReader metadataReader) { boolean annotatedWithAutoConfiguration = metadataReader.getAnnotationMetadata() - .isAnnotated(AutoConfiguration.class.getName()); + .isAnnotated(AutoConfiguration.class.getName()); return annotatedWithAutoConfiguration || getAutoConfigurations().contains(metadataReader.getClassMetadata().getClassName()); } 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 416b1b0c94..480aab3dfa 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -252,8 +252,9 @@ public class AutoConfigurationImportSelector implements DeferredImportSelector, } if (environment instanceof ConfigurableEnvironment) { Binder binder = Binder.get(environment); - return binder.bind(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class).map(Arrays::asList) - .orElse(Collections.emptyList()); + return binder.bind(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class) + .map(Arrays::asList) + .orElse(Collections.emptyList()); } String[] excludes = environment.getProperty(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class); return (excludes != null) ? Arrays.asList(excludes) : Collections.emptyList(); @@ -437,7 +438,7 @@ public class AutoConfigurationImportSelector implements DeferredImportSelector, AutoConfigurationImportSelector.class.getSimpleName(), deferredImportSelector.getClass().getName())); AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector) deferredImportSelector) - .getAutoConfigurationEntry(annotationMetadata); + .getAutoConfigurationEntry(annotationMetadata); this.autoConfigurationEntries.add(autoConfigurationEntry); for (String importClassName : autoConfigurationEntry.getConfigurations()) { this.entries.putIfAbsent(importClassName, annotationMetadata); @@ -450,15 +451,18 @@ public class AutoConfigurationImportSelector implements DeferredImportSelector, return Collections.emptyList(); } Set allExclusions = this.autoConfigurationEntries.stream() - .map(AutoConfigurationEntry::getExclusions).flatMap(Collection::stream).collect(Collectors.toSet()); + .map(AutoConfigurationEntry::getExclusions) + .flatMap(Collection::stream) + .collect(Collectors.toSet()); Set processedConfigurations = this.autoConfigurationEntries.stream() - .map(AutoConfigurationEntry::getConfigurations).flatMap(Collection::stream) - .collect(Collectors.toCollection(LinkedHashSet::new)); + .map(AutoConfigurationEntry::getConfigurations) + .flatMap(Collection::stream) + .collect(Collectors.toCollection(LinkedHashSet::new)); processedConfigurations.removeAll(allExclusions); return sortAutoConfigurations(processedConfigurations, getAutoConfigurationMetadata()).stream() - .map((importClassName) -> new Entry(this.entries.get(importClassName), importClassName)) - .collect(Collectors.toList()); + .map((importClassName) -> new Entry(this.entries.get(importClassName), importClassName)) + .collect(Collectors.toList()); } private AutoConfigurationMetadata getAutoConfigurationMetadata() { @@ -471,7 +475,7 @@ public class AutoConfigurationImportSelector implements DeferredImportSelector, private List sortAutoConfigurations(Set configurations, AutoConfigurationMetadata autoConfigurationMetadata) { return new AutoConfigurationSorter(getMetadataReaderFactory(), autoConfigurationMetadata) - .getInPriorityOrder(configurations); + .getInPriorityOrder(configurations); } private MetadataReaderFactory getMetadataReaderFactory() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationPackages.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationPackages.java index 6799241c38..31c9957dde 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationPackages.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationPackages.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -127,7 +127,7 @@ public abstract class AutoConfigurationPackages { PackageImports(AnnotationMetadata metadata) { AnnotationAttributes attributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(AutoConfigurationPackage.class.getName(), false)); + .fromMap(metadata.getAnnotationAttributes(AutoConfigurationPackage.class.getName(), false)); List packageNames = new ArrayList<>(Arrays.asList(attributes.getStringArray("basePackages"))); for (Class basePackageClass : attributes.getClassArray("basePackageClasses")) { packageNames.add(basePackageClass.getPackage().getName()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java index 6877a54ab9..5229834e72 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -206,7 +206,7 @@ class AutoConfigurationSorter { AutoConfigureOrder.DEFAULT_ORDER); } Map attributes = getAnnotationMetadata() - .getAnnotationAttributes(AutoConfigureOrder.class.getName()); + .getAnnotationAttributes(AutoConfigureOrder.class.getName()); return (attributes != null) ? (Integer) attributes.get("value") : AutoConfigureOrder.DEFAULT_ORDER; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurations.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurations.java index 904d1eb1ee..3796587c63 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurations.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurations.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,9 @@ public class AutoConfigurations extends Configurations implements Ordered { protected Collection> sort(Collection> classes) { List names = classes.stream().map(Class::getName).collect(Collectors.toList()); List sorted = SORTER.getInPriorityOrder(names); - return sorted.stream().map((className) -> ClassUtils.resolveClassName(className, null)) - .collect(Collectors.toCollection(ArrayList::new)); + return sorted.stream() + .map((className) -> ClassUtils.resolveClassName(className, null)) + .collect(Collectors.toCollection(ArrayList::new)); } @Override 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..e862517d35 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -101,8 +101,8 @@ class SharedMetadataReaderFactoryContextInitializer private void register(BeanDefinitionRegistry registry) { if (!registry.containsBeanDefinition(BEAN_NAME)) { BeanDefinition definition = BeanDefinitionBuilder - .rootBeanDefinition(SharedMetadataReaderFactoryBean.class, SharedMetadataReaderFactoryBean::new) - .getBeanDefinition(); + .rootBeanDefinition(SharedMetadataReaderFactoryBean.class, SharedMetadataReaderFactoryBean::new) + .getBeanDefinition(); registry.registerBeanDefinition(BEAN_NAME, definition); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/AbstractConnectionFactoryConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/AbstractConnectionFactoryConfigurer.java index 4d6160f4df..3a25c78554 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/AbstractConnectionFactoryConfigurer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/AbstractConnectionFactoryConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,8 +56,9 @@ public abstract class AbstractConnectionFactoryConfigurer builder = (retryConfig.isStateless()) ? RetryInterceptorBuilder.stateless() : RetryInterceptorBuilder.stateful(); RetryTemplate retryTemplate = new RetryTemplateFactory(this.retryTemplateCustomizers) - .createRetryTemplate(retryConfig, RabbitRetryTemplateCustomizer.Target.LISTENER); + .createRetryTemplate(retryConfig, RabbitRetryTemplateCustomizer.Target.LISTENER); builder.retryOperations(retryTemplate); MessageRecoverer recoverer = (this.messageRecoverer != null) ? this.messageRecoverer : new RejectAndDontRequeueRecoverer(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/CachingConnectionFactoryConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/CachingConnectionFactoryConfigurer.java index 1c8ecdcca7..97ab3d661b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/CachingConnectionFactoryConfigurer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/CachingConnectionFactoryConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,12 +37,15 @@ public class CachingConnectionFactoryConfigurer extends AbstractConnectionFactor public void configure(CachingConnectionFactory connectionFactory, RabbitProperties rabbitProperties) { PropertyMapper map = PropertyMapper.get(); map.from(rabbitProperties::isPublisherReturns).to(connectionFactory::setPublisherReturns); - map.from(rabbitProperties::getPublisherConfirmType).whenNonNull() - .to(connectionFactory::setPublisherConfirmType); + map.from(rabbitProperties::getPublisherConfirmType) + .whenNonNull() + .to(connectionFactory::setPublisherConfirmType); RabbitProperties.Cache.Channel channel = rabbitProperties.getCache().getChannel(); map.from(channel::getSize).whenNonNull().to(connectionFactory::setChannelCacheSize); - map.from(channel::getCheckoutTimeout).whenNonNull().as(Duration::toMillis) - .to(connectionFactory::setChannelCheckoutTimeout); + map.from(channel::getCheckoutTimeout) + .whenNonNull() + .as(Duration::toMillis) + .to(connectionFactory::setChannelCheckoutTimeout); RabbitProperties.Cache.Connection connection = rabbitProperties.getCache().getConnection(); map.from(connection::getMode).whenNonNull().to(connectionFactory::setCacheMode); map.from(connection::getSize).whenNonNull().to(connectionFactory::setConnectionCacheSize); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAnnotationDrivenConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAnnotationDrivenConfiguration.java index 3a2a6bceb7..a34392019a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAnnotationDrivenConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAnnotationDrivenConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,8 +69,8 @@ class RabbitAnnotationDrivenConfiguration { this.properties); configurer.setMessageConverter(this.messageConverter.getIfUnique()); configurer.setMessageRecoverer(this.messageRecoverer.getIfUnique()); - configurer.setRetryTemplateCustomizers( - this.retryTemplateCustomizers.orderedStream().collect(Collectors.toList())); + configurer + .setRetryTemplateCustomizers(this.retryTemplateCustomizers.orderedStream().collect(Collectors.toList())); return configurer; } @@ -94,8 +94,8 @@ class RabbitAnnotationDrivenConfiguration { this.properties); configurer.setMessageConverter(this.messageConverter.getIfUnique()); configurer.setMessageRecoverer(this.messageRecoverer.getIfUnique()); - configurer.setRetryTemplateCustomizers( - this.retryTemplateCustomizers.orderedStream().collect(Collectors.toList())); + configurer + .setRetryTemplateCustomizers(this.retryTemplateCustomizers.orderedStream().collect(Collectors.toList())); return configurer; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.java index eef1a834db..8221516953 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -128,7 +128,7 @@ public class RabbitAutoConfiguration { connectionFactoryBean.afterPropertiesSet(); com.rabbitmq.client.ConnectionFactory connectionFactory = connectionFactoryBean.getObject(); connectionFactoryCustomizers.orderedStream() - .forEach((customizer) -> customizer.customize(connectionFactory)); + .forEach((customizer) -> customizer.customize(connectionFactory)); CachingConnectionFactory factory = new CachingConnectionFactory(connectionFactory); rabbitCachingConnectionFactoryConfigurer.configure(factory); @@ -150,7 +150,7 @@ public class RabbitAutoConfiguration { RabbitTemplateConfigurer configurer = new RabbitTemplateConfigurer(properties); configurer.setMessageConverter(messageConverter.getIfUnique()); configurer - .setRetryTemplateCustomizers(retryTemplateCustomizers.orderedStream().collect(Collectors.toList())); + .setRetryTemplateCustomizers(retryTemplateCustomizers.orderedStream().collect(Collectors.toList())); return configurer; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitConnectionFactoryBeanConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitConnectionFactoryBeanConfigurer.java index ff0728616f..2c2149bc3e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitConnectionFactoryBeanConfigurer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitConnectionFactoryBeanConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,8 +71,10 @@ public class RabbitConnectionFactoryBeanConfigurer { map.from(this.rabbitProperties::determineUsername).whenNonNull().to(factory::setUsername); map.from(this.rabbitProperties::determinePassword).whenNonNull().to(factory::setPassword); map.from(this.rabbitProperties::determineVirtualHost).whenNonNull().to(factory::setVirtualHost); - map.from(this.rabbitProperties::getRequestedHeartbeat).whenNonNull().asInt(Duration::getSeconds) - .to(factory::setRequestedHeartbeat); + map.from(this.rabbitProperties::getRequestedHeartbeat) + .whenNonNull() + .asInt(Duration::getSeconds) + .to(factory::setRequestedHeartbeat); map.from(this.rabbitProperties::getRequestedChannelMax).to(factory::setRequestedChannelMax); RabbitProperties.Ssl ssl = this.rabbitProperties.getSsl(); if (ssl.determineEnabled()) { @@ -87,13 +89,17 @@ public class RabbitConnectionFactoryBeanConfigurer { map.from(ssl::getTrustStorePassword).to(factory::setTrustStorePassphrase); map.from(ssl::getTrustStoreAlgorithm).whenNonNull().to(factory::setTrustStoreAlgorithm); map.from(ssl::isValidateServerCertificate) - .to((validate) -> factory.setSkipServerCertificateValidation(!validate)); + .to((validate) -> factory.setSkipServerCertificateValidation(!validate)); map.from(ssl::getVerifyHostname).to(factory::setEnableHostnameVerification); } - map.from(this.rabbitProperties::getConnectionTimeout).whenNonNull().asInt(Duration::toMillis) - .to(factory::setConnectionTimeout); - map.from(this.rabbitProperties::getChannelRpcTimeout).whenNonNull().asInt(Duration::toMillis) - .to(factory::setChannelRpcTimeout); + map.from(this.rabbitProperties::getConnectionTimeout) + .whenNonNull() + .asInt(Duration::toMillis) + .to(factory::setConnectionTimeout); + map.from(this.rabbitProperties::getChannelRpcTimeout) + .whenNonNull() + .asInt(Duration::toMillis) + .to(factory::setChannelRpcTimeout); map.from(this.credentialsProvider).whenNonNull().to(factory::setCredentialsProvider); map.from(this.credentialsRefreshService).whenNonNull().to(factory::setCredentialsRefreshService); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitTemplateConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitTemplateConfigurer.java index 08d47f5dd1..a4cef4cce4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitTemplateConfigurer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitTemplateConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -109,12 +109,16 @@ public class RabbitTemplateConfigurer { RabbitProperties.Template templateProperties = this.rabbitProperties.getTemplate(); if (templateProperties.getRetry().isEnabled()) { template.setRetryTemplate(new RetryTemplateFactory(this.retryTemplateCustomizers) - .createRetryTemplate(templateProperties.getRetry(), RabbitRetryTemplateCustomizer.Target.SENDER)); + .createRetryTemplate(templateProperties.getRetry(), RabbitRetryTemplateCustomizer.Target.SENDER)); } - map.from(templateProperties::getReceiveTimeout).whenNonNull().as(Duration::toMillis) - .to(template::setReceiveTimeout); - map.from(templateProperties::getReplyTimeout).whenNonNull().as(Duration::toMillis) - .to(template::setReplyTimeout); + map.from(templateProperties::getReceiveTimeout) + .whenNonNull() + .as(Duration::toMillis) + .to(template::setReceiveTimeout); + map.from(templateProperties::getReplyTimeout) + .whenNonNull() + .as(Duration::toMillis) + .to(template::setReplyTimeout); map.from(templateProperties::getExchange).to(template::setExchange); map.from(templateProperties::getRoutingKey).to(template::setRoutingKey); map.from(templateProperties::getDefaultReceiveQueue).whenNonNull().to(template::setDefaultReceiveQueue); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RetryTemplateFactory.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RetryTemplateFactory.java index b063015921..2779f91547 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RetryTemplateFactory.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RetryTemplateFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,8 +45,10 @@ class RetryTemplateFactory { map.from(properties::getMaxAttempts).to(policy::setMaxAttempts); template.setRetryPolicy(policy); ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy(); - map.from(properties::getInitialInterval).whenNonNull().as(Duration::toMillis) - .to(backOffPolicy::setInitialInterval); + map.from(properties::getInitialInterval) + .whenNonNull() + .as(Duration::toMillis) + .to(backOffPolicy::setInitialInterval); map.from(properties::getMultiplier).to(backOffPolicy::setMultiplier); map.from(properties::getMaxInterval).whenNonNull().as(Duration::toMillis).to(backOffPolicy::setMaxInterval); template.setBackOffPolicy(backOffPolicy); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherApplicationRunner.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherApplicationRunner.java index ef18b46b6f..76b3e955d2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherApplicationRunner.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherApplicationRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -210,7 +210,8 @@ public class JobLauncherApplicationRunner implements ApplicationRunner, Ordered, return jobParameters; } JobParameters nextParameters = new JobParametersBuilder(jobParameters, this.jobExplorer) - .getNextJobParameters(job).toJobParameters(); + .getNextJobParameters(job) + .toJobParameters(); return merge(nextParameters, jobParameters); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizers.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizers.java index c50f4fea13..7dd7bc930b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizers.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizers.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,8 @@ public class CacheManagerCustomizers { @SuppressWarnings("unchecked") public T customize(T cacheManager) { LambdaSafe.callbacks(CacheManagerCustomizer.class, this.customizers, cacheManager) - .withLogger(CacheManagerCustomizers.class).invoke((customizer) -> customizer.customize(cacheManager)); + .withLogger(CacheManagerCustomizers.class) + .invoke((customizer) -> customizer.customize(cacheManager)); return cacheManager; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CouchbaseCacheConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CouchbaseCacheConfiguration.java index a4ba5952d7..c4b4930f29 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CouchbaseCacheConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CouchbaseCacheConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,7 +55,7 @@ class CouchbaseCacheConfiguration { CouchbaseCacheManagerBuilder builder = CouchbaseCacheManager.builder(clientFactory); Couchbase couchbase = cacheProperties.getCouchbase(); org.springframework.data.couchbase.cache.CouchbaseCacheConfiguration config = org.springframework.data.couchbase.cache.CouchbaseCacheConfiguration - .defaultCacheConfig(); + .defaultCacheConfig(); if (couchbase.getExpiration() != null) { config = config.entryExpiry(couchbase.getExpiration()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.java index c5e13aa513..07d9d3c402 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -114,7 +114,7 @@ class JCacheCacheConfiguration implements BeanClassLoaderAware { ObjectProvider cachePropertiesCustomizers, CacheProperties cacheProperties) { Properties properties = new Properties(); cachePropertiesCustomizers.orderedStream() - .forEach((customizer) -> customizer.customize(cacheProperties, properties)); + .forEach((customizer) -> customizer.customize(cacheProperties, properties)); return properties; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/RedisCacheConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/RedisCacheConfiguration.java index 5e14f7daa1..ebd8ca33cf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/RedisCacheConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/RedisCacheConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,8 +57,9 @@ class RedisCacheConfiguration { ObjectProvider redisCacheConfiguration, ObjectProvider redisCacheManagerBuilderCustomizers, RedisConnectionFactory redisConnectionFactory, ResourceLoader resourceLoader) { - RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory).cacheDefaults( - determineConfiguration(cacheProperties, redisCacheConfiguration, resourceLoader.getClassLoader())); + RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory) + .cacheDefaults( + determineConfiguration(cacheProperties, redisCacheConfiguration, resourceLoader.getClassLoader())); List cacheNames = cacheProperties.getCacheNames(); if (!cacheNames.isEmpty()) { builder.initialCacheNames(new LinkedHashSet<>(cacheNames)); @@ -81,9 +82,9 @@ class RedisCacheConfiguration { CacheProperties cacheProperties, ClassLoader classLoader) { Redis redisProperties = cacheProperties.getRedis(); org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration - .defaultCacheConfig(); - config = config.serializeValuesWith( - SerializationPair.fromSerializer(new JdkSerializationRedisSerializer(classLoader))); + .defaultCacheConfig(); + config = config + .serializeValuesWith(SerializationPair.fromSerializer(new JdkSerializationRedisSerializer(classLoader))); if (redisProperties.getTimeToLive() != null) { config = config.entryTtl(redisProperties.getTimeToLive()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.java index 15f6153294..580ce8a5e3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -152,78 +152,91 @@ public class CassandraAutoConfiguration { private Config mapConfig(CassandraProperties properties) { CassandraDriverOptions options = new CassandraDriverOptions(); PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); - map.from(properties.getSessionName()).whenHasText() - .to((sessionName) -> options.add(DefaultDriverOption.SESSION_NAME, sessionName)); + map.from(properties.getSessionName()) + .whenHasText() + .to((sessionName) -> options.add(DefaultDriverOption.SESSION_NAME, sessionName)); map.from(properties::getUsername) - .to((username) -> options.add(DefaultDriverOption.AUTH_PROVIDER_USER_NAME, username) - .add(DefaultDriverOption.AUTH_PROVIDER_PASSWORD, properties.getPassword())); + .to((username) -> options.add(DefaultDriverOption.AUTH_PROVIDER_USER_NAME, username) + .add(DefaultDriverOption.AUTH_PROVIDER_PASSWORD, properties.getPassword())); map.from(properties::getCompression) - .to((compression) -> options.add(DefaultDriverOption.PROTOCOL_COMPRESSION, compression)); + .to((compression) -> options.add(DefaultDriverOption.PROTOCOL_COMPRESSION, compression)); mapConnectionOptions(properties, options); mapPoolingOptions(properties, options); mapRequestOptions(properties, options); mapControlConnectionOptions(properties, options); map.from(mapContactPoints(properties)) - .to((contactPoints) -> options.add(DefaultDriverOption.CONTACT_POINTS, contactPoints)); - map.from(properties.getLocalDatacenter()).whenHasText().to( - (localDatacenter) -> options.add(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER, localDatacenter)); + .to((contactPoints) -> options.add(DefaultDriverOption.CONTACT_POINTS, contactPoints)); + map.from(properties.getLocalDatacenter()) + .whenHasText() + .to((localDatacenter) -> options.add(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER, localDatacenter)); return options.build(); } private void mapConnectionOptions(CassandraProperties properties, CassandraDriverOptions options) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); Connection connectionProperties = properties.getConnection(); - map.from(connectionProperties::getConnectTimeout).asInt(Duration::toMillis) - .to((connectTimeout) -> options.add(DefaultDriverOption.CONNECTION_CONNECT_TIMEOUT, connectTimeout)); - map.from(connectionProperties::getInitQueryTimeout).asInt(Duration::toMillis).to( - (initQueryTimeout) -> options.add(DefaultDriverOption.CONNECTION_INIT_QUERY_TIMEOUT, initQueryTimeout)); + map.from(connectionProperties::getConnectTimeout) + .asInt(Duration::toMillis) + .to((connectTimeout) -> options.add(DefaultDriverOption.CONNECTION_CONNECT_TIMEOUT, connectTimeout)); + map.from(connectionProperties::getInitQueryTimeout) + .asInt(Duration::toMillis) + .to((initQueryTimeout) -> options.add(DefaultDriverOption.CONNECTION_INIT_QUERY_TIMEOUT, initQueryTimeout)); } private void mapPoolingOptions(CassandraProperties properties, CassandraDriverOptions options) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); CassandraProperties.Pool poolProperties = properties.getPool(); - map.from(poolProperties::getIdleTimeout).asInt(Duration::toMillis) - .to((idleTimeout) -> options.add(DefaultDriverOption.HEARTBEAT_TIMEOUT, idleTimeout)); - map.from(poolProperties::getHeartbeatInterval).asInt(Duration::toMillis) - .to((heartBeatInterval) -> options.add(DefaultDriverOption.HEARTBEAT_INTERVAL, heartBeatInterval)); + map.from(poolProperties::getIdleTimeout) + .asInt(Duration::toMillis) + .to((idleTimeout) -> options.add(DefaultDriverOption.HEARTBEAT_TIMEOUT, idleTimeout)); + map.from(poolProperties::getHeartbeatInterval) + .asInt(Duration::toMillis) + .to((heartBeatInterval) -> options.add(DefaultDriverOption.HEARTBEAT_INTERVAL, heartBeatInterval)); } private void mapRequestOptions(CassandraProperties properties, CassandraDriverOptions options) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); Request requestProperties = properties.getRequest(); - map.from(requestProperties::getTimeout).asInt(Duration::toMillis) - .to(((timeout) -> options.add(DefaultDriverOption.REQUEST_TIMEOUT, timeout))); + map.from(requestProperties::getTimeout) + .asInt(Duration::toMillis) + .to(((timeout) -> options.add(DefaultDriverOption.REQUEST_TIMEOUT, timeout))); map.from(requestProperties::getConsistency) - .to(((consistency) -> options.add(DefaultDriverOption.REQUEST_CONSISTENCY, consistency))); - map.from(requestProperties::getSerialConsistency).to( - (serialConsistency) -> options.add(DefaultDriverOption.REQUEST_SERIAL_CONSISTENCY, serialConsistency)); + .to(((consistency) -> options.add(DefaultDriverOption.REQUEST_CONSISTENCY, consistency))); + map.from(requestProperties::getSerialConsistency) + .to((serialConsistency) -> options.add(DefaultDriverOption.REQUEST_SERIAL_CONSISTENCY, serialConsistency)); map.from(requestProperties::getPageSize) - .to((pageSize) -> options.add(DefaultDriverOption.REQUEST_PAGE_SIZE, pageSize)); + .to((pageSize) -> options.add(DefaultDriverOption.REQUEST_PAGE_SIZE, pageSize)); Throttler throttlerProperties = requestProperties.getThrottler(); - map.from(throttlerProperties::getType).as(ThrottlerType::type) - .to((type) -> options.add(DefaultDriverOption.REQUEST_THROTTLER_CLASS, type)); + map.from(throttlerProperties::getType) + .as(ThrottlerType::type) + .to((type) -> options.add(DefaultDriverOption.REQUEST_THROTTLER_CLASS, type)); map.from(throttlerProperties::getMaxQueueSize) - .to((maxQueueSize) -> options.add(DefaultDriverOption.REQUEST_THROTTLER_MAX_QUEUE_SIZE, maxQueueSize)); - map.from(throttlerProperties::getMaxConcurrentRequests).to((maxConcurrentRequests) -> options - .add(DefaultDriverOption.REQUEST_THROTTLER_MAX_CONCURRENT_REQUESTS, maxConcurrentRequests)); - map.from(throttlerProperties::getMaxRequestsPerSecond).to((maxRequestsPerSecond) -> options - .add(DefaultDriverOption.REQUEST_THROTTLER_MAX_REQUESTS_PER_SECOND, maxRequestsPerSecond)); - map.from(throttlerProperties::getDrainInterval).asInt(Duration::toMillis).to( - (drainInterval) -> options.add(DefaultDriverOption.REQUEST_THROTTLER_DRAIN_INTERVAL, drainInterval)); + .to((maxQueueSize) -> options.add(DefaultDriverOption.REQUEST_THROTTLER_MAX_QUEUE_SIZE, maxQueueSize)); + map.from(throttlerProperties::getMaxConcurrentRequests) + .to((maxConcurrentRequests) -> options.add(DefaultDriverOption.REQUEST_THROTTLER_MAX_CONCURRENT_REQUESTS, + maxConcurrentRequests)); + map.from(throttlerProperties::getMaxRequestsPerSecond) + .to((maxRequestsPerSecond) -> options.add(DefaultDriverOption.REQUEST_THROTTLER_MAX_REQUESTS_PER_SECOND, + maxRequestsPerSecond)); + map.from(throttlerProperties::getDrainInterval) + .asInt(Duration::toMillis) + .to((drainInterval) -> options.add(DefaultDriverOption.REQUEST_THROTTLER_DRAIN_INTERVAL, drainInterval)); } private void mapControlConnectionOptions(CassandraProperties properties, CassandraDriverOptions options) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); Controlconnection controlProperties = properties.getControlconnection(); - map.from(controlProperties::getTimeout).asInt(Duration::toMillis) - .to((timeout) -> options.add(DefaultDriverOption.CONTROL_CONNECTION_TIMEOUT, timeout)); + map.from(controlProperties::getTimeout) + .asInt(Duration::toMillis) + .to((timeout) -> options.add(DefaultDriverOption.CONTROL_CONNECTION_TIMEOUT, timeout)); } private List mapContactPoints(CassandraProperties properties) { if (properties.getContactPoints() != null) { - return properties.getContactPoints().stream() - .map((candidate) -> formatContactPoint(candidate, properties.getPort())) - .collect(Collectors.toList()); + return properties.getContactPoints() + .stream() + .map((candidate) -> formatContactPoint(candidate, properties.getPort())) + .collect(Collectors.toList()); } return null; } 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..73f57bb035 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -166,7 +166,7 @@ public abstract class AbstractNestedCondition extends SpringBootCondition implem List getMatchOutcomes() { List outcomes = new ArrayList<>(); this.memberConditions.forEach((metadata, conditions) -> outcomes - .add(new MemberOutcomes(this.context, metadata, conditions).getUltimateOutcome())); + .add(new MemberOutcomes(this.context, metadata, conditions).getUltimateOutcome())); return Collections.unmodifiableList(outcomes); } @@ -198,7 +198,7 @@ public abstract class AbstractNestedCondition extends SpringBootCondition implem ConditionOutcome getUltimateOutcome() { ConditionMessage.Builder message = ConditionMessage - .forCondition("NestedCondition on " + ClassUtils.getShortName(this.metadata.getClassName())); + .forCondition("NestedCondition on " + ClassUtils.getShortName(this.metadata.getClassName())); if (this.outcomes.size() == 1) { ConditionOutcome outcome = this.outcomes.get(0); return new ConditionOutcome(outcome.isMatch(), message.because(outcome.getMessage())); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AllNestedConditions.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AllNestedConditions.java index 58ae16d276..93e88c306e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AllNestedConditions.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AllNestedConditions.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,8 +62,9 @@ public abstract class AllNestedConditions extends AbstractNestedCondition { protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) { boolean match = hasSameSize(memberOutcomes.getMatches(), memberOutcomes.getAll()); List messages = new ArrayList<>(); - messages.add(ConditionMessage.forCondition("AllNestedConditions").because( - memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + " did not")); + messages.add(ConditionMessage.forCondition("AllNestedConditions") + .because(memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + + " did not")); for (ConditionOutcome outcome : memberOutcomes.getAll()) { messages.add(outcome.getConditionMessage()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AnyNestedCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AnyNestedCondition.java index ede56389ad..1c37ed0236 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AnyNestedCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AnyNestedCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,8 +65,9 @@ public abstract class AnyNestedCondition extends AbstractNestedCondition { protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) { boolean match = !memberOutcomes.getMatches().isEmpty(); List messages = new ArrayList<>(); - messages.add(ConditionMessage.forCondition("AnyNestedCondition").because( - memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + " did not")); + messages.add(ConditionMessage.forCondition("AnyNestedCondition") + .because(memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + + " did not")); for (ConditionOutcome outcome : memberOutcomes.getAll()) { messages.add(outcome.getConditionMessage()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReport.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReport.java index a7b1410dce..4a945908f2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReport.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReport.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -127,7 +127,7 @@ public final class ConditionEvaluationReport { this.outcomes.forEach((candidateSource, sourceOutcomes) -> { if (candidateSource.startsWith(prefix)) { ConditionOutcome outcome = ConditionOutcome - .noMatch(ConditionMessage.forCondition("Ancestor " + source).because("did not match")); + .noMatch(ConditionMessage.forCondition("Ancestor " + source).because("did not match")); sourceOutcomes.add(ANCESTOR_CONDITION, outcome); } }); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditions.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditions.java index 43997cddb3..c0e89e3316 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditions.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditions.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,8 +62,9 @@ public abstract class NoneNestedConditions extends AbstractNestedCondition { protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) { boolean match = memberOutcomes.getMatches().isEmpty(); List messages = new ArrayList<>(); - messages.add(ConditionMessage.forCondition("NoneNestedConditions").because( - memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + " did not")); + messages.add(ConditionMessage.forCondition("NoneNestedConditions") + .because(memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + + " did not")); for (ConditionOutcome outcome : memberOutcomes.getAll()) { messages.add(outcome.getConditionMessage()); } 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..edefe23f96 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -104,7 +104,8 @@ class OnBeanCondition extends FilteringSpringBootCondition implements Configurat List missing = filter(requiredBeanTypes, ClassNameFilter.MISSING, getBeanClassLoader()); if (!missing.isEmpty()) { ConditionMessage message = ConditionMessage.forCondition(annotation) - .didNotFind("required type", "required types").items(Style.QUOTE, missing); + .didNotFind("required type", "required types") + .items(Style.QUOTE, missing); return ConditionOutcome.noMatch(message); } return null; @@ -121,8 +122,9 @@ class OnBeanCondition extends FilteringSpringBootCondition implements Configurat String reason = createOnBeanNoMatchReason(matchResult); return ConditionOutcome.noMatch(spec.message().because(reason)); } - matchMessage = spec.message(matchMessage).found("bean", "beans").items(Style.QUOTE, - matchResult.getNamesOfAllMatches()); + matchMessage = spec.message(matchMessage) + .found("bean", "beans") + .items(Style.QUOTE, matchResult.getNamesOfAllMatches()); } if (metadata.isAnnotated(ConditionalOnSingleCandidate.class.getName())) { Spec spec = new SingleCandidateSpec(context, metadata, annotations); @@ -138,16 +140,16 @@ class OnBeanCondition extends FilteringSpringBootCondition implements Configurat List primaryBeans = getPrimaryBeans(context.getBeanFactory(), allBeans, spec.getStrategy() == SearchStrategy.ALL); if (primaryBeans.isEmpty()) { - return ConditionOutcome.noMatch( - spec.message().didNotFind("a primary bean from beans").items(Style.QUOTE, allBeans)); + return ConditionOutcome + .noMatch(spec.message().didNotFind("a primary bean from beans").items(Style.QUOTE, allBeans)); } if (primaryBeans.size() > 1) { return ConditionOutcome - .noMatch(spec.message().found("multiple primary beans").items(Style.QUOTE, primaryBeans)); + .noMatch(spec.message().found("multiple primary beans").items(Style.QUOTE, primaryBeans)); } matchMessage = spec.message(matchMessage) - .found("a single primary bean '" + primaryBeans.get(0) + "' from beans") - .items(Style.QUOTE, allBeans); + .found("a single primary bean '" + primaryBeans.get(0) + "' from beans") + .items(Style.QUOTE, allBeans); } } if (metadata.isAnnotated(ConditionalOnMissingBean.class.getName())) { @@ -419,8 +421,8 @@ class OnBeanCondition extends FilteringSpringBootCondition implements Configurat Spec(ConditionContext context, AnnotatedTypeMetadata metadata, MergedAnnotations annotations, Class annotationType) { MultiValueMap attributes = annotations.stream(annotationType) - .filter(MergedAnnotationPredicates.unique(MergedAnnotation::getMetaTypes)) - .collect(MergedAnnotationCollectors.toMultiValueMap(Adapt.CLASS_TO_STRING)); + .filter(MergedAnnotationPredicates.unique(MergedAnnotation::getMetaTypes)) + .collect(MergedAnnotationCollectors.toMultiValueMap(Adapt.CLASS_TO_STRING)); MergedAnnotation annotation = annotations.get(annotationType); this.classLoader = context.getClassLoader(); this.annotationType = annotationType; @@ -568,7 +570,7 @@ class OnBeanCondition extends FilteringSpringBootCondition implements Configurat private boolean isBeanMethod(Method method) { return method != null && MergedAnnotations.from(method, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY) - .isPresent(Bean.class); + .isPresent(Bean.class); } private SearchStrategy getStrategy() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java index d36ef76a0b..0a46416749 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -95,22 +95,24 @@ class OnClassCondition extends FilteringSpringBootCondition { List missing = filter(onClasses, ClassNameFilter.MISSING, classLoader); if (!missing.isEmpty()) { return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnClass.class) - .didNotFind("required class", "required classes").items(Style.QUOTE, missing)); + .didNotFind("required class", "required classes") + .items(Style.QUOTE, missing)); } matchMessage = matchMessage.andCondition(ConditionalOnClass.class) - .found("required class", "required classes") - .items(Style.QUOTE, filter(onClasses, ClassNameFilter.PRESENT, classLoader)); + .found("required class", "required classes") + .items(Style.QUOTE, filter(onClasses, ClassNameFilter.PRESENT, classLoader)); } List onMissingClasses = getCandidates(metadata, ConditionalOnMissingClass.class); if (onMissingClasses != null) { List present = filter(onMissingClasses, ClassNameFilter.PRESENT, classLoader); if (!present.isEmpty()) { return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnMissingClass.class) - .found("unwanted class", "unwanted classes").items(Style.QUOTE, present)); + .found("unwanted class", "unwanted classes") + .items(Style.QUOTE, present)); } matchMessage = matchMessage.andCondition(ConditionalOnMissingClass.class) - .didNotFind("unwanted class", "unwanted classes") - .items(Style.QUOTE, filter(onMissingClasses, ClassNameFilter.MISSING, classLoader)); + .didNotFind("unwanted class", "unwanted classes") + .items(Style.QUOTE, filter(onMissingClasses, ClassNameFilter.MISSING, classLoader)); } return ConditionOutcome.match(matchMessage); } @@ -226,7 +228,8 @@ class OnClassCondition extends FilteringSpringBootCondition { private ConditionOutcome getOutcome(String className, ClassLoader classLoader) { if (ClassNameFilter.MISSING.matches(className, classLoader)) { return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnClass.class) - .didNotFind("required class").items(Style.QUOTE, className)); + .didNotFind("required class") + .items(Style.QUOTE, className)); } return null; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnExpressionCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnExpressionCondition.java index 703eca8244..860db28957 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnExpressionCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnExpressionCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,7 +38,7 @@ class OnExpressionCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { String expression = (String) metadata.getAnnotationAttributes(ConditionalOnExpression.class.getName()) - .get("value"); + .get("value"); expression = wrapIfNecessary(expression); ConditionMessage.Builder messageBuilder = ConditionMessage.forCondition(ConditionalOnExpression.class, "(" + expression + ")"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJavaCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJavaCondition.java index 4b5b33a435..de58f03fd1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJavaCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJavaCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ class OnJavaCondition extends SpringBootCondition { boolean match = isWithin(runningVersion, range, version); String expected = String.format((range != Range.EQUAL_OR_NEWER) ? "(older than %s)" : "(%s or newer)", version); ConditionMessage message = ConditionMessage.forCondition(ConditionalOnJava.class, expected) - .foundExactly(runningVersion); + .foundExactly(runningVersion); return new ConditionOutcome(match, message); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJndiCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJndiCondition.java index 61c5ec3389..600672da2c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJndiCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJndiCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,35 +40,36 @@ class OnJndiCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { AnnotationAttributes annotationAttributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(ConditionalOnJndi.class.getName())); + .fromMap(metadata.getAnnotationAttributes(ConditionalOnJndi.class.getName())); String[] locations = annotationAttributes.getStringArray("value"); try { return getMatchOutcome(locations); } catch (NoClassDefFoundError ex) { return ConditionOutcome - .noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class).because("JNDI class not found")); + .noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class).because("JNDI class not found")); } } private ConditionOutcome getMatchOutcome(String[] locations) { if (!isJndiAvailable()) { return ConditionOutcome - .noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class).notAvailable("JNDI environment")); + .noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class).notAvailable("JNDI environment")); } if (locations.length == 0) { return ConditionOutcome - .match(ConditionMessage.forCondition(ConditionalOnJndi.class).available("JNDI environment")); + .match(ConditionMessage.forCondition(ConditionalOnJndi.class).available("JNDI environment")); } JndiLocator locator = getJndiLocator(locations); String location = locator.lookupFirstLocation(); String details = "(" + StringUtils.arrayToCommaDelimitedString(locations) + ")"; if (location != null) { return ConditionOutcome.match(ConditionMessage.forCondition(ConditionalOnJndi.class, details) - .foundExactly("\"" + location + "\"")); + .foundExactly("\"" + location + "\"")); } return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class, details) - .didNotFind("any matching JNDI location").atAll()); + .didNotFind("any matching JNDI location") + .atAll()); } protected boolean isJndiAvailable() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyCondition.java index aa708df0dd..f3fa94a6a4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,9 +49,10 @@ class OnPropertyCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { List allAnnotationAttributes = metadata.getAnnotations() - .stream(ConditionalOnProperty.class.getName()) - .filter(MergedAnnotationPredicates.unique(MergedAnnotation::getMetaTypes)) - .map(MergedAnnotation::asAnnotationAttributes).collect(Collectors.toList()); + .stream(ConditionalOnProperty.class.getName()) + .filter(MergedAnnotationPredicates.unique(MergedAnnotation::getMetaTypes)) + .map(MergedAnnotation::asAnnotationAttributes) + .collect(Collectors.toList()); List noMatch = new ArrayList<>(); List match = new ArrayList<>(); for (AnnotationAttributes annotationAttributes : allAnnotationAttributes) { @@ -71,15 +72,16 @@ class OnPropertyCondition extends SpringBootCondition { spec.collectProperties(resolver, missingProperties, nonMatchingProperties); if (!missingProperties.isEmpty()) { return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnProperty.class, spec) - .didNotFind("property", "properties").items(Style.QUOTE, missingProperties)); + .didNotFind("property", "properties") + .items(Style.QUOTE, missingProperties)); } if (!nonMatchingProperties.isEmpty()) { return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnProperty.class, spec) - .found("different value in property", "different value in properties") - .items(Style.QUOTE, nonMatchingProperties)); + .found("different value in property", "different value in properties") + .items(Style.QUOTE, nonMatchingProperties)); } return ConditionOutcome - .match(ConditionMessage.forCondition(ConditionalOnProperty.class, spec).because("matched")); + .match(ConditionMessage.forCondition(ConditionalOnProperty.class, spec).because("matched")); } private static class Spec { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnResourceCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnResourceCondition.java index 2d79a87c77..16faa3ecb0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnResourceCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnResourceCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ class OnResourceCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { MultiValueMap attributes = metadata - .getAllAnnotationAttributes(ConditionalOnResource.class.getName(), true); + .getAllAnnotationAttributes(ConditionalOnResource.class.getName(), true); ResourceLoader loader = context.getResourceLoader(); List locations = new ArrayList<>(); collectValues(locations, attributes.get("resources")); @@ -56,10 +56,12 @@ class OnResourceCondition extends SpringBootCondition { } if (!missing.isEmpty()) { return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnResource.class) - .didNotFind("resource", "resources").items(Style.QUOTE, missing)); + .didNotFind("resource", "resources") + .items(Style.QUOTE, missing)); } return ConditionOutcome.match(ConditionMessage.forCondition(ConditionalOnResource.class) - .found("location", "locations").items(locations)); + .found("location", "locations") + .items(locations)); } private void collectValues(List names, List values) { 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 faa9949a1f..529912ef73 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-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ class OnWarDeploymentCondition extends SpringBootCondition { } } return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnWarDeployment.class) - .because("the application is not deployed as a WAR file.")); + .because("the application is not deployed as a WAR file.")); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ResourceCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ResourceCondition.java index acb578357d..a4461fee80 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ResourceCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ResourceCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -80,8 +80,8 @@ public abstract class ResourceCondition extends SpringBootCondition { } } if (found.isEmpty()) { - ConditionMessage message = startConditionMessage().didNotFind("resource", "resources").items(Style.QUOTE, - Arrays.asList(this.resourceLocations)); + ConditionMessage message = startConditionMessage().didNotFind("resource", "resources") + .items(Style.QUOTE, Arrays.asList(this.resourceLocations)); return ConditionOutcome.noMatch(message); } ConditionMessage message = startConditionMessage().found("resource", "resources").items(Style.QUOTE, found); 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..a92df838b9 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -103,8 +103,8 @@ public abstract class SpringBootCondition implements Condition { private void recordEvaluation(ConditionContext context, String classOrMethodName, ConditionOutcome outcome) { if (context.getBeanFactory() != null) { - ConditionEvaluationReport.get(context.getBeanFactory()).recordConditionEvaluation(classOrMethodName, this, - outcome); + ConditionEvaluationReport.get(context.getBeanFactory()) + .recordConditionEvaluation(classOrMethodName, this, outcome); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java index c4c76c0692..edbfb6ba36 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,7 +70,7 @@ public class MessageSourceAutoConfiguration { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); if (StringUtils.hasText(properties.getBasename())) { messageSource.setBasenames(StringUtils - .commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename()))); + .commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename()))); } if (properties.getEncoding() != null) { messageSource.setDefaultEncoding(properties.getEncoding().name()); @@ -116,7 +116,7 @@ public class MessageSourceAutoConfiguration { String target = name.replace('.', '/'); try { return new PathMatchingResourcePatternResolver(classLoader) - .getResources("classpath*:" + target + ".properties"); + .getResources("classpath*:" + target + ".properties"); } catch (Exception ex) { return NO_RESOURCES; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.java index 64b2c57714..81d90d0933 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,24 +76,29 @@ public class CouchbaseAutoConfiguration { @ConditionalOnMissingBean public Cluster couchbaseCluster(CouchbaseProperties properties, ClusterEnvironment couchbaseClusterEnvironment) { ClusterOptions options = ClusterOptions.clusterOptions(properties.getUsername(), properties.getPassword()) - .environment(couchbaseClusterEnvironment); + .environment(couchbaseClusterEnvironment); return Cluster.connect(properties.getConnectionString(), options); } private ClusterEnvironment.Builder initializeEnvironmentBuilder(CouchbaseProperties properties) { ClusterEnvironment.Builder builder = ClusterEnvironment.builder(); Timeouts timeouts = properties.getEnv().getTimeouts(); - builder.timeoutConfig(TimeoutConfig.kvTimeout(timeouts.getKeyValue()).analyticsTimeout(timeouts.getAnalytics()) - .kvDurableTimeout(timeouts.getKeyValueDurable()).queryTimeout(timeouts.getQuery()) - .viewTimeout(timeouts.getView()).searchTimeout(timeouts.getSearch()) - .managementTimeout(timeouts.getManagement()).connectTimeout(timeouts.getConnect()) - .disconnectTimeout(timeouts.getDisconnect())); + builder.timeoutConfig(TimeoutConfig.kvTimeout(timeouts.getKeyValue()) + .analyticsTimeout(timeouts.getAnalytics()) + .kvDurableTimeout(timeouts.getKeyValueDurable()) + .queryTimeout(timeouts.getQuery()) + .viewTimeout(timeouts.getView()) + .searchTimeout(timeouts.getSearch()) + .managementTimeout(timeouts.getManagement()) + .connectTimeout(timeouts.getConnect()) + .disconnectTimeout(timeouts.getDisconnect())); CouchbaseProperties.Io io = properties.getEnv().getIo(); - builder.ioConfig(IoConfig.maxHttpConnections(io.getMaxEndpoints()).numKvConnections(io.getMinEndpoints()) - .idleHttpConnectionTimeout(io.getIdleHttpConnectionTimeout())); + builder.ioConfig(IoConfig.maxHttpConnections(io.getMaxEndpoints()) + .numKvConnections(io.getMinEndpoints()) + .idleHttpConnectionTimeout(io.getIdleHttpConnectionTimeout())); if (properties.getEnv().getSsl().getEnabled()) { builder.securityConfig(SecurityConfig.enableTls(true) - .trustManagerFactory(getTrustManagerFactory(properties.getEnv().getSsl()))); + .trustManagerFactory(getTrustManagerFactory(properties.getEnv().getSsl()))); } return builder; } @@ -102,7 +107,7 @@ public class CouchbaseAutoConfiguration { String resource = ssl.getKeyStore(); try { TrustManagerFactory trustManagerFactory = TrustManagerFactory - .getInstance(KeyManagerFactory.getDefaultAlgorithm()); + .getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = loadKeyStore(resource, ssl.getKeyStorePassword()); trustManagerFactory.init(keyStore); return trustManagerFactory; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/OnRepositoryTypeCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/OnRepositoryTypeCondition.java index 4900574a29..7f988f52af 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/OnRepositoryTypeCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/OnRepositoryTypeCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ class OnRepositoryTypeCondition extends SpringBootCondition { ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnRepositoryType.class); if (configuredType == requiredType || configuredType == RepositoryType.AUTO) { return ConditionOutcome - .match(message.because("configured type of '" + configuredType.name() + "' matched required type")); + .match(message.because("configured type of '" + configuredType.name() + "' matched required type")); } return ConditionOutcome.noMatch(message.because("configured type (" + configuredType.name() + ") did not match required type (" + requiredType.name() + ")")); @@ -51,8 +51,8 @@ class OnRepositoryTypeCondition extends SpringBootCondition { private RepositoryType getTypeProperty(Environment environment, String store) { return RepositoryType - .valueOf(environment.getProperty(String.format("spring.data.%s.repositories.type", store), "auto") - .toUpperCase(Locale.ENGLISH)); + .valueOf(environment.getProperty(String.format("spring.data.%s.repositories.type", store), "auto") + .toUpperCase(Locale.ENGLISH)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataConfiguration.java index 52b7220bcf..20826c607b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,7 +68,7 @@ class CouchbaseDataConfiguration { Class fieldNamingStrategy = properties.getFieldNamingStrategy(); if (fieldNamingStrategy != null) { mappingContext - .setFieldNamingStrategy((FieldNamingStrategy) BeanUtils.instantiateClass(fieldNamingStrategy)); + .setFieldNamingStrategy((FieldNamingStrategy) BeanUtils.instantiateClass(fieldNamingStrategy)); } mappingContext.setAutoIndexCreation(properties.isAutoIndex()); return mappingContext; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRestClientAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRestClientAutoConfiguration.java index a0ec6b74cb..9ccff1a085 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRestClientAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRestClientAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,11 +68,11 @@ public class ReactiveElasticsearchRestClientAutoConfiguration { @ConditionalOnMissingBean public ClientConfiguration clientConfiguration() { ClientConfiguration.MaybeSecureClientConfigurationBuilder builder = ClientConfiguration.builder() - .connectedTo(this.properties.getEndpoints().toArray(new String[0])); + .connectedTo(this.properties.getEndpoints().toArray(new String[0])); PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(this.properties.isUseSsl()).whenTrue().toCall(builder::usingSsl); map.from(this.properties.getCredentials()) - .to((credentials) -> builder.withBasicAuth(credentials.getUsername(), credentials.getPassword())); + .to((credentials) -> builder.withBasicAuth(credentials.getUsername(), credentials.getPassword())); map.from(this.properties.getConnectionTimeout()).to(builder::withConnectTimeout); map.from(this.properties.getSocketTimeout()).to(builder::withSocketTimeout); map.from(this.properties.getPathPrefix()).to(builder::withPathPrefix); @@ -85,7 +85,8 @@ public class ReactiveElasticsearchRestClientAutoConfiguration { map.from(this.properties.getMaxInMemorySize()).asInt(DataSize::toBytes).to((maxInMemorySize) -> { builder.withClientConfigurer(WebClientConfigurationCallback.from((webClient) -> { ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() - .codecs((configurer) -> configurer.defaultCodecs().maxInMemorySize(maxInMemorySize)).build(); + .codecs((configurer) -> configurer.defaultCodecs().maxInMemorySize(maxInMemorySize)) + .build(); return webClient.mutate().exchangeStrategies(exchangeStrategies).build(); })); }); @@ -113,8 +114,11 @@ public class ReactiveElasticsearchRestClientAutoConfiguration { this.properties = properties; this.restClientProperties = restClientProperties; this.deprecatedProperties = deprecatedreactiveProperties; - this.uris = properties.getUris().stream().map((s) -> s.startsWith("http") ? s : "http://" + s) - .map(URI::create).collect(Collectors.toList()); + this.uris = properties.getUris() + .stream() + .map((s) -> s.startsWith("http") ? s : "http://" + s) + .map(URI::create) + .collect(Collectors.toList()); } private List getEndpoints() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.java index 9d7f20cb3d..2b116fe579 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -148,7 +148,7 @@ class LettuceConnectionConfiguration extends RedisConnectionConfiguration { ClusterClientOptions.Builder builder = ClusterClientOptions.builder(); Refresh refreshProperties = getProperties().getLettuce().getCluster().getRefresh(); Builder refreshBuilder = ClusterTopologyRefreshOptions.builder() - .dynamicRefreshSources(refreshProperties.isDynamicRefreshSources()); + .dynamicRefreshSources(refreshProperties.isDynamicRefreshSources()); if (refreshProperties.getPeriod() != null) { refreshBuilder.enablePeriodicRefresh(refreshProperties.getPeriod()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfiguration.java index 5046671c00..9f2cb6ee3c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,12 @@ public class RedisReactiveAutoConfiguration { JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer( resourceLoader.getClassLoader()); RedisSerializationContext serializationContext = RedisSerializationContext - .newSerializationContext().key(jdkSerializer).value(jdkSerializer).hashKey(jdkSerializer) - .hashValue(jdkSerializer).build(); + .newSerializationContext() + .key(jdkSerializer) + .value(jdkSerializer) + .hashKey(jdkSerializer) + .hashValue(jdkSerializer) + .build(); return new ReactiveRedisTemplate<>(reactiveRedisConnectionFactory, serializationContext); } 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 12972fbd23..2599f94e56 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -116,7 +116,7 @@ class NoSuchBeanDefinitionFailureAnalyzer extends AbstractInjectionFailureAnalyz Constructor constructor = (Constructor) injectionPoint.getMember(); Class declaringClass = constructor.getDeclaringClass(); MergedAnnotation configurationProperties = MergedAnnotations.from(declaringClass) - .get(ConfigurationProperties.class); + .get(ConfigurationProperties.class); if (configurationProperties.isPresent()) { if (KotlinDetector.isKotlinType(declaringClass) && !KotlinDetector.isKotlinReflectPresent()) { action = String.format( @@ -162,9 +162,9 @@ class NoSuchBeanDefinitionFailureAnalyzer extends AbstractInjectionFailureAnalyz } String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, type); return Arrays.stream(beanNames) - .map((beanName) -> new UserConfigurationResult(getFactoryMethodMetadata(beanName), - this.beanFactory.getBean(beanName).equals(null))) - .collect(Collectors.toList()); + .map((beanName) -> new UserConfigurationResult(getFactoryMethodMetadata(beanName), + this.beanFactory.getBean(beanName).equals(null))) + .collect(Collectors.toList()); } private MethodMetadata getFactoryMethodMetadata(String beanName) { @@ -178,8 +178,8 @@ class NoSuchBeanDefinitionFailureAnalyzer extends AbstractInjectionFailureAnalyz private void collectReportedConditionOutcomes(NoSuchBeanDefinitionException cause, List results) { this.report.getConditionAndOutcomesBySource() - .forEach((source, sourceOutcomes) -> collectReportedConditionOutcomes(cause, new Source(source), - sourceOutcomes, results)); + .forEach((source, sourceOutcomes) -> collectReportedConditionOutcomes(cause, new Source(source), + sourceOutcomes, results)); } private void collectReportedConditionOutcomes(NoSuchBeanDefinitionException cause, Source source, @@ -252,9 +252,9 @@ class NoSuchBeanDefinitionFailureAnalyzer extends AbstractInjectionFailureAnalyz private List findBeanMethods(Source source, NoSuchBeanDefinitionException cause) { try { MetadataReader classMetadata = NoSuchBeanDefinitionFailureAnalyzer.this.metadataReaderFactory - .getMetadataReader(source.getClassName()); + .getMetadataReader(source.getClassName()); Set candidates = classMetadata.getAnnotationMetadata() - .getAnnotatedMethods(Bean.class.getName()); + .getAnnotatedMethods(Bean.class.getName()); List result = new ArrayList<>(); for (MethodMetadata candidate : candidates) { if (isMatch(candidate, source, cause)) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java index e0c27c2cf1..b947aad3bd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -112,7 +112,7 @@ public class EntityScanPackages { Assert.notNull(packageNames, "PackageNames must not be null"); if (registry.containsBeanDefinition(BEAN)) { EntityScanPackagesBeanDefinition beanDefinition = (EntityScanPackagesBeanDefinition) registry - .getBeanDefinition(BEAN); + .getBeanDefinition(BEAN); beanDefinition.addPackageNames(packageNames); } else { @@ -139,7 +139,7 @@ public class EntityScanPackages { private Set getPackagesToScan(AnnotationMetadata metadata) { AnnotationAttributes attributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(EntityScan.class.getName())); + .fromMap(metadata.getAnnotationAttributes(EntityScan.class.getName())); Set packagesToScan = new LinkedHashSet<>(); for (String basePackage : attributes.getStringArray("basePackages")) { String[] tokenized = StringUtils.tokenizeToStringArray( diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientConfigurations.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientConfigurations.java index 8e50a3da5f..297c41f501 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientConfigurations.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientConfigurations.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -103,7 +103,8 @@ class ElasticsearchRestClientConfigurations { } try { return HttpHost.create(new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), - uri.getQuery(), uri.getFragment()).toString()); + uri.getQuery(), uri.getFragment()) + .toString()); } catch (URISyntaxException ex) { throw new IllegalStateException(ex); @@ -197,10 +198,14 @@ class ElasticsearchRestClientConfigurations { @Override public void customize(RequestConfig.Builder builder) { - map.from(this.properties::getConnectionTimeout).whenNonNull().asInt(Duration::toMillis) - .to(builder::setConnectTimeout); - map.from(this.properties::getSocketTimeout).whenNonNull().asInt(Duration::toMillis) - .to(builder::setSocketTimeout); + map.from(this.properties::getConnectionTimeout) + .whenNonNull() + .asInt(Duration::toMillis) + .to(builder::setConnectTimeout); + map.from(this.properties::getSocketTimeout) + .whenNonNull() + .asInt(Duration::toMillis) + .to(builder::setSocketTimeout); } } @@ -213,8 +218,11 @@ class ElasticsearchRestClientConfigurations { properties.getPassword()); setCredentials(AuthScope.ANY, credentials); } - properties.getUris().stream().map(this::toUri).filter(this::hasUserInfo) - .forEach(this::addUserInfoCredentials); + properties.getUris() + .stream() + .map(this::toUri) + .filter(this::hasUserInfo) + .forEach(this::addUserInfoCredentials); } private URI toUri(String uri) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java index aeb09976e5..a5cc7bf2d2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -145,7 +145,7 @@ public class FlywayAutoConfiguration { } if (properties.getUser() != null && dataSource != null) { DataSourceBuilder builder = DataSourceBuilder.derivedFrom(dataSource) - .type(SimpleDriverDataSource.class); + .type(SimpleDriverDataSource.class); applyCommonBuilderProperties(properties, builder); return builder.build(); } @@ -164,17 +164,18 @@ public class FlywayAutoConfiguration { private void configureProperties(FluentConfiguration configuration, FlywayProperties properties) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); String[] locations = new LocationResolver(configuration.getDataSource()) - .resolveLocations(properties.getLocations()).toArray(new String[0]); + .resolveLocations(properties.getLocations()) + .toArray(new String[0]); configureFailOnMissingLocations(configuration, properties.isFailOnMissingLocations()); map.from(locations).to(configuration::locations); map.from(properties.getEncoding()).to(configuration::encoding); map.from(properties.getConnectRetries()).to(configuration::connectRetries); // No method reference for compatibility with Flyway < 7.15 map.from(properties.getConnectRetriesInterval()) - .to((interval) -> configuration.connectRetriesInterval((int) interval.getSeconds())); + .to((interval) -> configuration.connectRetriesInterval((int) interval.getSeconds())); // No method reference for compatibility with Flyway 6.x map.from(properties.getLockRetryCount()) - .to((lockRetryCount) -> configuration.lockRetryCount(lockRetryCount)); + .to((lockRetryCount) -> configuration.lockRetryCount(lockRetryCount)); // No method reference for compatibility with Flyway 5.x map.from(properties.getDefaultSchema()).to((schema) -> configuration.defaultSchema(schema)); map.from(properties.getSchemas()).as(StringUtils::toStringArray).to(configuration::schemas); @@ -190,11 +191,12 @@ public class FlywayAutoConfiguration { map.from(properties.getPlaceholderSuffix()).to(configuration::placeholderSuffix); // No method reference for compatibility with Flyway version < 8.0 map.from(properties.getPlaceholderSeparator()) - .to((placeHolderSeparator) -> configuration.placeholderSeparator(placeHolderSeparator)); + .to((placeHolderSeparator) -> configuration.placeholderSeparator(placeHolderSeparator)); map.from(properties.isPlaceholderReplacement()).to(configuration::placeholderReplacement); map.from(properties.getSqlMigrationPrefix()).to(configuration::sqlMigrationPrefix); - map.from(properties.getSqlMigrationSuffixes()).as(StringUtils::toStringArray) - .to(configuration::sqlMigrationSuffixes); + map.from(properties.getSqlMigrationSuffixes()) + .as(StringUtils::toStringArray) + .to(configuration::sqlMigrationSuffixes); map.from(properties.getSqlMigrationSeparator()).to(configuration::sqlMigrationSeparator); map.from(properties.getRepeatableSqlMigrationPrefix()).to(configuration::repeatableSqlMigrationPrefix); map.from(properties.getTarget()).to(configuration::target); @@ -209,13 +211,14 @@ public class FlywayAutoConfiguration { map.from(properties.isSkipDefaultResolvers()).to(configuration::skipDefaultResolvers); configureValidateMigrationNaming(configuration, properties.isValidateMigrationNaming()); map.from(properties.isValidateOnMigrate()).to(configuration::validateOnMigrate); - map.from(properties.getInitSqls()).whenNot(CollectionUtils::isEmpty) - .as((initSqls) -> StringUtils.collectionToDelimitedString(initSqls, "\n")) - .to(configuration::initSql); + map.from(properties.getInitSqls()) + .whenNot(CollectionUtils::isEmpty) + .as((initSqls) -> StringUtils.collectionToDelimitedString(initSqls, "\n")) + .to(configuration::initSql); map.from(properties.getScriptPlaceholderPrefix()) - .to((prefix) -> configuration.scriptPlaceholderPrefix(prefix)); + .to((prefix) -> configuration.scriptPlaceholderPrefix(prefix)); map.from(properties.getScriptPlaceholderSuffix()) - .to((suffix) -> configuration.scriptPlaceholderSuffix(suffix)); + .to((suffix) -> configuration.scriptPlaceholderSuffix(suffix)); // Pro properties map.from(properties.getBatch()).to(configuration::batch); map.from(properties.getDryRunOutput()).to(configuration::dryRunOutput); @@ -224,38 +227,41 @@ public class FlywayAutoConfiguration { map.from(properties.getOracleSqlplus()).to(configuration::oracleSqlplus); // No method reference for compatibility with Flyway 5.x map.from(properties.getOracleSqlplusWarn()) - .to((oracleSqlplusWarn) -> configuration.oracleSqlplusWarn(oracleSqlplusWarn)); + .to((oracleSqlplusWarn) -> configuration.oracleSqlplusWarn(oracleSqlplusWarn)); map.from(properties.getStream()).to(configuration::stream); map.from(properties.getUndoSqlMigrationPrefix()).to(configuration::undoSqlMigrationPrefix); // No method reference for compatibility with Flyway 6.x map.from(properties.getCherryPick()).to((cherryPick) -> configuration.cherryPick(cherryPick)); // No method reference for compatibility with Flyway 6.x - map.from(properties.getJdbcProperties()).whenNot(Map::isEmpty) - .to((jdbcProperties) -> configuration.jdbcProperties(jdbcProperties)); + map.from(properties.getJdbcProperties()) + .whenNot(Map::isEmpty) + .to((jdbcProperties) -> configuration.jdbcProperties(jdbcProperties)); // No method reference for compatibility with Flyway 6.x map.from(properties.getKerberosConfigFile()) - .to((configFile) -> configuration.kerberosConfigFile(configFile)); + .to((configFile) -> configuration.kerberosConfigFile(configFile)); // No method reference for compatibility with Flyway 6.x map.from(properties.getOracleKerberosCacheFile()) - .to((cacheFile) -> configuration.oracleKerberosCacheFile(cacheFile)); + .to((cacheFile) -> configuration.oracleKerberosCacheFile(cacheFile)); // No method reference for compatibility with Flyway 6.x map.from(properties.getOutputQueryResults()) - .to((outputQueryResults) -> configuration.outputQueryResults(outputQueryResults)); - map.from(properties.getSqlServerKerberosLoginFile()).whenNonNull() - .to(this::configureSqlServerKerberosLoginFile); + .to((outputQueryResults) -> configuration.outputQueryResults(outputQueryResults)); + map.from(properties.getSqlServerKerberosLoginFile()) + .whenNonNull() + .to(this::configureSqlServerKerberosLoginFile); // No method reference for compatibility with Flyway 6.x map.from(properties.getSkipExecutingMigrations()) - .to((skipExecutingMigrations) -> configuration.skipExecutingMigrations(skipExecutingMigrations)); + .to((skipExecutingMigrations) -> configuration.skipExecutingMigrations(skipExecutingMigrations)); // No method reference for compatibility with Flyway < 7.8 - map.from(properties.getIgnoreMigrationPatterns()).whenNot(List::isEmpty) - .to((ignoreMigrationPatterns) -> configuration - .ignoreMigrationPatterns(ignoreMigrationPatterns.toArray(new String[0]))); + map.from(properties.getIgnoreMigrationPatterns()) + .whenNot(List::isEmpty) + .to((ignoreMigrationPatterns) -> configuration + .ignoreMigrationPatterns(ignoreMigrationPatterns.toArray(new String[0]))); // No method reference for compatibility with Flyway version < 7.9 map.from(properties.getDetectEncoding()) - .to((detectEncoding) -> configuration.detectEncoding(detectEncoding)); + .to((detectEncoding) -> configuration.detectEncoding(detectEncoding)); // No method reference for compatibility with Flyway version < 8.0 map.from(properties.getBaselineMigrationPrefix()) - .to((baselineMigrationPrefix) -> configuration.baselineMigrationPrefix(baselineMigrationPrefix)); + .to((baselineMigrationPrefix) -> configuration.baselineMigrationPrefix(baselineMigrationPrefix)); } @SuppressWarnings("deprecation") @@ -293,7 +299,7 @@ public class FlywayAutoConfiguration { private void configureSqlServerKerberosLoginFile(String sqlServerKerberosLoginFile) { SQLServerConfigurationExtension sqlServerConfigurationExtension = PluginRegister - .getPlugin(SQLServerConfigurationExtension.class); + .getPlugin(SQLServerConfigurationExtension.class); sqlServerConfigurationExtension.setKerberosLoginFile(sqlServerKerberosLoginFile); } @@ -362,8 +368,9 @@ public class FlywayAutoConfiguration { return locations; } String vendor = databaseDriver.getId(); - return locations.stream().map((location) -> location.replace(VENDOR_PLACEHOLDER, vendor)) - .collect(Collectors.toList()); + return locations.stream() + .map((location) -> location.replace(VENDOR_PLACEHOLDER, vendor)) + .collect(Collectors.toList()); } private DatabaseDriver getDatabaseDriver() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywaySchemaManagementProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywaySchemaManagementProvider.java index 210bfb3b23..45300bef41 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywaySchemaManagementProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywaySchemaManagementProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,11 @@ class FlywaySchemaManagementProvider implements SchemaManagementProvider { @Override public SchemaManagement getSchemaManagement(DataSource dataSource) { return StreamSupport.stream(this.flywayInstances.spliterator(), false) - .map((flyway) -> flyway.getConfiguration().getDataSource()).filter(dataSource::equals).findFirst() - .map((managedDataSource) -> SchemaManagement.MANAGED).orElse(SchemaManagement.UNMANAGED); + .map((flyway) -> flyway.getConfiguration().getDataSource()) + .filter(dataSource::equals) + .findFirst() + .map((managedDataSource) -> SchemaManagement.MANAGED) + .orElse(SchemaManagement.UNMANAGED); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/DefaultGraphQlSchemaCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/DefaultGraphQlSchemaCondition.java index 53d3f1f0da..77ead8392c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/DefaultGraphQlSchemaCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/DefaultGraphQlSchemaCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,9 +60,9 @@ class DefaultGraphQlSchemaCondition extends SpringBootCondition implements Confi ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnGraphQlSchema.class); Binder binder = Binder.get(context.getEnvironment()); GraphQlProperties.Schema schema = binder.bind("spring.graphql.schema", GraphQlProperties.Schema.class) - .orElse(new GraphQlProperties.Schema()); + .orElse(new GraphQlProperties.Schema()); ResourcePatternResolver resourcePatternResolver = ResourcePatternUtils - .getResourcePatternResolver(context.getResourceLoader()); + .getResourcePatternResolver(context.getResourceLoader()); List schemaResources = resolveSchemaResources(resourcePatternResolver, schema.getLocations(), schema.getFileExtensions()); if (!schemaResources.isEmpty()) { @@ -70,8 +70,8 @@ class DefaultGraphQlSchemaCondition extends SpringBootCondition implements Confi messages.add(message.found("schema", "schemas").items(ConditionMessage.Style.QUOTE, schemaResources)); } else { - messages.add(message.didNotFind("schema files in locations").items(ConditionMessage.Style.QUOTE, - Arrays.asList(schema.getLocations()))); + messages.add(message.didNotFind("schema files in locations") + .items(ConditionMessage.Style.QUOTE, Arrays.asList(schema.getLocations()))); } ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); String[] customizerBeans = beanFactory.getBeanNamesForType(GraphQlSourceBuilderCustomizer.class, false, false); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/GraphQlAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/GraphQlAutoConfiguration.java index bc90f07e5c..7013533bec 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/GraphQlAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/GraphQlAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -84,9 +84,10 @@ public class GraphQlAutoConfiguration { Resource[] schemaResources = resolveSchemaResources(resourcePatternResolver, schemaLocations, properties.getSchema().getFileExtensions()); GraphQlSource.SchemaResourceBuilder builder = GraphQlSource.schemaResourceBuilder() - .schemaResources(schemaResources).exceptionResolvers(toList(exceptionResolvers)) - .subscriptionExceptionResolvers(toList(subscriptionExceptionResolvers)) - .instrumentation(toList(instrumentations)); + .schemaResources(schemaResources) + .exceptionResolvers(toList(exceptionResolvers)) + .subscriptionExceptionResolvers(toList(subscriptionExceptionResolvers)) + .instrumentation(toList(instrumentations)); if (!properties.getSchema().getIntrospection().isEnabled()) { builder.configureRuntimeWiring(this::enableIntrospection); } @@ -140,7 +141,7 @@ public class GraphQlAutoConfiguration { public AnnotatedControllerConfigurer annotatedControllerConfigurer() { AnnotatedControllerConfigurer controllerConfigurer = new AnnotatedControllerConfigurer(); controllerConfigurer - .addFormatterRegistrar((registry) -> ApplicationConversionService.addBeans(registry, this.beanFactory)); + .addFormatterRegistrar((registry) -> ApplicationConversionService.addBeans(registry, this.beanFactory)); return controllerConfigurer; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/GraphQlProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/GraphQlProperties.java index 504ab540b2..1ea766a8be 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/GraphQlProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/GraphQlProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -100,8 +100,9 @@ public class GraphQlProperties { } private String[] appendSlashIfNecessary(String[] locations) { - return Arrays.stream(locations).map((location) -> location.endsWith("/") ? location : location + "/") - .toArray(String[]::new); + return Arrays.stream(locations) + .map((location) -> location.endsWith("/") ? location : location + "/") + .toArray(String[]::new); } public Introspection getIntrospection() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/reactive/GraphQlWebFluxAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/reactive/GraphQlWebFluxAutoConfiguration.java index 70178c8016..327853d706 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/reactive/GraphQlWebFluxAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/reactive/GraphQlWebFluxAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -83,7 +83,8 @@ import static org.springframework.web.reactive.function.server.RequestPredicates public class GraphQlWebFluxAutoConfiguration { private static final RequestPredicate SUPPORTS_MEDIATYPES = accept(MediaType.APPLICATION_GRAPHQL, - MediaType.APPLICATION_JSON).and(contentType(MediaType.APPLICATION_GRAPHQL, MediaType.APPLICATION_JSON)); + MediaType.APPLICATION_JSON) + .and(contentType(MediaType.APPLICATION_GRAPHQL, MediaType.APPLICATION_JSON)); private static final Log logger = LogFactory.getLog(GraphQlWebFluxAutoConfiguration.class); @@ -98,7 +99,8 @@ public class GraphQlWebFluxAutoConfiguration { public WebGraphQlHandler webGraphQlHandler(ExecutionGraphQlService service, ObjectProvider interceptorsProvider) { return WebGraphQlHandler.builder(service) - .interceptors(interceptorsProvider.orderedStream().collect(Collectors.toList())).build(); + .interceptors(interceptorsProvider.orderedStream().collect(Collectors.toList())) + .build(); } @Bean diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/rsocket/GraphQlRSocketAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/rsocket/GraphQlRSocketAutoConfiguration.java index fc44994770..811271ba97 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/rsocket/GraphQlRSocketAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/rsocket/GraphQlRSocketAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,7 +60,7 @@ public class GraphQlRSocketAutoConfiguration { public GraphQlRSocketHandler graphQlRSocketHandler(ExecutionGraphQlService graphQlService, ObjectProvider interceptorsProvider, ObjectMapper objectMapper) { List interceptors = interceptorsProvider.orderedStream() - .collect(Collectors.toList()); + .collect(Collectors.toList()); return new GraphQlRSocketHandler(graphQlService, interceptors, new Jackson2JsonEncoder(objectMapper)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/servlet/GraphQlWebMvcAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/servlet/GraphQlWebMvcAutoConfiguration.java index 15a3d46ac7..55017d34d8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/servlet/GraphQlWebMvcAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/servlet/GraphQlWebMvcAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -102,8 +102,9 @@ public class GraphQlWebMvcAutoConfiguration { ObjectProvider interceptorsProvider, ObjectProvider accessorsProvider) { return WebGraphQlHandler.builder(service) - .interceptors(interceptorsProvider.orderedStream().collect(Collectors.toList())) - .threadLocalAccessors(accessorsProvider.orderedStream().collect(Collectors.toList())).build(); + .interceptors(interceptorsProvider.orderedStream().collect(Collectors.toList())) + .threadLocalAccessors(accessorsProvider.orderedStream().collect(Collectors.toList())) + .build(); } @Bean @@ -115,7 +116,7 @@ public class GraphQlWebMvcAutoConfiguration { RouterFunctions.Builder builder = RouterFunctions.route(); builder = builder.GET(path, this::onlyAllowPost); builder = builder.POST(path, RequestPredicates.contentType(SUPPORTED_MEDIA_TYPES) - .and(RequestPredicates.accept(SUPPORTED_MEDIA_TYPES)), httpHandler::handleRequest); + .and(RequestPredicates.accept(SUPPORTED_MEDIA_TYPES)), httpHandler::handleRequest); if (properties.getGraphiql().isEnabled()) { GraphiQlHandler graphiQLHandler = new GraphiQlHandler(path, properties.getWebsocket().getPath()); builder = builder.GET(properties.getGraphiql().getPath(), graphiQLHandler::handleRequest); @@ -171,9 +172,12 @@ public class GraphQlWebMvcAutoConfiguration { } private GenericHttpMessageConverter getJsonConverter(HttpMessageConverters converters) { - return converters.getConverters().stream().filter(this::canReadJsonMap).findFirst() - .map(this::asGenericHttpMessageConverter) - .orElseThrow(() -> new IllegalStateException("No JSON converter")); + return converters.getConverters() + .stream() + .filter(this::canReadJsonMap) + .findFirst() + .map(this::asGenericHttpMessageConverter) + .orElseThrow(() -> new IllegalStateException("No JSON converter")); } private boolean canReadJsonMap(HttpMessageConverter candidate) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.java index d3c0d8b480..4fd3f99778 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -80,7 +80,7 @@ public class GsonAutoConfiguration { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(properties::getGenerateNonExecutableJson).toCall(builder::generateNonExecutableJson); map.from(properties::getExcludeFieldsWithoutExposeAnnotation) - .toCall(builder::excludeFieldsWithoutExposeAnnotation); + .toCall(builder::excludeFieldsWithoutExposeAnnotation); map.from(properties::getSerializeNulls).whenTrue().toCall(builder::serializeNulls); map.from(properties::getEnableComplexMapKeySerialization).toCall(builder::enableComplexMapKeySerialization); map.from(properties::getDisableInnerClassSerialization).toCall(builder::disableInnerClassSerialization); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastClientConfigAvailableCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastClientConfigAvailableCondition.java index 09d938f728..4c335b637f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastClientConfigAvailableCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastClientConfigAvailableCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,7 @@ class HazelcastClientConfigAvailableCondition extends HazelcastConfigResourceCon ConditionOutcome configValidationOutcome = Hazelcast4ClientValidation.clientConfigOutcome(context, HAZELCAST_CONFIG_PROPERTY, startConditionMessage()); return (configValidationOutcome != null) ? configValidationOutcome : ConditionOutcome - .match(startConditionMessage().foundExactly("property " + HAZELCAST_CONFIG_PROPERTY)); + .match(startConditionMessage().foundExactly("property " + HAZELCAST_CONFIG_PROPERTY)); } return getResourceOutcome(context, metadata); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastConfigResourceCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastConfigResourceCondition.java index 359810d591..af5054c9eb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastConfigResourceCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastConfigResourceCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +48,8 @@ public abstract class HazelcastConfigResourceCondition extends ResourceCondition @Override protected ConditionOutcome getResourceOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { if (System.getProperty(this.configSystemProperty) != null) { - return ConditionOutcome.match( - startConditionMessage().because("System property '" + this.configSystemProperty + "' is set.")); + return ConditionOutcome + .match(startConditionMessage().because("System property '" + this.configSystemProperty + "' is set.")); } return super.getResourceOutcome(context, metadata); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfiguration.java index 901db8ce0b..b8f7038971 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,8 +79,10 @@ public class CodecsAutoConfiguration { PropertyMapper map = PropertyMapper.get(); CodecConfigurer.DefaultCodecs defaultCodecs = configurer.defaultCodecs(); defaultCodecs.enableLoggingRequestDetails(codecProperties.isLogRequestDetails()); - map.from(codecProperties.getMaxInMemorySize()).whenNonNull().asInt(DataSize::toBytes) - .to(defaultCodecs::maxInMemorySize); + map.from(codecProperties.getMaxInMemorySize()) + .whenNonNull() + .asInt(DataSize::toBytes) + .to(defaultCodecs::maxInMemorySize); }; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java index fea498382c..96d2202e7d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -95,18 +95,20 @@ public class IntegrationAutoConfiguration { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(properties.getChannel().isAutoCreate()).to(integrationProperties::setChannelsAutoCreate); map.from(properties.getChannel().getMaxUnicastSubscribers()) - .to(integrationProperties::setChannelsMaxUnicastSubscribers); + .to(integrationProperties::setChannelsMaxUnicastSubscribers); map.from(properties.getChannel().getMaxBroadcastSubscribers()) - .to(integrationProperties::setChannelsMaxBroadcastSubscribers); + .to(integrationProperties::setChannelsMaxBroadcastSubscribers); map.from(properties.getError().isRequireSubscribers()) - .to(integrationProperties::setErrorChannelRequireSubscribers); + .to(integrationProperties::setErrorChannelRequireSubscribers); map.from(properties.getError().isIgnoreFailures()).to(integrationProperties::setErrorChannelIgnoreFailures); map.from(properties.getEndpoint().isThrowExceptionOnLateReply()) - .to(integrationProperties::setMessagingTemplateThrowExceptionOnLateReply); - map.from(properties.getEndpoint().getReadOnlyHeaders()).as(StringUtils::toStringArray) - .to(integrationProperties::setReadOnlyHeaders); - map.from(properties.getEndpoint().getNoAutoStartup()).as(StringUtils::toStringArray) - .to(integrationProperties::setNoAutoStartupEndpoints); + .to(integrationProperties::setMessagingTemplateThrowExceptionOnLateReply); + map.from(properties.getEndpoint().getReadOnlyHeaders()) + .as(StringUtils::toStringArray) + .to(integrationProperties::setReadOnlyHeaders); + map.from(properties.getEndpoint().getNoAutoStartup()) + .as(StringUtils::toStringArray) + .to(integrationProperties::setNoAutoStartupEndpoints); return integrationProperties; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationPropertiesEnvironmentPostProcessor.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationPropertiesEnvironmentPostProcessor.java index 3ed91d7a50..a4e2657270 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationPropertiesEnvironmentPostProcessor.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationPropertiesEnvironmentPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,7 +60,8 @@ class IntegrationPropertiesEnvironmentPostProcessor implements EnvironmentPostPr PropertiesPropertySourceLoader loader = new PropertiesPropertySourceLoader(); try { OriginTrackedMapPropertySource propertyFileSource = (OriginTrackedMapPropertySource) loader - .load("META-INF/spring.integration.properties", resource).get(0); + .load("META-INF/spring.integration.properties", resource) + .get(0); environment.getPropertySources().addLast(new IntegrationPropertiesPropertySource(propertyFileSource)); } catch (IOException ex) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzer.java index 19e6449bf2..4b271537ae 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,14 +66,16 @@ class DataSourceBeanCreationFailureAnalyzer extends AbstractFailureAnalyzer initializeDataSourceBuilder() { - return DataSourceBuilder.create(getClassLoader()).type(getType()).driverClassName(determineDriverClassName()) - .url(determineUrl()).username(determineUsername()).password(determinePassword()); + return DataSourceBuilder.create(getClassLoader()) + .type(getType()) + .driverClassName(determineDriverClassName()) + .url(determineUrl()) + .username(determineUsername()) + .password(determinePassword()); } public boolean isGenerateUniqueName() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfiguration.java index 1229335836..aba988c5d7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,8 @@ public class EmbeddedDataSourceConfiguration implements BeanClassLoaderAware { @Bean(destroyMethod = "shutdown") public EmbeddedDatabase dataSource(DataSourceProperties properties) { return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseConnection.get(this.classLoader).getType()) - .setName(properties.determineDatabaseName()).build(); + .setName(properties.determineDatabaseName()) + .build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration.java index 4c650b4790..9e24fbc817 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -91,12 +91,16 @@ public class JmsAutoConfiguration { map.from(properties::getDefaultDestination).whenNonNull().to(template::setDefaultDestinationName); map.from(properties::getDeliveryDelay).whenNonNull().as(Duration::toMillis).to(template::setDeliveryDelay); map.from(properties::determineQosEnabled).to(template::setExplicitQosEnabled); - map.from(properties::getDeliveryMode).whenNonNull().as(DeliveryMode::getValue) - .to(template::setDeliveryMode); + map.from(properties::getDeliveryMode) + .whenNonNull() + .as(DeliveryMode::getValue) + .to(template::setDeliveryMode); map.from(properties::getPriority).whenNonNull().to(template::setPriority); map.from(properties::getTimeToLive).whenNonNull().as(Duration::toMillis).to(template::setTimeToLive); - map.from(properties::getReceiveTimeout).whenNonNull().as(Duration::toMillis) - .to(template::setReceiveTimeout); + map.from(properties::getReceiveTimeout) + .whenNonNull() + .as(Duration::toMillis) + .to(template::setReceiveTimeout); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsPoolConnectionFactoryFactory.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsPoolConnectionFactoryFactory.java index 27ceec82fc..936c296601 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsPoolConnectionFactoryFactory.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsPoolConnectionFactoryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ public class JmsPoolConnectionFactoryFactory { pooledConnectionFactory.setBlockIfSessionPoolIsFull(this.properties.isBlockIfFull()); if (this.properties.getBlockIfFullTimeout() != null) { pooledConnectionFactory - .setBlockIfSessionPoolIsFullTimeout(this.properties.getBlockIfFullTimeout().toMillis()); + .setBlockIfSessionPoolIsFullTimeout(this.properties.getBlockIfFullTimeout().toMillis()); } if (this.properties.getIdleTimeout() != null) { pooledConnectionFactory.setConnectionIdleTimeout((int) this.properties.getIdleTimeout().toMillis()); @@ -57,7 +57,7 @@ public class JmsPoolConnectionFactoryFactory { pooledConnectionFactory.setMaxSessionsPerConnection(this.properties.getMaxSessionsPerConnection()); if (this.properties.getTimeBetweenExpirationCheck() != null) { pooledConnectionFactory - .setConnectionCheckInterval(this.properties.getTimeBetweenExpirationCheck().toMillis()); + .setConnectionCheckInterval(this.properties.getTimeBetweenExpirationCheck().toMillis()); } pooledConnectionFactory.setUseAnonymousProducers(this.properties.isUseAnonymousProducers()); return pooledConnectionFactory; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryConfiguration.java index e53aa4b65f..f2212fa47a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,7 +63,7 @@ class ActiveMQConnectionFactoryConfiguration { ObjectProvider factoryCustomizers) { return new ActiveMQConnectionFactoryFactory(properties, factoryCustomizers.orderedStream().collect(Collectors.toList())) - .createConnectionFactory(ActiveMQConnectionFactory.class); + .createConnectionFactory(ActiveMQConnectionFactory.class); } @Configuration(proxyBeanMethods = false) @@ -98,9 +98,9 @@ class ActiveMQConnectionFactoryConfiguration { ObjectProvider factoryCustomizers) { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactoryFactory(properties, factoryCustomizers.orderedStream().collect(Collectors.toList())) - .createConnectionFactory(ActiveMQConnectionFactory.class); + .createConnectionFactory(ActiveMQConnectionFactory.class); return new JmsPoolConnectionFactoryFactory(properties.getPool()) - .createPooledConnectionFactory(connectionFactory); + .createPooledConnectionFactory(connectionFactory); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryFactory.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryFactory.java index 39c88a7337..1830c4873f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryFactory.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQConnectionFactoryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,8 +85,8 @@ class ActiveMQConnectionFactoryFactory { String user = this.properties.getUser(); String password = this.properties.getPassword(); if (StringUtils.hasLength(user) && StringUtils.hasLength(password)) { - return factoryClass.getConstructor(String.class, String.class, String.class).newInstance(user, password, - brokerUrl); + return factoryClass.getConstructor(String.class, String.class, String.class) + .newInstance(user, password, brokerUrl); } return factoryClass.getConstructor(String.class).newInstance(brokerUrl); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQXAConnectionFactoryConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQXAConnectionFactoryConfiguration.java index 7493d7950a..eeb0c05bf1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQXAConnectionFactoryConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQXAConnectionFactoryConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ class ActiveMQXAConnectionFactoryConfiguration { throws Exception { ActiveMQXAConnectionFactory connectionFactory = new ActiveMQConnectionFactoryFactory(properties, factoryCustomizers.orderedStream().collect(Collectors.toList())) - .createConnectionFactory(ActiveMQXAConnectionFactory.class); + .createConnectionFactory(ActiveMQXAConnectionFactory.class); return wrapper.wrapConnectionFactory(connectionFactory); } @@ -64,7 +64,7 @@ class ActiveMQXAConnectionFactoryConfiguration { ObjectProvider factoryCustomizers) { return new ActiveMQConnectionFactoryFactory(properties, factoryCustomizers.orderedStream().collect(Collectors.toList())) - .createConnectionFactory(ActiveMQConnectionFactory.class); + .createConnectionFactory(ActiveMQConnectionFactory.class); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryConfiguration.java index 33ca773b33..ec58238b9a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -78,7 +78,7 @@ class ArtemisConnectionFactoryConfiguration { private ActiveMQConnectionFactory createConnectionFactory() { return new ArtemisConnectionFactoryFactory(this.beanFactory, this.properties) - .createConnectionFactory(ActiveMQConnectionFactory.class); + .createConnectionFactory(ActiveMQConnectionFactory.class); } } @@ -91,9 +91,9 @@ class ArtemisConnectionFactoryConfiguration { @Bean(destroyMethod = "stop") JmsPoolConnectionFactory jmsConnectionFactory(ListableBeanFactory beanFactory, ArtemisProperties properties) { ActiveMQConnectionFactory connectionFactory = new ArtemisConnectionFactoryFactory(beanFactory, properties) - .createConnectionFactory(ActiveMQConnectionFactory.class); + .createConnectionFactory(ActiveMQConnectionFactory.class); return new JmsPoolConnectionFactoryFactory(properties.getPool()) - .createPooledConnectionFactory(connectionFactory); + .createPooledConnectionFactory(connectionFactory); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactory.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactory.java index 6d47dcfd58..81d91c1602 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactory.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,13 +71,14 @@ class ArtemisEmbeddedConfigurationFactory { configuration.addAddressConfiguration(createAddressConfiguration("ExpiryQueue")); configuration.addAddressesSetting("#", new AddressSettings().setDeadLetterAddress(SimpleString.toSimpleString("DLQ")) - .setExpiryAddress(SimpleString.toSimpleString("ExpiryQueue"))); + .setExpiryAddress(SimpleString.toSimpleString("ExpiryQueue"))); return configuration; } private CoreAddressConfiguration createAddressConfiguration(String name) { - return new CoreAddressConfiguration().setName(name).addRoutingType(RoutingType.ANYCAST).addQueueConfiguration( - new QueueConfiguration(name).setRoutingType(RoutingType.ANYCAST).setAddress(name)); + return new CoreAddressConfiguration().setName(name) + .addRoutingType(RoutingType.ANYCAST) + .addQueueConfiguration(new QueueConfiguration(name).setRoutingType(RoutingType.ANYCAST).setAddress(name)); } private String getDataDir() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedServerConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedServerConfiguration.java index 1c1841a55a..2ab3f43c4f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedServerConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedServerConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,15 +69,16 @@ class ArtemisEmbeddedServerConfiguration { ObjectProvider configurationCustomizers) { for (JMSQueueConfiguration queueConfiguration : jmsConfiguration.getQueueConfigurations()) { String queueName = queueConfiguration.getName(); - configuration.addAddressConfiguration( - new CoreAddressConfiguration().setName(queueName).addRoutingType(RoutingType.ANYCAST) - .addQueueConfiguration(new QueueConfiguration(queueName).setAddress(queueName) - .setFilterString(queueConfiguration.getSelector()) - .setDurable(queueConfiguration.isDurable()).setRoutingType(RoutingType.ANYCAST))); + configuration.addAddressConfiguration(new CoreAddressConfiguration().setName(queueName) + .addRoutingType(RoutingType.ANYCAST) + .addQueueConfiguration(new QueueConfiguration(queueName).setAddress(queueName) + .setFilterString(queueConfiguration.getSelector()) + .setDurable(queueConfiguration.isDurable()) + .setRoutingType(RoutingType.ANYCAST))); } for (TopicConfiguration topicConfiguration : jmsConfiguration.getTopicConfigurations()) { configuration.addAddressConfiguration(new CoreAddressConfiguration().setName(topicConfiguration.getName()) - .addRoutingType(RoutingType.MULTICAST)); + .addRoutingType(RoutingType.MULTICAST)); } configurationCustomizers.orderedStream().forEach((customizer) -> customizer.customize(configuration)); EmbeddedActiveMQ embeddedActiveMq = new EmbeddedActiveMQ(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisXAConnectionFactoryConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisXAConnectionFactoryConfiguration.java index 77bff3666a..86147dbac4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisXAConnectionFactoryConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisXAConnectionFactoryConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,14 +47,14 @@ class ArtemisXAConnectionFactoryConfiguration { ConnectionFactory jmsConnectionFactory(ListableBeanFactory beanFactory, ArtemisProperties properties, XAConnectionFactoryWrapper wrapper) throws Exception { return wrapper.wrapConnectionFactory(new ArtemisConnectionFactoryFactory(beanFactory, properties) - .createConnectionFactory(ActiveMQXAConnectionFactory.class)); + .createConnectionFactory(ActiveMQXAConnectionFactory.class)); } @Bean ActiveMQXAConnectionFactory nonXaJmsConnectionFactory(ListableBeanFactory beanFactory, ArtemisProperties properties) { return new ArtemisConnectionFactoryFactory(beanFactory, properties) - .createConnectionFactory(ActiveMQXAConnectionFactory.class); + .createConnectionFactory(ActiveMQXAConnectionFactory.class); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/ConcurrentKafkaListenerContainerFactoryConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/ConcurrentKafkaListenerContainerFactoryConfigurer.java index 2f3f56841f..3aa751a05d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/ConcurrentKafkaListenerContainerFactoryConfigurer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/ConcurrentKafkaListenerContainerFactoryConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -201,10 +201,13 @@ public class ConcurrentKafkaListenerContainerFactoryConfigurer { map.from(properties::getNoPollThreshold).to(container::setNoPollThreshold); map.from(properties.getIdleBetweenPolls()).as(Duration::toMillis).to(container::setIdleBetweenPolls); map.from(properties::getIdleEventInterval).as(Duration::toMillis).to(container::setIdleEventInterval); - map.from(properties::getIdlePartitionEventInterval).as(Duration::toMillis) - .to(container::setIdlePartitionEventInterval); - map.from(properties::getMonitorInterval).as(Duration::getSeconds).as(Number::intValue) - .to(container::setMonitorInterval); + map.from(properties::getIdlePartitionEventInterval) + .as(Duration::toMillis) + .to(container::setIdlePartitionEventInterval); + map.from(properties::getMonitorInterval) + .as(Duration::getSeconds) + .as(Number::intValue) + .to(container::setMonitorInterval); map.from(properties::getLogContainerConfig).to(container::setLogContainerConfig); map.from(properties::isOnlyLogRecordMetadata).to(container::setOnlyLogRecordMetadata); map.from(properties::isMissingTopicsFatal).to(container::setMissingTopicsFatal); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.java index ad6217e952..627047a69e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -89,7 +89,7 @@ class KafkaAnnotationDrivenConfiguration { this.messageConverter = messageConverter.getIfUnique(); this.recordFilterStrategy = recordFilterStrategy.getIfUnique(); this.batchMessageConverter = batchMessageConverter - .getIfUnique(() -> new BatchMessagingMessageConverter(this.messageConverter)); + .getIfUnique(() -> new BatchMessagingMessageConverter(this.messageConverter)); this.kafkaTemplate = kafkaTemplate.getIfUnique(); this.transactionManager = kafkaTransactionManager.getIfUnique(); this.rebalanceListener = rebalanceListener.getIfUnique(); @@ -127,7 +127,7 @@ class KafkaAnnotationDrivenConfiguration { ObjectProvider> kafkaConsumerFactory) { ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); configurer.configure(factory, kafkaConsumerFactory - .getIfAvailable(() -> new DefaultKafkaConsumerFactory<>(this.properties.buildConsumerProperties()))); + .getIfAvailable(() -> new DefaultKafkaConsumerFactory<>(this.properties.buildConsumerProperties()))); return factory; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfiguration.java index 40895af155..1006965f29 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -151,8 +151,10 @@ public class KafkaAutoConfiguration { public RetryTopicConfiguration kafkaRetryTopicConfiguration(KafkaTemplate kafkaTemplate) { KafkaProperties.Retry.Topic retryTopic = this.properties.getRetry().getTopic(); RetryTopicConfigurationBuilder builder = RetryTopicConfigurationBuilder.newInstance() - .maxAttempts(retryTopic.getAttempts()).useSingleTopicForFixedDelays().suffixTopicsWithIndexValues() - .doNotAutoCreateRetryTopics(); + .maxAttempts(retryTopic.getAttempts()) + .useSingleTopicForFixedDelays() + .suffixTopicsWithIndexValues() + .doNotAutoCreateRetryTopics(); setBackOffPolicy(builder, retryTopic); return builder.create(kafkaTemplate); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java index 65fd1575f6..3d334c33ba 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -429,21 +429,25 @@ public class KafkaProperties { public Map buildProperties() { Properties properties = new Properties(); PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); - map.from(this::getAutoCommitInterval).asInt(Duration::toMillis) - .to(properties.in(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG)); + map.from(this::getAutoCommitInterval) + .asInt(Duration::toMillis) + .to(properties.in(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG)); map.from(this::getAutoOffsetReset).to(properties.in(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)); map.from(this::getBootstrapServers).to(properties.in(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG)); map.from(this::getClientId).to(properties.in(ConsumerConfig.CLIENT_ID_CONFIG)); map.from(this::getEnableAutoCommit).to(properties.in(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG)); - map.from(this::getFetchMaxWait).asInt(Duration::toMillis) - .to(properties.in(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG)); - map.from(this::getFetchMinSize).asInt(DataSize::toBytes) - .to(properties.in(ConsumerConfig.FETCH_MIN_BYTES_CONFIG)); + map.from(this::getFetchMaxWait) + .asInt(Duration::toMillis) + .to(properties.in(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG)); + map.from(this::getFetchMinSize) + .asInt(DataSize::toBytes) + .to(properties.in(ConsumerConfig.FETCH_MIN_BYTES_CONFIG)); map.from(this::getGroupId).to(properties.in(ConsumerConfig.GROUP_ID_CONFIG)); - map.from(this::getHeartbeatInterval).asInt(Duration::toMillis) - .to(properties.in(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG)); + map.from(this::getHeartbeatInterval) + .asInt(Duration::toMillis) + .to(properties.in(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG)); map.from(() -> getIsolationLevel().name().toLowerCase(Locale.ROOT)) - .to(properties.in(ConsumerConfig.ISOLATION_LEVEL_CONFIG)); + .to(properties.in(ConsumerConfig.ISOLATION_LEVEL_CONFIG)); map.from(this::getKeyDeserializer).to(properties.in(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG)); map.from(this::getValueDeserializer).to(properties.in(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG)); map.from(this::getMaxPollRecords).to(properties.in(ConsumerConfig.MAX_POLL_RECORDS_CONFIG)); @@ -615,8 +619,9 @@ public class KafkaProperties { map.from(this::getAcks).to(properties.in(ProducerConfig.ACKS_CONFIG)); map.from(this::getBatchSize).asInt(DataSize::toBytes).to(properties.in(ProducerConfig.BATCH_SIZE_CONFIG)); map.from(this::getBootstrapServers).to(properties.in(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)); - map.from(this::getBufferMemory).as(DataSize::toBytes) - .to(properties.in(ProducerConfig.BUFFER_MEMORY_CONFIG)); + map.from(this::getBufferMemory) + .as(DataSize::toBytes) + .to(properties.in(ProducerConfig.BUFFER_MEMORY_CONFIG)); map.from(this::getClientId).to(properties.in(ProducerConfig.CLIENT_ID_CONFIG)); map.from(this::getCompressionType).to(properties.in(ProducerConfig.COMPRESSION_TYPE_CONFIG)); map.from(this::getKeySerializer).to(properties.in(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)); @@ -815,8 +820,9 @@ public class KafkaProperties { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(this::getApplicationId).to(properties.in("application.id")); map.from(this::getBootstrapServers).to(properties.in(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG)); - map.from(this::getCacheMaxSizeBuffering).asInt(DataSize::toBytes) - .to(properties.in("cache.max.bytes.buffering")); + map.from(this::getCacheMaxSizeBuffering) + .asInt(DataSize::toBytes) + .to(properties.in("cache.max.bytes.buffering")); map.from(this::getClientId).to(properties.in(CommonClientConfigs.CLIENT_ID_CONFIG)); map.from(this::getReplicationFactor).to(properties.in("replication.factor")); map.from(this::getStateDir).to(properties.in("state.dir")); @@ -1244,15 +1250,17 @@ public class KafkaProperties { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(this::getKeyPassword).to(properties.in(SslConfigs.SSL_KEY_PASSWORD_CONFIG)); map.from(this::getKeyStoreCertificateChain) - .to(properties.in(SslConfigs.SSL_KEYSTORE_CERTIFICATE_CHAIN_CONFIG)); + .to(properties.in(SslConfigs.SSL_KEYSTORE_CERTIFICATE_CHAIN_CONFIG)); map.from(this::getKeyStoreKey).to(properties.in(SslConfigs.SSL_KEYSTORE_KEY_CONFIG)); - map.from(this::getKeyStoreLocation).as(this::resourceToPath) - .to(properties.in(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)); + map.from(this::getKeyStoreLocation) + .as(this::resourceToPath) + .to(properties.in(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)); map.from(this::getKeyStorePassword).to(properties.in(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)); map.from(this::getKeyStoreType).to(properties.in(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)); map.from(this::getTrustStoreCertificates).to(properties.in(SslConfigs.SSL_TRUSTSTORE_CERTIFICATES_CONFIG)); - map.from(this::getTrustStoreLocation).as(this::resourceToPath) - .to(properties.in(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)); + map.from(this::getTrustStoreLocation) + .as(this::resourceToPath) + .to(properties.in(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)); map.from(this::getTrustStorePassword).to(properties.in(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)); map.from(this::getTrustStoreType).to(properties.in(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)); map.from(this::getProtocol).to(properties.in(SslConfigs.SSL_PROTOCOL_CONFIG)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.java index 7ca7cb9b1c..0144f9bf99 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,8 +58,8 @@ public class LdapAutoConfiguration { propertyMapper.from(properties.getAnonymousReadOnly()).to(source::setAnonymousReadOnly); propertyMapper.from(properties.getBase()).to(source::setBase); propertyMapper.from(properties.determineUrls(environment)).to(source::setUrls); - propertyMapper.from(properties.getBaseEnvironment()).to( - (baseEnvironment) -> source.setBaseEnvironmentProperties(Collections.unmodifiableMap(baseEnvironment))); + propertyMapper.from(properties.getBaseEnvironment()) + .to((baseEnvironment) -> source.setBaseEnvironmentProperties(Collections.unmodifiableMap(baseEnvironment))); return source; } @@ -70,10 +70,10 @@ public class LdapAutoConfiguration { PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenNonNull(); LdapTemplate ldapTemplate = new LdapTemplate(contextSource); propertyMapper.from(template.isIgnorePartialResultException()) - .to(ldapTemplate::setIgnorePartialResultException); + .to(ldapTemplate::setIgnorePartialResultException); propertyMapper.from(template.isIgnoreNameNotFoundException()).to(ldapTemplate::setIgnoreNameNotFoundException); propertyMapper.from(template.isIgnoreSizeLimitExceededException()) - .to(ldapTemplate::setIgnoreSizeLimitExceededException); + .to(ldapTemplate::setIgnoreSizeLimitExceededException); return ldapTemplate; } 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 00f7ddd6cd..25b56aa477 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -146,7 +146,7 @@ public class EmbeddedLdapAutoConfiguration { private void setPortProperty(ApplicationContext context, int port) { if (context instanceof ConfigurableApplicationContext) { MutablePropertySources sources = ((ConfigurableApplicationContext) context).getEnvironment() - .getPropertySources(); + .getPropertySources(); getLdapPorts(sources).put("local.ldap.port", port); } if (context.getParent() != null) { @@ -183,8 +183,10 @@ public class EmbeddedLdapAutoConfiguration { public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { Builder message = ConditionMessage.forCondition("Embedded LDAP"); Environment environment = context.getEnvironment(); - if (environment != null && !Binder.get(environment).bind("spring.ldap.embedded.base-dn", STRING_LIST) - .orElseGet(Collections::emptyList).isEmpty()) { + if (environment != null && !Binder.get(environment) + .bind("spring.ldap.embedded.base-dn", STRING_LIST) + .orElseGet(Collections::emptyList) + .isEmpty()) { return ConditionOutcome.match(message.because("Found base-dn property")); } return ConditionOutcome.noMatch(message.because("No base-dn property found")); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration.java index 7099825f31..b716ad3207 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -130,7 +130,7 @@ public class LiquibaseAutoConfiguration { } if (properties.getUser() != null && dataSource != null) { DataSourceBuilder builder = DataSourceBuilder.derivedFrom(dataSource) - .type(SimpleDriverDataSource.class); + .type(SimpleDriverDataSource.class); applyCommonBuilderProperties(properties, builder); return builder.build(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseSchemaManagementProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseSchemaManagementProvider.java index a5ad86c64d..e6f8c00083 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseSchemaManagementProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseSchemaManagementProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,9 +42,12 @@ class LiquibaseSchemaManagementProvider implements SchemaManagementProvider { @Override public SchemaManagement getSchemaManagement(DataSource dataSource) { - return StreamSupport.stream(this.liquibaseInstances.spliterator(), false).map(SpringLiquibase::getDataSource) - .filter(dataSource::equals).findFirst().map((managedDataSource) -> SchemaManagement.MANAGED) - .orElse(SchemaManagement.UNMANAGED); + return StreamSupport.stream(this.liquibaseInstances.spliterator(), false) + .map(SpringLiquibase::getDataSource) + .filter(dataSource::equals) + .findFirst() + .map((managedDataSource) -> SchemaManagement.MANAGED) + .orElse(SchemaManagement.UNMANAGED); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportMessage.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportMessage.java index 802206cd9f..62b702a6bb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportMessage.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportMessage.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,8 +74,10 @@ public class ConditionEvaluationReportMessage { private void logPositiveMatches(StringBuilder message, Map shortOutcomes) { message.append(String.format("Positive matches:%n")); message.append(String.format("-----------------%n")); - List> matched = shortOutcomes.entrySet().stream() - .filter((entry) -> entry.getValue().isFullMatch()).collect(Collectors.toList()); + List> matched = shortOutcomes.entrySet() + .stream() + .filter((entry) -> entry.getValue().isFullMatch()) + .collect(Collectors.toList()); if (matched.isEmpty()) { message.append(String.format("%n None%n")); } @@ -88,8 +90,10 @@ public class ConditionEvaluationReportMessage { private void logNegativeMatches(StringBuilder message, Map shortOutcomes) { message.append(String.format("Negative matches:%n")); message.append(String.format("-----------------%n")); - List> nonMatched = shortOutcomes.entrySet().stream() - .filter((entry) -> !entry.getValue().isFullMatch()).collect(Collectors.toList()); + List> nonMatched = shortOutcomes.entrySet() + .stream() + .filter((entry) -> !entry.getValue().isFullMatch()) + .collect(Collectors.toList()); if (nonMatched.isEmpty()) { message.append(String.format("%n None%n")); } @@ -134,8 +138,8 @@ public class ConditionEvaluationReportMessage { for (String shortName : shortNames) { List fullyQualifiedNames = map.get(shortName); if (fullyQualifiedNames.size() > 1) { - fullyQualifiedNames.forEach( - (fullyQualifiedName) -> result.put(fullyQualifiedName, outcomes.get(fullyQualifiedName))); + fullyQualifiedNames + .forEach((fullyQualifiedName) -> result.put(fullyQualifiedName, outcomes.get(fullyQualifiedName))); } else { result.put(shortName, outcomes.get(fullyQualifiedNames.get(0))); @@ -146,8 +150,8 @@ public class ConditionEvaluationReportMessage { private MultiValueMap mapToFullyQualifiedNames(Set keySet) { LinkedMultiValueMap map = new LinkedMultiValueMap<>(); - keySet.forEach( - (fullyQualifiedName) -> map.add(ClassUtils.getShortName(fullyQualifiedName), fullyQualifiedName)); + keySet + .forEach((fullyQualifiedName) -> map.add(ClassUtils.getShortName(fullyQualifiedName), fullyQualifiedName)); return map; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.java index 3dc054eafa..ab5be71f1f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ public class MongoAutoConfiguration { public MongoClient mongo(ObjectProvider builderCustomizers, MongoClientSettings settings) { return new MongoClientFactory(builderCustomizers.orderedStream().collect(Collectors.toList())) - .createMongoClient(settings); + .createMongoClient(settings); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactorySupport.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactorySupport.java index be841adec8..d45465ab4d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactorySupport.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactorySupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,8 +57,9 @@ public abstract class MongoClientFactorySupport { } private MongoDriverInformation driverInformation() { - return MongoDriverInformation.builder(MongoDriverInformation.builder().build()).driverName("spring-boot") - .build(); + return MongoDriverInformation.builder(MongoDriverInformation.builder().build()) + .driverName("spring-boot") + .build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfiguration.java index 3c7fb8b65b..8857447512 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -111,8 +111,8 @@ public class MongoReactiveAutoConfiguration { if (!isStreamFactoryFactoryDefined(this.settings.getIfAvailable())) { NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(); this.eventLoopGroup = eventLoopGroup; - builder.streamFactoryFactory( - NettyStreamFactoryFactory.builder().eventLoopGroup(eventLoopGroup).build()); + builder + .streamFactoryFactory(NettyStreamFactoryFactory.builder().eventLoopGroup(eventLoopGroup).build()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java index 095c2cc9ea..9d3a500485 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -136,8 +136,8 @@ public class EmbeddedMongoAutoConfiguration { builder.net(new Net(getHost().getHostAddress(), configuredPort, Network.localhostIsIPv6())); } else { - builder.net( - new Net(getHost().getHostAddress(), Network.freeServerPort(getHost()), Network.localhostIsIPv6())); + builder + .net(new Net(getHost().getHostAddress(), Network.freeServerPort(getHost()), Network.localhostIsIPv6())); } return builder.build(); } @@ -171,7 +171,7 @@ public class EmbeddedMongoAutoConfiguration { private void setPortProperty(ApplicationContext currentContext, int port) { if (currentContext instanceof ConfigurableApplicationContext) { MutablePropertySources sources = ((ConfigurableApplicationContext) currentContext).getEnvironment() - .getPropertySources(); + .getPropertySources(); getMongoPorts(sources).put("local.mongo.port", port); } if (currentContext.getParent() != null) { @@ -198,12 +198,16 @@ public class EmbeddedMongoAutoConfiguration { RuntimeConfig embeddedMongoRuntimeConfig( ObjectProvider downloadConfigBuilderCustomizers) { Logger logger = LoggerFactory.getLogger(getClass().getPackage().getName() + ".EmbeddedMongo"); - ProcessOutput processOutput = ProcessOutput.builder().output(Processors.logTo(logger, Slf4jLevel.INFO)) - .error(Processors.logTo(logger, Slf4jLevel.ERROR)) - .commands(Processors.named("[console>]", Processors.logTo(logger, Slf4jLevel.DEBUG))).build(); - return Defaults.runtimeConfigFor(Command.MongoD, logger).processOutput(processOutput) - .artifactStore(getArtifactStore(logger, downloadConfigBuilderCustomizers.orderedStream())) - .isDaemonProcess(false).build(); + ProcessOutput processOutput = ProcessOutput.builder() + .output(Processors.logTo(logger, Slf4jLevel.INFO)) + .error(Processors.logTo(logger, Slf4jLevel.ERROR)) + .commands(Processors.named("[console>]", Processors.logTo(logger, Slf4jLevel.DEBUG))) + .build(); + return Defaults.runtimeConfigFor(Command.MongoD, logger) + .processOutput(processOutput) + .artifactStore(getArtifactStore(logger, downloadConfigBuilderCustomizers.orderedStream())) + .isDaemonProcess(false) + .build(); } private ExtractedArtifactStore getArtifactStore(Logger logger, diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfiguration.java index 39c52b4d30..5d9aa4ebba 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -91,8 +91,8 @@ public class Neo4jAutoConfiguration { boolean hasKerberosTicket = StringUtils.hasText(kerberosTicket); if (hasUsername && hasKerberosTicket) { - throw new IllegalStateException(String.format( - "Cannot specify both username ('%s') and kerberos ticket ('%s')", username, kerberosTicket)); + throw new IllegalStateException(String + .format("Cannot specify both username ('%s') and kerberos ticket ('%s')", username, kerberosTicket)); } if (hasUsername && hasPassword) { return AuthTokens.basic(username, password, realm); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProvider.java index 3af26dac6e..aaef06de21 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,8 +52,10 @@ class HibernateDefaultDdlAutoProvider implements SchemaManagementProvider { @Override public SchemaManagement getSchemaManagement(DataSource dataSource) { return StreamSupport.stream(this.providers.spliterator(), false) - .map((provider) -> provider.getSchemaManagement(dataSource)).filter(SchemaManagement.MANAGED::equals) - .findFirst().orElse(SchemaManagement.UNMANAGED); + .map((provider) -> provider.getSchemaManagement(dataSource)) + .filter(SchemaManagement.MANAGED::equals) + .findFirst() + .orElse(SchemaManagement.UNMANAGED); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.java index 01a8fa29fd..7dc9a80ab8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -113,8 +113,8 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration { new SpringBeanContainer(beanFactory))); } if (physicalNamingStrategy != null || implicitNamingStrategy != null) { - customizers.add( - new NamingStrategiesHibernatePropertiesCustomizer(physicalNamingStrategy, implicitNamingStrategy)); + customizers + .add(new NamingStrategiesHibernatePropertiesCustomizer(physicalNamingStrategy, implicitNamingStrategy)); } customizers.addAll(hibernatePropertiesCustomizers); return customizers; @@ -128,9 +128,9 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration { @Override protected Map getVendorProperties() { Supplier defaultDdlMode = () -> this.defaultDdlAutoProvider.getDefaultDdlAuto(getDataSource()); - return new LinkedHashMap<>(this.hibernateProperties - .determineHibernateProperties(getProperties().getProperties(), new HibernateSettings() - .ddlAuto(defaultDdlMode).hibernatePropertiesCustomizers(this.hibernatePropertiesCustomizers))); + return new LinkedHashMap<>(this.hibernateProperties.determineHibernateProperties( + getProperties().getProperties(), new HibernateSettings().ddlAuto(defaultDdlMode) + .hibernatePropertiesCustomizers(this.hibernatePropertiesCustomizers))); } @Override diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java index 26600544e6..19c40b78f8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -131,8 +131,12 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware { public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder factoryBuilder) { Map vendorProperties = getVendorProperties(); customizeVendorProperties(vendorProperties); - return factoryBuilder.dataSource(this.dataSource).packages(getPackagesToScan()).properties(vendorProperties) - .mappingResources(getMappingResources()).jta(isJta()).build(); + return factoryBuilder.dataSource(this.dataSource) + .packages(getPackagesToScan()) + .properties(vendorProperties) + .mappingResources(getMappingResources()) + .jta(isJta()) + .build(); } protected abstract AbstractJpaVendorAdapter createJpaVendorAdapter(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/r2dbc/ConnectionFactoryBeanCreationFailureAnalyzer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/r2dbc/ConnectionFactoryBeanCreationFailureAnalyzer.java index a71e05e27d..c2833a6b26 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/r2dbc/ConnectionFactoryBeanCreationFailureAnalyzer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/r2dbc/ConnectionFactoryBeanCreationFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,8 +70,10 @@ class ConnectionFactoryBeanCreationFailureAnalyzer else { action.append(String.format("\tReview the configuration of %s%n.", cause.getEmbeddedDatabaseConnection())); } - action.append("\tIf you have database settings to be loaded from a particular " - + "profile you may need to activate it").append(getActiveProfiles()); + action + .append("\tIf you have database settings to be loaded from a particular " + + "profile you may need to activate it") + .append(getActiveProfiles()); return action.toString(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/r2dbc/ConnectionFactoryConfigurations.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/r2dbc/ConnectionFactoryConfigurations.java index f7c815f119..a4c636d2a1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/r2dbc/ConnectionFactoryConfigurations.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/r2dbc/ConnectionFactoryConfigurations.java @@ -59,13 +59,14 @@ abstract class ConnectionFactoryConfigurations { List optionsCustomizers) { try { return org.springframework.boot.r2dbc.ConnectionFactoryBuilder - .withOptions(new ConnectionFactoryOptionsInitializer().initialize(properties, - () -> EmbeddedDatabaseConnection.get(classLoader))) - .configure((options) -> { - for (ConnectionFactoryOptionsBuilderCustomizer optionsCustomizer : optionsCustomizers) { - optionsCustomizer.customize(options); - } - }).build(); + .withOptions(new ConnectionFactoryOptionsInitializer().initialize(properties, + () -> EmbeddedDatabaseConnection.get(classLoader))) + .configure((options) -> { + for (ConnectionFactoryOptionsBuilderCustomizer optionsCustomizer : optionsCustomizers) { + optionsCustomizer.customize(options); + } + }) + .build(); } catch (IllegalStateException ex) { String message = ex.getMessage(); @@ -135,8 +136,8 @@ abstract class ConnectionFactoryConfigurations { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { - BindResult pool = Binder.get(context.getEnvironment()).bind("spring.r2dbc.pool", - Bindable.of(Pool.class)); + BindResult pool = Binder.get(context.getEnvironment()) + .bind("spring.r2dbc.pool", Bindable.of(Pool.class)); if (hasPoolUrl(context.getEnvironment())) { if (pool.isBound()) { throw new MultipleConnectionPoolConfigurationsException(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfiguration.java index dd5b8c13ac..a6958a8332 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfiguration.java @@ -111,7 +111,7 @@ public class RSocketServerAutoConfiguration { RSocketServerCustomizer frameDecoderRSocketServerCustomizer(RSocketMessageHandler rSocketMessageHandler) { return (server) -> { if (rSocketMessageHandler.getRSocketStrategies() - .dataBufferFactory() instanceof NettyDataBufferFactory) { + .dataBufferFactory() instanceof NettyDataBufferFactory) { server.payloadDecoder(PayloadDecoder.ZERO_COPY); } }; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ClientsConfiguredCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ClientsConfiguredCondition.java index c6246d4c24..43e7ef93f9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ClientsConfiguredCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ClientsConfiguredCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,22 +40,25 @@ import org.springframework.core.type.AnnotatedTypeMetadata; public class ClientsConfiguredCondition extends SpringBootCondition { private static final Bindable> STRING_REGISTRATION_MAP = Bindable - .mapOf(String.class, OAuth2ClientProperties.Registration.class); + .mapOf(String.class, OAuth2ClientProperties.Registration.class); @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConditionMessage.Builder message = ConditionMessage.forCondition("OAuth2 Clients Configured Condition"); Map registrations = getRegistrations(context.getEnvironment()); if (!registrations.isEmpty()) { - return ConditionOutcome.match(message.foundExactly("registered clients " + registrations.values().stream() - .map(OAuth2ClientProperties.Registration::getClientId).collect(Collectors.joining(", ")))); + return ConditionOutcome.match(message.foundExactly("registered clients " + registrations.values() + .stream() + .map(OAuth2ClientProperties.Registration::getClientId) + .collect(Collectors.joining(", ")))); } return ConditionOutcome.noMatch(message.notAvailable("registered clients")); } private Map getRegistrations(Environment environment) { - return Binder.get(environment).bind("spring.security.oauth2.client.registration", STRING_REGISTRATION_MAP) - .orElse(Collections.emptyMap()); + return Binder.get(environment) + .bind("spring.security.oauth2.client.registration", STRING_REGISTRATION_MAP) + .orElse(Collections.emptyMap()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapter.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapter.java index d1b9777675..905602259d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapter.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,9 @@ public final class OAuth2ClientPropertiesRegistrationAdapter { public static Map getClientRegistrations(OAuth2ClientProperties properties) { Map clientRegistrations = new HashMap<>(); - properties.getRegistration().forEach((key, value) -> clientRegistrations.put(key, - getClientRegistration(key, value, properties.getProvider()))); + properties.getRegistration() + .forEach((key, value) -> clientRegistrations.put(key, + getClientRegistration(key, value, properties.getProvider()))); return clientRegistrations; } @@ -63,10 +64,12 @@ public final class OAuth2ClientPropertiesRegistrationAdapter { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(properties::getClientId).to(builder::clientId); map.from(properties::getClientSecret).to(builder::clientSecret); - map.from(properties::getClientAuthenticationMethod).as(ClientAuthenticationMethod::new) - .to(builder::clientAuthenticationMethod); - map.from(properties::getAuthorizationGrantType).as(AuthorizationGrantType::new) - .to(builder::authorizationGrantType); + map.from(properties::getClientAuthenticationMethod) + .as(ClientAuthenticationMethod::new) + .to(builder::clientAuthenticationMethod); + map.from(properties::getAuthorizationGrantType) + .as(AuthorizationGrantType::new) + .to(builder::authorizationGrantType); map.from(properties::getRedirectUri).to(builder::redirectUri); map.from(properties::getScope).as(StringUtils::toStringArray).to(builder::scope); map.from(properties::getClientName).to(builder::clientName); @@ -112,8 +115,9 @@ public final class OAuth2ClientPropertiesRegistrationAdapter { map.from(provider::getAuthorizationUri).to(builder::authorizationUri); map.from(provider::getTokenUri).to(builder::tokenUri); map.from(provider::getUserInfoUri).to(builder::userInfoUri); - map.from(provider::getUserInfoAuthenticationMethod).as(AuthenticationMethod::new) - .to(builder::userInfoAuthenticationMethod); + map.from(provider::getUserInfoAuthenticationMethod) + .as(AuthenticationMethod::new) + .to(builder::userInfoAuthenticationMethod); map.from(provider::getJwkSetUri).to(builder::jwkSetUri); map.from(provider::getUserNameAttribute).to(builder::userNameAttributeName); return builder; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/KeyValueCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/KeyValueCondition.java index 9f282187fc..90b5d71cb0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/KeyValueCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/KeyValueCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ public class KeyValueCondition extends SpringBootCondition { ConditionMessage.Builder message = ConditionMessage.forCondition("Public Key Value Condition"); Environment environment = context.getEnvironment(); String publicKeyLocation = environment - .getProperty("spring.security.oauth2.resourceserver.jwt.public-key-location"); + .getProperty("spring.security.oauth2.resourceserver.jwt.public-key-location"); if (!StringUtils.hasText(publicKeyLocation)) { return ConditionOutcome.noMatch(message.didNotFind("public-key-location property").atAll()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerJwkConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerJwkConfiguration.java index 715aa69dd2..edaf54d1ea 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerJwkConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerJwkConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,7 +79,9 @@ class ReactiveOAuth2ResourceServerJwkConfiguration { @ConditionalOnProperty(name = "spring.security.oauth2.resourceserver.jwt.jwk-set-uri") ReactiveJwtDecoder jwtDecoder() { NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = NimbusReactiveJwtDecoder - .withJwkSetUri(this.properties.getJwkSetUri()).jwsAlgorithms(this::jwsAlgorithms).build(); + .withJwkSetUri(this.properties.getJwkSetUri()) + .jwsAlgorithms(this::jwsAlgorithms) + .build(); String issuerUri = this.properties.getIssuerUri(); Supplier> defaultValidator = (issuerUri != null) ? () -> JwtValidators.createDefaultWithIssuer(issuerUri) : JwtValidators::createDefault; @@ -110,9 +112,10 @@ class ReactiveOAuth2ResourceServerJwkConfiguration { @Conditional(KeyValueCondition.class) NimbusReactiveJwtDecoder jwtDecoderByPublicKeyValue() throws Exception { RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA") - .generatePublic(new X509EncodedKeySpec(getKeySpec(this.properties.readPublicKey()))); + .generatePublic(new X509EncodedKeySpec(getKeySpec(this.properties.readPublicKey()))); NimbusReactiveJwtDecoder jwtDecoder = NimbusReactiveJwtDecoder.withPublicKey(publicKey) - .signatureAlgorithm(SignatureAlgorithm.from(exactlyOneAlgorithm())).build(); + .signatureAlgorithm(SignatureAlgorithm.from(exactlyOneAlgorithm())) + .build(); jwtDecoder.setJwtValidator(getValidators(JwtValidators::createDefault)); return jwtDecoder; } @@ -138,7 +141,7 @@ class ReactiveOAuth2ResourceServerJwkConfiguration { SupplierReactiveJwtDecoder jwtDecoderByIssuerUri() { return new SupplierReactiveJwtDecoder(() -> { NimbusReactiveJwtDecoder jwtDecoder = (NimbusReactiveJwtDecoder) ReactiveJwtDecoders - .fromIssuerLocation(this.properties.getIssuerUri()); + .fromIssuerLocation(this.properties.getIssuerUri()); jwtDecoder.setJwtValidator( getValidators(() -> JwtValidators.createDefaultWithIssuer(this.properties.getIssuerUri()))); return jwtDecoder; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerJwtConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerJwtConfiguration.java index 479ace9b43..3d9b52ab0a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerJwtConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerJwtConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,7 +79,8 @@ class OAuth2ResourceServerJwtConfiguration { @ConditionalOnProperty(name = "spring.security.oauth2.resourceserver.jwt.jwk-set-uri") JwtDecoder jwtDecoderByJwkKeySetUri() { NimbusJwtDecoder nimbusJwtDecoder = NimbusJwtDecoder.withJwkSetUri(this.properties.getJwkSetUri()) - .jwsAlgorithms(this::jwsAlgorithms).build(); + .jwsAlgorithms(this::jwsAlgorithms) + .build(); String issuerUri = this.properties.getIssuerUri(); Supplier> defaultValidator = (issuerUri != null) ? () -> JwtValidators.createDefaultWithIssuer(issuerUri) : JwtValidators::createDefault; @@ -110,9 +111,10 @@ class OAuth2ResourceServerJwtConfiguration { @Conditional(KeyValueCondition.class) JwtDecoder jwtDecoderByPublicKeyValue() throws Exception { RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA") - .generatePublic(new X509EncodedKeySpec(getKeySpec(this.properties.readPublicKey()))); + .generatePublic(new X509EncodedKeySpec(getKeySpec(this.properties.readPublicKey()))); NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey(publicKey) - .signatureAlgorithm(SignatureAlgorithm.from(exactlyOneAlgorithm())).build(); + .signatureAlgorithm(SignatureAlgorithm.from(exactlyOneAlgorithm())) + .build(); jwtDecoder.setJwtValidator(getValidators(JwtValidators::createDefault)); return jwtDecoder; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/rsocket/RSocketSecurityAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/rsocket/RSocketSecurityAutoConfiguration.java index c2dcd14d3c..1b8692bafd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/rsocket/RSocketSecurityAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/rsocket/RSocketSecurityAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ public class RSocketSecurityAutoConfiguration { @Bean RSocketMessageHandlerCustomizer rSocketAuthenticationPrincipalMessageHandlerCustomizer() { return (messageHandler) -> messageHandler.getArgumentResolverConfigurer() - .addCustomResolver(new AuthenticationPrincipalArgumentResolver()); + .addCustomResolver(new AuthenticationPrincipalArgumentResolver()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyRegistrationConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyRegistrationConfiguration.java index b4be7d3590..788d4a279a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyRegistrationConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyRegistrationConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,8 +71,11 @@ class Saml2RelyingPartyRegistrationConfiguration { @Bean RelyingPartyRegistrationRepository relyingPartyRegistrationRepository(Saml2RelyingPartyProperties properties) { - List registrations = properties.getRegistration().entrySet().stream() - .map(this::asRegistration).collect(Collectors.toList()); + List registrations = properties.getRegistration() + .entrySet() + .stream() + .map(this::asRegistration) + .collect(Collectors.toList()); return new InMemoryRelyingPartyRegistrationRepository(registrations); } @@ -89,13 +92,22 @@ class Saml2RelyingPartyRegistrationConfiguration { builder.assertionConsumerServiceLocation(properties.getAcs().getLocation()); builder.assertionConsumerServiceBinding(properties.getAcs().getBinding()); builder.assertingPartyDetails(mapAssertingParty(properties, id, usingMetadata)); - builder.signingX509Credentials((credentials) -> properties.getSigning().getCredentials().stream() - .map(this::asSigningCredential).forEach(credentials::add)); - builder.decryptionX509Credentials((credentials) -> properties.getDecryption().getCredentials().stream() - .map(this::asDecryptionCredential).forEach(credentials::add)); + builder.signingX509Credentials((credentials) -> properties.getSigning() + .getCredentials() + .stream() + .map(this::asSigningCredential) + .forEach(credentials::add)); + builder.decryptionX509Credentials((credentials) -> properties.getDecryption() + .getCredentials() + .stream() + .map(this::asDecryptionCredential) + .forEach(credentials::add)); builder.assertingPartyDetails( (details) -> details.verificationX509Credentials((credentials) -> assertingParty.getVerification() - .getCredentials().stream().map(this::asVerificationCredential).forEach(credentials::add))); + .getCredentials() + .stream() + .map(this::asVerificationCredential) + .forEach(credentials::add))); builder.singleLogoutServiceLocation(properties.getSinglelogout().getUrl()); builder.singleLogoutServiceResponseLocation(properties.getSinglelogout().getResponseUrl()); builder.singleLogoutServiceBinding(properties.getSinglelogout().getBinding()); @@ -114,8 +126,9 @@ class Saml2RelyingPartyRegistrationConfiguration { map.from(assertingParty::getEntityId).to(details::entityId); map.from(assertingParty::getSingleSignonBinding).to(details::singleSignOnServiceBinding); map.from(assertingParty::getSingleSignonUrl).to(details::singleSignOnServiceLocation); - map.from(assertingParty::getSingleSignonSignRequest).when((ignored) -> !usingMetadata) - .to(details::wantAuthnRequestsSigned); + map.from(assertingParty::getSingleSignonSignRequest) + .when((ignored) -> !usingMetadata) + .to(details::wantAuthnRequestsSigned); map.from(assertingParty.getSinglelogoutUrl()).to(details::singleLogoutServiceLocation); map.from(assertingParty.getSinglelogoutResponseUrl()).to(details::singleLogoutServiceResponseLocation); map.from(assertingParty.getSinglelogoutBinding()).to(details::singleLogoutServiceBinding); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfiguration.java index 34198755c0..c5d70a62dc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,9 +69,11 @@ public class SecurityFilterAutoConfiguration { if (securityProperties.getFilter().getDispatcherTypes() == null) { return null; } - return securityProperties.getFilter().getDispatcherTypes().stream() - .map((type) -> DispatcherType.valueOf(type.name())) - .collect(Collectors.toCollection(() -> EnumSet.noneOf(DispatcherType.class))); + return securityProperties.getFilter() + .getDispatcherTypes() + .stream() + .map((type) -> DispatcherType.valueOf(type.name())) + .collect(Collectors.toCollection(() -> EnumSet.noneOf(DispatcherType.class))); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequest.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequest.java index c6f38ed14c..a5c29f1b46 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequest.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -142,8 +142,9 @@ public final class StaticResourceRequest { } private Stream getPatterns(DispatcherServletPath dispatcherServletPath) { - return this.locations.stream().flatMap(StaticResourceLocation::getPatterns) - .map(dispatcherServletPath::getRelativePath); + return this.locations.stream() + .flatMap(StaticResourceLocation::getPatterns) + .map(dispatcherServletPath::getRelativePath); } @Override diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfiguration.java index 10f146e9a4..03431aba24 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,9 +77,10 @@ public class UserDetailsServiceAutoConfiguration { ObjectProvider passwordEncoder) { SecurityProperties.User user = properties.getUser(); List roles = user.getRoles(); - return new InMemoryUserDetailsManager( - User.withUsername(user.getName()).password(getOrDeducePassword(user, passwordEncoder.getIfAvailable())) - .roles(StringUtils.toStringArray(roles)).build()); + return new InMemoryUserDetailsManager(User.withUsername(user.getName()) + .password(getOrDeducePassword(user, passwordEncoder.getIfAvailable())) + .roles(StringUtils.toStringArray(roles)) + .build()); } private String getOrDeducePassword(SecurityProperties.User user, PasswordEncoder encoder) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/AbstractSessionCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/AbstractSessionCondition.java index 52cc494519..ba5040a6e7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/AbstractSessionCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/AbstractSessionCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,15 +51,15 @@ abstract class AbstractSessionCondition extends SpringBootCondition { ((AnnotationMetadata) metadata).getClassName()); if (!environment.containsProperty("spring.session.store-type")) { return ConditionOutcome.match(message.didNotFind("property", "properties") - .items(ConditionMessage.Style.QUOTE, "spring.session.store-type")); + .items(ConditionMessage.Style.QUOTE, "spring.session.store-type")); } try { Binder binder = Binder.get(environment); return binder.bind("spring.session.store-type", StoreType.class) - .map((t) -> new ConditionOutcome(t == required, - message.found("spring.session.store-type property").items(t))) - .orElseGet(() -> ConditionOutcome - .noMatch(message.didNotFind("spring.session.store-type property").atAll())); + .map((t) -> new ConditionOutcome(t == required, + message.found("spring.session.store-type property").items(t))) + .orElseGet(() -> ConditionOutcome + .noMatch(message.didNotFind("spring.session.store-type property").atAll())); } catch (BindException ex) { return ConditionOutcome.noMatch(message.found("invalid spring.session.store-type property").atAll()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HazelcastSessionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HazelcastSessionConfiguration.java index 15fbb27b0d..3e3677eef0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HazelcastSessionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HazelcastSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,7 +55,7 @@ class HazelcastSessionConfiguration { public void customize(SessionProperties sessionProperties, HazelcastSessionProperties hazelcastSessionProperties, ServerProperties serverProperties) { Duration timeout = sessionProperties - .determineTimeout(() -> serverProperties.getServlet().getSession().getTimeout()); + .determineTimeout(() -> serverProperties.getServlet().getSession().getTimeout()); if (timeout != null) { setMaxInactiveIntervalInSeconds((int) timeout.getSeconds()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionConfiguration.java index 397a89f60f..8a9da464d4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,7 +74,7 @@ class JdbcSessionConfiguration { void customize(SessionProperties sessionProperties, JdbcSessionProperties jdbcSessionProperties, ServerProperties serverProperties) { Duration timeout = sessionProperties - .determineTimeout(() -> serverProperties.getServlet().getSession().getTimeout()); + .determineTimeout(() -> serverProperties.getServlet().getSession().getTimeout()); if (timeout != null) { setMaxInactiveIntervalInSeconds((int) timeout.getSeconds()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoReactiveSessionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoReactiveSessionConfiguration.java index de5fadcd72..448c6f47c0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoReactiveSessionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoReactiveSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ class MongoReactiveSessionConfiguration { void customize(SessionProperties sessionProperties, MongoSessionProperties mongoSessionProperties, ServerProperties serverProperties) { Duration timeout = sessionProperties - .determineTimeout(() -> serverProperties.getReactive().getSession().getTimeout()); + .determineTimeout(() -> serverProperties.getReactive().getSession().getTimeout()); if (timeout != null) { setMaxInactiveIntervalInSeconds((int) timeout.getSeconds()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoSessionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoSessionConfiguration.java index 2118bdbdc6..7ce7a8e5b8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoSessionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ class MongoSessionConfiguration { public void customize(SessionProperties sessionProperties, MongoSessionProperties mongoSessionProperties, ServerProperties serverProperties) { Duration timeout = sessionProperties - .determineTimeout(() -> serverProperties.getServlet().getSession().getTimeout()); + .determineTimeout(() -> serverProperties.getServlet().getSession().getTimeout()); if (timeout != null) { setMaxInactiveIntervalInSeconds((int) timeout.getSeconds()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryFailureAnalyzer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryFailureAnalyzer.java index 3cbb89f57b..8c814bedba 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryFailureAnalyzer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,8 @@ class NonUniqueSessionRepositoryFailureAnalyzer extends AbstractFailureAnalyzer< @Override protected FailureAnalysis analyze(Throwable rootFailure, NonUniqueSessionRepositoryException cause) { StringBuilder message = new StringBuilder(); - message.append( - String.format("Multiple Spring Session store implementations are available on the classpath:%n")); + message + .append(String.format("Multiple Spring Session store implementations are available on the classpath:%n")); for (Class candidate : cause.getAvailableCandidates()) { message.append(String.format(" - %s%n", candidate.getName())); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisReactiveSessionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisReactiveSessionConfiguration.java index b807f93bd7..453c84adaa 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisReactiveSessionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisReactiveSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ class RedisReactiveSessionConfiguration { void customize(SessionProperties sessionProperties, RedisSessionProperties redisSessionProperties, ServerProperties serverProperties) { Duration timeout = sessionProperties - .determineTimeout(() -> serverProperties.getReactive().getSession().getTimeout()); + .determineTimeout(() -> serverProperties.getReactive().getSession().getTimeout()); if (timeout != null) { setMaxInactiveIntervalInSeconds((int) timeout.getSeconds()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java index 3b9fb921b8..b50f11a338 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,7 +72,7 @@ class RedisSessionConfiguration { public void customize(SessionProperties sessionProperties, RedisSessionProperties redisSessionProperties, ServerProperties serverProperties) { Duration timeout = sessionProperties - .determineTimeout(() -> serverProperties.getServlet().getSession().getTimeout()); + .determineTimeout(() -> serverProperties.getServlet().getSession().getTimeout()); if (timeout != null) { setMaxInactiveIntervalInSeconds((int) timeout.getSeconds()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionAutoConfiguration.java index 9d64cf2ce3..c013ede877 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -118,7 +118,7 @@ public class SessionAutoConfiguration { @Bean DefaultCookieSerializerCustomizer rememberMeServicesCookieSerializerCustomizer() { return (cookieSerializer) -> cookieSerializer - .setRememberMeRequestAttribute(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR); + .setRememberMeRequestAttribute(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR); } } @@ -180,8 +180,8 @@ public class SessionAutoConfiguration { protected final String[] selectImports(WebApplicationType webApplicationType) { return Arrays.stream(StoreType.values()) - .map((type) -> SessionStoreMappings.getConfigurationClass(webApplicationType, type)) - .toArray(String[]::new); + .map((type) -> SessionStoreMappings.getConfigurationClass(webApplicationType, type)) + .toArray(String[]::new); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.java index 973a81d411..3338603aeb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,8 +52,10 @@ class SessionRepositoryFilterConfiguration { if (servletProperties.getFilterDispatcherTypes() == null) { return null; } - return servletProperties.getFilterDispatcherTypes().stream().map((type) -> DispatcherType.valueOf(type.name())) - .collect(Collectors.toCollection(() -> EnumSet.noneOf(DispatcherType.class))); + return servletProperties.getFilterDispatcherTypes() + .stream() + .map((type) -> DispatcherType.valueOf(type.name())) + .collect(Collectors.toCollection(() -> EnumSet.noneOf(DispatcherType.class))); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionStoreMappings.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionStoreMappings.java index f9253b9012..00dbedd05e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionStoreMappings.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionStoreMappings.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,11 +57,13 @@ final class SessionStoreMappings { } static StoreType getType(WebApplicationType webApplicationType, String configurationClass) { - return MAPPINGS.entrySet().stream() - .filter((entry) -> ObjectUtils.nullSafeEquals(configurationClass, - entry.getValue().getConfiguration(webApplicationType))) - .map(Map.Entry::getKey).findFirst() - .orElseThrow(() -> new IllegalStateException("Unknown configuration class " + configurationClass)); + return MAPPINGS.entrySet() + .stream() + .filter((entry) -> ObjectUtils.nullSafeEquals(configurationClass, + entry.getValue().getConfiguration(webApplicationType))) + .map(Map.Entry::getKey) + .findFirst() + .orElseThrow(() -> new IllegalStateException("Unknown configuration class " + configurationClass)); } private static class Configurations { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.java index 69bf55f10c..511f8e6d04 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,11 @@ class DataSourceInitializationConfiguration { private static DataSource determineDataSource(DataSource dataSource, String username, String password) { if (StringUtils.hasText(username) && StringUtils.hasText(password)) { - return DataSourceBuilder.derivedFrom(dataSource).username(username).password(password) - .type(SimpleDriverDataSource.class).build(); + return DataSourceBuilder.derivedFrom(dataSource) + .username(username) + .password(password) + .type(SimpleDriverDataSource.class) + .build(); } return dataSource; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/OnDatabaseInitializationCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/OnDatabaseInitializationCondition.java index f986b0bdc1..032a047314 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/OnDatabaseInitializationCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/OnDatabaseInitializationCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,7 +61,7 @@ public class OnDatabaseInitializationCondition extends SpringBootCondition { boolean match = match(mode); String messagePrefix = (propertyName != null) ? propertyName : "default value"; return new ConditionOutcome(match, ConditionMessage.forCondition(this.name + "Database Initialization") - .because(messagePrefix + " is " + mode)); + .because(messagePrefix + " is " + mode)); } private boolean match(DatabaseInitializationMode mode) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/R2dbcInitializationConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/R2dbcInitializationConfiguration.java index f0a6893bff..f84166cd73 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/R2dbcInitializationConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/R2dbcInitializationConfiguration.java @@ -50,8 +50,10 @@ class R2dbcInitializationConfiguration { private static ConnectionFactory determineConnectionFactory(ConnectionFactory connectionFactory, String username, String password) { if (StringUtils.hasText(username) && StringUtils.hasText(password)) { - return ConnectionFactoryBuilder.derivedFrom(connectionFactory).username(username).password(password) - .build(); + return ConnectionFactoryBuilder.derivedFrom(connectionFactory) + .username(username) + .password(password) + .build(); } return connectionFactory; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/SettingsCreator.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/SettingsCreator.java index a60c93c041..23db871a5b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/SettingsCreator.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/SettingsCreator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,8 @@ final class SettingsCreator { static DatabaseInitializationSettings createFrom(SqlInitializationProperties properties) { DatabaseInitializationSettings settings = new DatabaseInitializationSettings(); - settings.setSchemaLocations( - scriptLocations(properties.getSchemaLocations(), "schema", properties.getPlatform())); + settings + .setSchemaLocations(scriptLocations(properties.getSchemaLocations(), "schema", properties.getPlatform())); settings.setDataLocations(scriptLocations(properties.getDataLocations(), "data", properties.getPlatform())); settings.setContinueOnError(properties.isContinueOnError()); settings.setSeparator(properties.getSeparator()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/task/ScheduledBeanLazyInitializationExcludeFilter.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/task/ScheduledBeanLazyInitializationExcludeFilter.java index 644a4bcb2b..d68d513c2f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/task/ScheduledBeanLazyInitializationExcludeFilter.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/task/ScheduledBeanLazyInitializationExcludeFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,7 +64,7 @@ class ScheduledBeanLazyInitializationExcludeFilter implements LazyInitialization Map> annotatedMethods = MethodIntrospector.selectMethods(targetType, (MethodIntrospector.MetadataLookup>) (method) -> { Set scheduledAnnotations = AnnotatedElementUtils - .getMergedRepeatableAnnotations(method, Scheduled.class, Schedules.class); + .getMergedRepeatableAnnotations(method, Scheduled.class, Schedules.class); return (!scheduledAnnotations.isEmpty() ? scheduledAnnotations : null); }); if (annotatedMethods.isEmpty()) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java index c9111b2ce8..0ec34f3ca6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -209,8 +209,10 @@ public class ThymeleafAutoConfiguration { private void mapReactiveProperties(Reactive properties, ThymeleafReactiveViewResolver resolver) { PropertyMapper map = PropertyMapper.get(); map.from(properties::getMediaTypes).whenNonNull().to(resolver::setSupportedMediaTypes); - map.from(properties::getMaxChunkSize).asInt(DataSize::toBytes).when((size) -> size > 0) - .to(resolver::setResponseMaxChunkSizeBytes); + map.from(properties::getMaxChunkSize) + .asInt(DataSize::toBytes) + .when((size) -> size > 0) + .to(resolver::setResponseMaxChunkSizeBytes); map.from(properties::getFullModeViewNames).to(resolver::setFullModeViewNames); map.from(properties::getChunkedModeViewNames).to(resolver::setChunkedModeViewNames); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizers.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizers.java index 4e9b892674..2bb603c4bc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizers.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizers.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,8 @@ public class TransactionManagerCustomizers { @SuppressWarnings("unchecked") public void customize(PlatformTransactionManager transactionManager) { LambdaSafe.callbacks(PlatformTransactionManagerCustomizer.class, this.customizers, transactionManager) - .withLogger(TransactionManagerCustomizers.class) - .invoke((customizer) -> customizer.customize(transactionManager)); + .withLogger(TransactionManagerCustomizers.class) + .invoke((customizer) -> customizer.customize(transactionManager)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebProperties.java index 2127c227ff..d0ba50a51c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -574,12 +574,15 @@ public class WebProperties { map.from(this::getCachePublic).whenTrue().toCall(control::cachePublic); map.from(this::getCachePrivate).whenTrue().toCall(control::cachePrivate); map.from(this::getProxyRevalidate).whenTrue().toCall(control::proxyRevalidate); - map.from(this::getStaleWhileRevalidate).whenNonNull() - .to((duration) -> control.staleWhileRevalidate(duration.getSeconds(), TimeUnit.SECONDS)); - map.from(this::getStaleIfError).whenNonNull() - .to((duration) -> control.staleIfError(duration.getSeconds(), TimeUnit.SECONDS)); - map.from(this::getSMaxAge).whenNonNull() - .to((duration) -> control.sMaxAge(duration.getSeconds(), TimeUnit.SECONDS)); + map.from(this::getStaleWhileRevalidate) + .whenNonNull() + .to((duration) -> control.staleWhileRevalidate(duration.getSeconds(), TimeUnit.SECONDS)); + map.from(this::getStaleIfError) + .whenNonNull() + .to((duration) -> control.staleIfError(duration.getSeconds(), TimeUnit.SECONDS)); + map.from(this::getSMaxAge) + .whenNonNull() + .to((duration) -> control.sMaxAge(duration.getSeconds(), TimeUnit.SECONDS)); // check if cacheControl remained untouched if (control.getHeaderValue() == null) { return null; 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..7a179d0d22 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -82,15 +82,22 @@ public class JettyWebServerFactoryCustomizer PropertyMapper propertyMapper = PropertyMapper.get(); propertyMapper.from(threadProperties::getAcceptors).whenNonNull().to(factory::setAcceptors); propertyMapper.from(threadProperties::getSelectors).whenNonNull().to(factory::setSelectors); - propertyMapper.from(properties::getMaxHttpHeaderSize).whenNonNull().asInt(DataSize::toBytes) - .when(this::isPositive).to((maxHttpHeaderSize) -> factory - .addServerCustomizers(new MaxHttpHeaderSizeCustomizer(maxHttpHeaderSize))); - propertyMapper.from(jettyProperties::getMaxHttpFormPostSize).asInt(DataSize::toBytes).when(this::isPositive) - .to((maxHttpFormPostSize) -> customizeMaxHttpFormPostSize(factory, maxHttpFormPostSize)); - propertyMapper.from(jettyProperties::getConnectionIdleTimeout).whenNonNull() - .to((idleTimeout) -> customizeIdleTimeout(factory, idleTimeout)); - propertyMapper.from(jettyProperties::getAccesslog).when(ServerProperties.Jetty.Accesslog::isEnabled) - .to((accesslog) -> customizeAccessLog(factory, accesslog)); + propertyMapper.from(properties::getMaxHttpHeaderSize) + .whenNonNull() + .asInt(DataSize::toBytes) + .when(this::isPositive) + .to((maxHttpHeaderSize) -> factory + .addServerCustomizers(new MaxHttpHeaderSizeCustomizer(maxHttpHeaderSize))); + propertyMapper.from(jettyProperties::getMaxHttpFormPostSize) + .asInt(DataSize::toBytes) + .when(this::isPositive) + .to((maxHttpFormPostSize) -> customizeMaxHttpFormPostSize(factory, maxHttpFormPostSize)); + propertyMapper.from(jettyProperties::getConnectionIdleTimeout) + .whenNonNull() + .to((idleTimeout) -> customizeIdleTimeout(factory, idleTimeout)); + propertyMapper.from(jettyProperties::getAccesslog) + .when(ServerProperties.Jetty.Accesslog::isEnabled) + .to((accesslog) -> customizeAccessLog(factory, accesslog)); } private boolean isPositive(Integer value) { @@ -212,7 +219,7 @@ public class JettyWebServerFactoryCustomizer private void customize(ConnectionFactory factory) { if (factory instanceof HttpConfiguration.ConnectionFactory) { ((HttpConfiguration.ConnectionFactory) factory).getHttpConfiguration() - .setRequestHeaderSize(this.maxHttpHeaderSize); + .setRequestHeaderSize(this.maxHttpHeaderSize); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizer.java index 1776b8c97b..7f81f5e0ec 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,12 +58,14 @@ public class NettyWebServerFactoryCustomizer factory.setUseForwardHeaders(getOrDeduceUseForwardHeaders()); PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenNonNull(); ServerProperties.Netty nettyProperties = this.serverProperties.getNetty(); - propertyMapper.from(nettyProperties::getConnectionTimeout).whenNonNull() - .to((connectionTimeout) -> customizeConnectionTimeout(factory, connectionTimeout)); - propertyMapper.from(nettyProperties::getIdleTimeout).whenNonNull() - .to((idleTimeout) -> customizeIdleTimeout(factory, idleTimeout)); + propertyMapper.from(nettyProperties::getConnectionTimeout) + .whenNonNull() + .to((connectionTimeout) -> customizeConnectionTimeout(factory, connectionTimeout)); + propertyMapper.from(nettyProperties::getIdleTimeout) + .whenNonNull() + .to((idleTimeout) -> customizeIdleTimeout(factory, idleTimeout)); propertyMapper.from(nettyProperties::getMaxKeepAliveRequests) - .to((maxKeepAliveRequests) -> customizeMaxKeepAliveRequests(factory, maxKeepAliveRequests)); + .to((maxKeepAliveRequests) -> customizeMaxKeepAliveRequests(factory, maxKeepAliveRequests)); customizeRequestDecoder(factory, propertyMapper); } @@ -82,22 +84,28 @@ public class NettyWebServerFactoryCustomizer private void customizeRequestDecoder(NettyReactiveWebServerFactory factory, PropertyMapper propertyMapper) { factory.addServerCustomizers((httpServer) -> httpServer.httpRequestDecoder((httpRequestDecoderSpec) -> { - propertyMapper.from(this.serverProperties.getMaxHttpHeaderSize()).whenNonNull() - .to((maxHttpRequestHeader) -> httpRequestDecoderSpec - .maxHeaderSize((int) maxHttpRequestHeader.toBytes())); + propertyMapper.from(this.serverProperties.getMaxHttpHeaderSize()) + .whenNonNull() + .to((maxHttpRequestHeader) -> httpRequestDecoderSpec + .maxHeaderSize((int) maxHttpRequestHeader.toBytes())); ServerProperties.Netty nettyProperties = this.serverProperties.getNetty(); - propertyMapper.from(nettyProperties.getMaxChunkSize()).whenNonNull() - .to((maxChunkSize) -> httpRequestDecoderSpec.maxChunkSize((int) maxChunkSize.toBytes())); - propertyMapper.from(nettyProperties.getMaxInitialLineLength()).whenNonNull() - .to((maxInitialLineLength) -> httpRequestDecoderSpec - .maxInitialLineLength((int) maxInitialLineLength.toBytes())); - propertyMapper.from(nettyProperties.getH2cMaxContentLength()).whenNonNull() - .to((h2cMaxContentLength) -> httpRequestDecoderSpec - .h2cMaxContentLength((int) h2cMaxContentLength.toBytes())); - propertyMapper.from(nettyProperties.getInitialBufferSize()).whenNonNull().to( - (initialBufferSize) -> httpRequestDecoderSpec.initialBufferSize((int) initialBufferSize.toBytes())); - propertyMapper.from(nettyProperties.isValidateHeaders()).whenNonNull() - .to(httpRequestDecoderSpec::validateHeaders); + propertyMapper.from(nettyProperties.getMaxChunkSize()) + .whenNonNull() + .to((maxChunkSize) -> httpRequestDecoderSpec.maxChunkSize((int) maxChunkSize.toBytes())); + propertyMapper.from(nettyProperties.getMaxInitialLineLength()) + .whenNonNull() + .to((maxInitialLineLength) -> httpRequestDecoderSpec + .maxInitialLineLength((int) maxInitialLineLength.toBytes())); + propertyMapper.from(nettyProperties.getH2cMaxContentLength()) + .whenNonNull() + .to((h2cMaxContentLength) -> httpRequestDecoderSpec + .h2cMaxContentLength((int) h2cMaxContentLength.toBytes())); + propertyMapper.from(nettyProperties.getInitialBufferSize()) + .whenNonNull() + .to((initialBufferSize) -> httpRequestDecoderSpec.initialBufferSize((int) initialBufferSize.toBytes())); + propertyMapper.from(nettyProperties.isValidateHeaders()) + .whenNonNull() + .to(httpRequestDecoderSpec::validateHeaders); return httpRequestDecoderSpec; })); } 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 deb41dff14..2705680328 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -84,43 +84,62 @@ public class TomcatWebServerFactoryCustomizer ServerProperties.Tomcat tomcatProperties = properties.getTomcat(); PropertyMapper propertyMapper = PropertyMapper.get(); propertyMapper.from(tomcatProperties::getBasedir).whenNonNull().to(factory::setBaseDirectory); - propertyMapper.from(tomcatProperties::getBackgroundProcessorDelay).whenNonNull().as(Duration::getSeconds) - .as(Long::intValue).to(factory::setBackgroundProcessorDelay); + propertyMapper.from(tomcatProperties::getBackgroundProcessorDelay) + .whenNonNull() + .as(Duration::getSeconds) + .as(Long::intValue) + .to(factory::setBackgroundProcessorDelay); customizeRemoteIpValve(factory); ServerProperties.Tomcat.Threads threadProperties = tomcatProperties.getThreads(); - propertyMapper.from(threadProperties::getMax).when(this::isPositive) - .to((maxThreads) -> customizeMaxThreads(factory, threadProperties.getMax())); - propertyMapper.from(threadProperties::getMinSpare).when(this::isPositive) - .to((minSpareThreads) -> customizeMinThreads(factory, minSpareThreads)); - propertyMapper.from(this.serverProperties.getMaxHttpHeaderSize()).whenNonNull().asInt(DataSize::toBytes) - .when(this::isPositive) - .to((maxHttpHeaderSize) -> customizeMaxHttpHeaderSize(factory, maxHttpHeaderSize)); - propertyMapper.from(tomcatProperties::getMaxSwallowSize).whenNonNull().asInt(DataSize::toBytes) - .to((maxSwallowSize) -> customizeMaxSwallowSize(factory, maxSwallowSize)); - propertyMapper.from(tomcatProperties::getMaxHttpFormPostSize).asInt(DataSize::toBytes) - .when((maxHttpFormPostSize) -> maxHttpFormPostSize != 0) - .to((maxHttpFormPostSize) -> customizeMaxHttpFormPostSize(factory, maxHttpFormPostSize)); - propertyMapper.from(tomcatProperties::getAccesslog).when(ServerProperties.Tomcat.Accesslog::isEnabled) - .to((enabled) -> customizeAccessLog(factory)); + propertyMapper.from(threadProperties::getMax) + .when(this::isPositive) + .to((maxThreads) -> customizeMaxThreads(factory, threadProperties.getMax())); + propertyMapper.from(threadProperties::getMinSpare) + .when(this::isPositive) + .to((minSpareThreads) -> customizeMinThreads(factory, minSpareThreads)); + propertyMapper.from(this.serverProperties.getMaxHttpHeaderSize()) + .whenNonNull() + .asInt(DataSize::toBytes) + .when(this::isPositive) + .to((maxHttpHeaderSize) -> customizeMaxHttpHeaderSize(factory, maxHttpHeaderSize)); + propertyMapper.from(tomcatProperties::getMaxSwallowSize) + .whenNonNull() + .asInt(DataSize::toBytes) + .to((maxSwallowSize) -> customizeMaxSwallowSize(factory, maxSwallowSize)); + propertyMapper.from(tomcatProperties::getMaxHttpFormPostSize) + .asInt(DataSize::toBytes) + .when((maxHttpFormPostSize) -> maxHttpFormPostSize != 0) + .to((maxHttpFormPostSize) -> customizeMaxHttpFormPostSize(factory, maxHttpFormPostSize)); + propertyMapper.from(tomcatProperties::getAccesslog) + .when(ServerProperties.Tomcat.Accesslog::isEnabled) + .to((enabled) -> customizeAccessLog(factory)); propertyMapper.from(tomcatProperties::getUriEncoding).whenNonNull().to(factory::setUriEncoding); - propertyMapper.from(tomcatProperties::getConnectionTimeout).whenNonNull() - .to((connectionTimeout) -> customizeConnectionTimeout(factory, connectionTimeout)); - propertyMapper.from(tomcatProperties::getMaxConnections).when(this::isPositive) - .to((maxConnections) -> customizeMaxConnections(factory, maxConnections)); - propertyMapper.from(tomcatProperties::getAcceptCount).when(this::isPositive) - .to((acceptCount) -> customizeAcceptCount(factory, acceptCount)); + propertyMapper.from(tomcatProperties::getConnectionTimeout) + .whenNonNull() + .to((connectionTimeout) -> customizeConnectionTimeout(factory, connectionTimeout)); + propertyMapper.from(tomcatProperties::getMaxConnections) + .when(this::isPositive) + .to((maxConnections) -> customizeMaxConnections(factory, maxConnections)); + propertyMapper.from(tomcatProperties::getAcceptCount) + .when(this::isPositive) + .to((acceptCount) -> customizeAcceptCount(factory, acceptCount)); propertyMapper.from(tomcatProperties::getProcessorCache) - .to((processorCache) -> customizeProcessorCache(factory, processorCache)); - propertyMapper.from(tomcatProperties::getKeepAliveTimeout).whenNonNull() - .to((keepAliveTimeout) -> customizeKeepAliveTimeout(factory, keepAliveTimeout)); + .to((processorCache) -> customizeProcessorCache(factory, processorCache)); + propertyMapper.from(tomcatProperties::getKeepAliveTimeout) + .whenNonNull() + .to((keepAliveTimeout) -> customizeKeepAliveTimeout(factory, keepAliveTimeout)); propertyMapper.from(tomcatProperties::getMaxKeepAliveRequests) - .to((maxKeepAliveRequests) -> customizeMaxKeepAliveRequests(factory, maxKeepAliveRequests)); - propertyMapper.from(tomcatProperties::getRelaxedPathChars).as(this::joinCharacters).whenHasText() - .to((relaxedChars) -> customizeRelaxedPathChars(factory, relaxedChars)); - propertyMapper.from(tomcatProperties::getRelaxedQueryChars).as(this::joinCharacters).whenHasText() - .to((relaxedChars) -> customizeRelaxedQueryChars(factory, relaxedChars)); + .to((maxKeepAliveRequests) -> customizeMaxKeepAliveRequests(factory, maxKeepAliveRequests)); + propertyMapper.from(tomcatProperties::getRelaxedPathChars) + .as(this::joinCharacters) + .whenHasText() + .to((relaxedChars) -> customizeRelaxedPathChars(factory, relaxedChars)); + propertyMapper.from(tomcatProperties::getRelaxedQueryChars) + .as(this::joinCharacters) + .whenHasText() + .to((relaxedChars) -> customizeRelaxedQueryChars(factory, relaxedChars)); propertyMapper.from(tomcatProperties::isRejectIllegalHeader) - .to((rejectIllegalHeader) -> customizeRejectIllegalHeader(factory, rejectIllegalHeader)); + .to((rejectIllegalHeader) -> customizeRejectIllegalHeader(factory, rejectIllegalHeader)); customizeStaticResources(factory); customizeErrorReportValve(properties.getError(), factory); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizer.java index 8f291b1a22..95f0bb3afe 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -78,8 +78,10 @@ public class UndertowWebServerFactoryCustomizer PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); ServerOptions options = new ServerOptions(factory); ServerProperties properties = this.serverProperties; - map.from(properties::getMaxHttpHeaderSize).asInt(DataSize::toBytes).when(this::isPositive) - .to(options.option(UndertowOptions.MAX_HEADER_SIZE)); + map.from(properties::getMaxHttpHeaderSize) + .asInt(DataSize::toBytes) + .when(this::isPositive) + .to(options.option(UndertowOptions.MAX_HEADER_SIZE)); mapUndertowProperties(factory, options); mapAccessLogProperties(factory); map.from(this::getOrDeduceUseForwardHeaders).to(factory::setUseForwardHeaders); @@ -93,8 +95,10 @@ public class UndertowWebServerFactoryCustomizer map.from(threadProperties::getIo).to(factory::setIoThreads); map.from(threadProperties::getWorker).to(factory::setWorkerThreads); map.from(properties::getDirectBuffers).to(factory::setUseDirectBuffers); - map.from(properties::getMaxHttpPostSize).as(DataSize::toBytes).when(this::isPositive) - .to(serverOptions.option(UndertowOptions.MAX_ENTITY_SIZE)); + map.from(properties::getMaxHttpPostSize) + .as(DataSize::toBytes) + .when(this::isPositive) + .to(serverOptions.option(UndertowOptions.MAX_ENTITY_SIZE)); map.from(properties::getMaxParameters).to(serverOptions.option(UndertowOptions.MAX_PARAMETERS)); map.from(properties::getMaxHeaders).to(serverOptions.option(UndertowOptions.MAX_HEADERS)); map.from(properties::getMaxCookies).to(serverOptions.option(UndertowOptions.MAX_COOKIES)); @@ -102,8 +106,9 @@ public class UndertowWebServerFactoryCustomizer map.from(properties::isDecodeUrl).to(serverOptions.option(UndertowOptions.DECODE_URL)); map.from(properties::getUrlCharset).as(Charset::name).to(serverOptions.option(UndertowOptions.URL_CHARSET)); map.from(properties::isAlwaysSetKeepAlive).to(serverOptions.option(UndertowOptions.ALWAYS_SET_KEEP_ALIVE)); - map.from(properties::getNoRequestTimeout).asInt(Duration::toMillis) - .to(serverOptions.option(UndertowOptions.NO_REQUEST_TIMEOUT)); + map.from(properties::getNoRequestTimeout) + .asInt(Duration::toMillis) + .to(serverOptions.option(UndertowOptions.NO_REQUEST_TIMEOUT)); map.from(properties.getOptions()::getServer).to(serverOptions.forEach(serverOptions::option)); SocketOptions socketOptions = new SocketOptions(factory); map.from(properties.getOptions()::getSocket).to(socketOptions.forEach(socketOptions::option)); @@ -176,8 +181,10 @@ public class UndertowWebServerFactoryCustomizer private static String getCanonicalName(String name) { StringBuilder canonicalName = new StringBuilder(name.length()); - name.chars().filter(Character::isLetterOrDigit).map(Character::toLowerCase) - .forEach((c) -> canonicalName.append((char) c)); + name.chars() + .filter(Character::isLetterOrDigit) + .map(Character::toLowerCase) + .forEach((c) -> canonicalName.append((char) c)); return canonicalName.toString(); } 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..6ce32747e3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,16 +55,20 @@ public class ReactiveMultipartAutoConfiguration { if (codec instanceof DefaultPartHttpMessageReader) { DefaultPartHttpMessageReader defaultPartHttpMessageReader = (DefaultPartHttpMessageReader) codec; PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); - map.from(multipartProperties::getMaxInMemorySize).asInt(DataSize::toBytes) - .to(defaultPartHttpMessageReader::setMaxInMemorySize); - map.from(multipartProperties::getMaxHeadersSize).asInt(DataSize::toBytes) - .to(defaultPartHttpMessageReader::setMaxHeadersSize); - map.from(multipartProperties::getMaxDiskUsagePerPart).asInt(DataSize::toBytes) - .to(defaultPartHttpMessageReader::setMaxDiskUsagePerPart); + map.from(multipartProperties::getMaxInMemorySize) + .asInt(DataSize::toBytes) + .to(defaultPartHttpMessageReader::setMaxInMemorySize); + map.from(multipartProperties::getMaxHeadersSize) + .asInt(DataSize::toBytes) + .to(defaultPartHttpMessageReader::setMaxHeadersSize); + map.from(multipartProperties::getMaxDiskUsagePerPart) + .asInt(DataSize::toBytes) + .to(defaultPartHttpMessageReader::setMaxDiskUsagePerPart); map.from(multipartProperties::getMaxParts).to(defaultPartHttpMessageReader::setMaxParts); map.from(multipartProperties::getStreaming).to(defaultPartHttpMessageReader::setStreaming); - map.from(multipartProperties::getFileStorageDirectory).as(Paths::get) - .to((dir) -> configureFileStorageDirectory(defaultPartHttpMessageReader, dir)); + map.from(multipartProperties::getFileStorageDirectory) + .as(Paths::get) + .to((dir) -> configureFileStorageDirectory(defaultPartHttpMessageReader, dir)); map.from(multipartProperties::getHeadersCharset).to(defaultPartHttpMessageReader::setHeadersCharset); } }); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryConfiguration.java index e76489d901..8663385d00 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryConfiguration.java @@ -86,11 +86,11 @@ abstract class ReactiveWebServerFactoryConfiguration { ObjectProvider> protocolHandlerCustomizers) { TomcatReactiveWebServerFactory factory = new TomcatReactiveWebServerFactory(); factory.getTomcatConnectorCustomizers() - .addAll(connectorCustomizers.orderedStream().collect(Collectors.toList())); + .addAll(connectorCustomizers.orderedStream().collect(Collectors.toList())); factory.getTomcatContextCustomizers() - .addAll(contextCustomizers.orderedStream().collect(Collectors.toList())); + .addAll(contextCustomizers.orderedStream().collect(Collectors.toList())); factory.getTomcatProtocolHandlerCustomizers() - .addAll(protocolHandlerCustomizers.orderedStream().collect(Collectors.toList())); + .addAll(protocolHandlerCustomizers.orderedStream().collect(Collectors.toList())); return factory; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfiguration.java index ab7d5c906e..c078cc2515 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -188,14 +188,14 @@ public class WebFluxAutoConfiguration { } if (!registry.hasMappingForPattern("/webjars/**")) { ResourceHandlerRegistration registration = registry.addResourceHandler("/webjars/**") - .addResourceLocations("classpath:/META-INF/resources/webjars/"); + .addResourceLocations("classpath:/META-INF/resources/webjars/"); configureResourceCaching(registration); customizeResourceHandlerRegistration(registration); } String staticPathPattern = this.webFluxProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { ResourceHandlerRegistration registration = registry.addResourceHandler(staticPathPattern) - .addResourceLocations(this.resourceProperties.getStaticLocations()); + .addResourceLocations(this.resourceProperties.getStaticLocations()); configureResourceCaching(registration); customizeResourceHandlerRegistration(registration); } @@ -204,7 +204,7 @@ public class WebFluxAutoConfiguration { private void configureResourceCaching(ResourceHandlerRegistration registration) { Duration cachePeriod = this.resourceProperties.getCache().getPeriod(); WebProperties.Resources.Cache.Cachecontrol cacheControl = this.resourceProperties.getCache() - .getCachecontrol(); + .getCachecontrol(); if (cachePeriod != null && cacheControl.getMaxAge() == null) { cacheControl.setMaxAge(cachePeriod); } @@ -257,8 +257,10 @@ public class WebFluxAutoConfiguration { @Override public FormattingConversionService webFluxConversionService() { Format format = this.webFluxProperties.getFormat(); - WebConversionService conversionService = new WebConversionService(new DateTimeFormatters() - .dateFormat(format.getDate()).timeFormat(format.getTime()).dateTimeFormat(format.getDateTime())); + WebConversionService conversionService = new WebConversionService( + new DateTimeFormatters().dateFormat(format.getDate()) + .timeFormat(format.getTime()) + .dateTimeFormat(format.getDateTime())); addFormatters(conversionService); return conversionService; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxProperties.java index d85e567dea..b8f962a736 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -169,6 +169,7 @@ public class WebFluxProperties { /** * SameSite values. + * * @deprecated since 2.6.0 for removal in 3.0.0 in favor of * {@link org.springframework.boot.web.server.Cookie.SameSite}. */ diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WelcomePageRouterFunctionFactory.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WelcomePageRouterFunctionFactory.java index 656ff43420..677c4cc0d1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WelcomePageRouterFunctionFactory.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WelcomePageRouterFunctionFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,8 +53,11 @@ final class WelcomePageRouterFunctionFactory { } private Resource getWelcomePage(ResourceLoader resourceLoader, String[] staticLocations) { - return Arrays.stream(staticLocations).map((location) -> getIndexHtml(resourceLoader, location)) - .filter(this::isReadable).findFirst().orElse(null); + return Arrays.stream(staticLocations) + .map((location) -> getIndexHtml(resourceLoader, location)) + .filter(this::isReadable) + .findFirst() + .orElse(null); } private Resource getIndexHtml(ResourceLoader resourceLoader, String location) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/AbstractErrorWebExceptionHandler.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/AbstractErrorWebExceptionHandler.java index 5cb3291fc3..fa0f71e2eb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/AbstractErrorWebExceptionHandler.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/AbstractErrorWebExceptionHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -262,10 +262,17 @@ public abstract class AbstractErrorWebExceptionHandler implements ErrorWebExcept Object trace = error.get("trace"); Object requestId = error.get("requestId"); builder.append("

Whitelabel Error Page

") - .append("

This application has no configured error view, so you are seeing this as a fallback.

") - .append("
").append(timestamp).append("
").append("
[").append(requestId) - .append("] There was an unexpected error (type=").append(htmlEscape(error.get("error"))) - .append(", status=").append(htmlEscape(error.get("status"))).append(").
"); + .append("

This application has no configured error view, so you are seeing this as a fallback.

") + .append("
") + .append(timestamp) + .append("
") + .append("
[") + .append(requestId) + .append("] There was an unexpected error (type=") + .append(htmlEscape(error.get("error"))) + .append(", status=") + .append(htmlEscape(error.get("status"))) + .append(").
"); if (message != null) { builder.append("
").append(htmlEscape(message)).append("
"); } @@ -307,10 +314,11 @@ public abstract class AbstractErrorWebExceptionHandler implements ErrorWebExcept } this.errorAttributes.storeErrorInformation(throwable, exchange); ServerRequest request = ServerRequest.create(exchange, this.messageReaders); - return getRoutingFunction(this.errorAttributes).route(request).switchIfEmpty(Mono.error(throwable)) - .flatMap((handler) -> handler.handle(request)) - .doOnNext((response) -> logError(request, response, throwable)) - .flatMap((response) -> write(exchange, response)); + return getRoutingFunction(this.errorAttributes).route(request) + .switchIfEmpty(Mono.error(throwable)) + .flatMap((handler) -> handler.handle(request)) + .doOnNext((response) -> logError(request, response, throwable)) + .flatMap((response) -> write(exchange, response)); } private boolean isDisconnectedClientError(Throwable ex) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandler.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandler.java index 4ea6aa4f27..c91f3cf0f2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandler.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -120,10 +120,10 @@ public class DefaultErrorWebExceptionHandler extends AbstractErrorWebExceptionHa int errorStatus = getHttpStatus(error); ServerResponse.BodyBuilder responseBody = ServerResponse.status(errorStatus).contentType(TEXT_HTML_UTF8); return Flux.just(getData(errorStatus).toArray(new String[] {})) - .flatMap((viewName) -> renderErrorView(viewName, responseBody, error)) - .switchIfEmpty(this.errorProperties.getWhitelabel().isEnabled() - ? renderDefaultErrorView(responseBody, error) : Mono.error(getError(request))) - .next(); + .flatMap((viewName) -> renderErrorView(viewName, responseBody, error)) + .switchIfEmpty(this.errorProperties.getWhitelabel().isEnabled() + ? renderDefaultErrorView(responseBody, error) : Mono.error(getError(request))) + .next(); } private List getData(int errorStatus) { @@ -144,8 +144,9 @@ public class DefaultErrorWebExceptionHandler extends AbstractErrorWebExceptionHa */ protected Mono renderErrorResponse(ServerRequest request) { Map error = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL)); - return ServerResponse.status(getHttpStatus(error)).contentType(MediaType.APPLICATION_JSON) - .body(BodyInserters.fromValue(error)); + return ServerResponse.status(getHttpStatus(error)) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(error)); } protected ErrorAttributeOptions getErrorAttributeOptions(ServerRequest request, MediaType mediaType) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorConfiguration.java index 09a92996a7..85ec0c5392 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorConfiguration.java @@ -58,8 +58,8 @@ class ClientHttpConnectorConfiguration { ReactorClientHttpConnector reactorClientHttpConnector(ReactorResourceFactory reactorResourceFactory, ObjectProvider mapperProvider) { ReactorNettyHttpClientMapper mapper = mapperProvider.orderedStream() - .reduce((before, after) -> (client) -> after.configure(before.configure(client))) - .orElse((client) -> client); + .reduce((before, after) -> (client) -> after.configure(before.configure(client))) + .orElse((client) -> client); return new ReactorClientHttpConnector(reactorResourceFactory, mapper::configure); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientCodecCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientCodecCustomizer.java index 8a812baa6b..548bbee818 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientCodecCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientCodecCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ public class WebClientCodecCustomizer implements WebClientCustomizer { @Override public void customize(WebClient.Builder webClientBuilder) { webClientBuilder - .codecs((codecs) -> this.codecCustomizers.forEach((customizer) -> customizer.customize(codecs))); + .codecs((codecs) -> this.codecCustomizers.forEach((customizer) -> customizer.customize(codecs))); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DefaultJerseyApplicationPath.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DefaultJerseyApplicationPath.java index 438acedaaf..b1ae0dc442 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DefaultJerseyApplicationPath.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DefaultJerseyApplicationPath.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,7 +55,9 @@ public class DefaultJerseyApplicationPath implements JerseyApplicationPath { } // Jersey doesn't like to be the default servlet, so map to /* as a fallback return MergedAnnotations.from(this.config.getApplication().getClass(), SearchStrategy.TYPE_HIERARCHY) - .get(ApplicationPath.class).getValue(MergedAnnotation.VALUE, String.class).orElse("/*"); + .get(ApplicationPath.class) + .getValue(MergedAnnotation.VALUE, String.class) + .orElse("/*"); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfiguration.java index ff2fac8d17..3e367c5bea 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -134,21 +134,21 @@ public class DispatcherServletAutoConfiguration { ConditionMessage.Builder message = ConditionMessage.forCondition("Default DispatcherServlet"); ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); List dispatchServletBeans = Arrays - .asList(beanFactory.getBeanNamesForType(DispatcherServlet.class, false, false)); + .asList(beanFactory.getBeanNamesForType(DispatcherServlet.class, false, false)); if (dispatchServletBeans.contains(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) { return ConditionOutcome - .noMatch(message.found("dispatcher servlet bean").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); + .noMatch(message.found("dispatcher servlet bean").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); } if (beanFactory.containsBean(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) { - return ConditionOutcome.noMatch( - message.found("non dispatcher servlet bean").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); + return ConditionOutcome + .noMatch(message.found("non dispatcher servlet bean").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); } if (dispatchServletBeans.isEmpty()) { return ConditionOutcome.match(message.didNotFind("dispatcher servlet beans").atAll()); } return ConditionOutcome.match(message.found("dispatcher servlet bean", "dispatcher servlet beans") - .items(Style.QUOTE, dispatchServletBeans) - .append("and none is named " + DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); + .items(Style.QUOTE, dispatchServletBeans) + .append("and none is named " + DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); } } @@ -172,7 +172,7 @@ public class DispatcherServletAutoConfiguration { return ConditionOutcome.match(); } List servlets = Arrays - .asList(beanFactory.getBeanNamesForType(DispatcherServlet.class, false, false)); + .asList(beanFactory.getBeanNamesForType(DispatcherServlet.class, false, false)); if (!servlets.contains(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) { return ConditionOutcome.noMatch( startMessage().found("non dispatcher servlet").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); @@ -183,26 +183,27 @@ public class DispatcherServletAutoConfiguration { private ConditionOutcome checkServletRegistration(ConfigurableListableBeanFactory beanFactory) { ConditionMessage.Builder message = startMessage(); List registrations = Arrays - .asList(beanFactory.getBeanNamesForType(ServletRegistrationBean.class, false, false)); + .asList(beanFactory.getBeanNamesForType(ServletRegistrationBean.class, false, false)); boolean containsDispatcherRegistrationBean = beanFactory - .containsBean(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME); + .containsBean(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME); if (registrations.isEmpty()) { if (containsDispatcherRegistrationBean) { return ConditionOutcome.noMatch(message.found("non servlet registration bean") - .items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); + .items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); } return ConditionOutcome.match(message.didNotFind("servlet registration bean").atAll()); } if (registrations.contains(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)) { return ConditionOutcome.noMatch(message.found("servlet registration bean") - .items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); + .items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); } if (containsDispatcherRegistrationBean) { return ConditionOutcome.noMatch(message.found("non servlet registration bean") - .items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); + .items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); } - return ConditionOutcome.match(message.found("servlet registration beans").items(Style.QUOTE, registrations) - .append("and none is named " + DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); + return ConditionOutcome.match(message.found("servlet registration beans") + .items(Style.QUOTE, registrations) + .append("and none is named " + DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); } private ConditionMessage.Builder startMessage() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration.java index 13a6c6a3ea..1fef29b2f5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -75,11 +75,11 @@ class ServletWebServerFactoryConfiguration { ObjectProvider> protocolHandlerCustomizers) { TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); factory.getTomcatConnectorCustomizers() - .addAll(connectorCustomizers.orderedStream().collect(Collectors.toList())); + .addAll(connectorCustomizers.orderedStream().collect(Collectors.toList())); factory.getTomcatContextCustomizers() - .addAll(contextCustomizers.orderedStream().collect(Collectors.toList())); + .addAll(contextCustomizers.orderedStream().collect(Collectors.toList())); factory.getTomcatProtocolHandlerCustomizers() - .addAll(protocolHandlerCustomizers.orderedStream().collect(Collectors.toList())); + .addAll(protocolHandlerCustomizers.orderedStream().collect(Collectors.toList())); return factory; } @@ -117,7 +117,7 @@ class ServletWebServerFactoryConfiguration { ObjectProvider builderCustomizers) { UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory(); factory.getDeploymentInfoCustomizers() - .addAll(deploymentInfoCustomizers.orderedStream().collect(Collectors.toList())); + .addAll(deploymentInfoCustomizers.orderedStream().collect(Collectors.toList())); factory.getBuilderCustomizers().addAll(builderCustomizers.orderedStream().collect(Collectors.toList())); return factory; } 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 39df1f1738..f7ffc9f23d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -227,14 +227,14 @@ public class WebMvcAutoConfiguration { @Override public void configureMessageConverters(List> converters) { this.messageConvertersProvider - .ifAvailable((customConverters) -> converters.addAll(customConverters.getConverters())); + .ifAvailable((customConverters) -> converters.addAll(customConverters.getConverters())); } @Override public void configureAsyncSupport(AsyncSupportConfigurer configurer) { if (this.beanFactory.containsBean(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME)) { Object taskExecutor = this.beanFactory - .getBean(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME); + .getBean(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME); if (taskExecutor instanceof AsyncTaskExecutor) { configurer.setTaskExecutor(((AsyncTaskExecutor) taskExecutor)); } @@ -248,12 +248,12 @@ public class WebMvcAutoConfiguration { @Override public void configurePathMatch(PathMatchConfigurer configurer) { if (this.mvcProperties.getPathmatch() - .getMatchingStrategy() == WebMvcProperties.MatchingStrategy.PATH_PATTERN_PARSER) { + .getMatchingStrategy() == WebMvcProperties.MatchingStrategy.PATH_PATTERN_PARSER) { configurer.setPatternParser(pathPatternParser); } configurer.setUseSuffixPatternMatch(this.mvcProperties.getPathmatch().isUseSuffixPattern()); - configurer.setUseRegisteredSuffixPatternMatch( - this.mvcProperties.getPathmatch().isUseRegisteredSuffixPattern()); + configurer + .setUseRegisteredSuffixPatternMatch(this.mvcProperties.getPathmatch().isUseRegisteredSuffixPattern()); this.dispatcherServletPath.ifAvailable((dispatcherPath) -> { String servletUrlMapping = dispatcherPath.getServletUrlMapping(); if (servletUrlMapping.equals("/") && singleDispatcherServlet()) { @@ -265,8 +265,10 @@ public class WebMvcAutoConfiguration { } private boolean singleDispatcherServlet() { - return this.servletRegistrations.stream().map(ServletRegistrationBean::getServlet) - .filter(DispatcherServlet.class::isInstance).count() == 1; + return this.servletRegistrations.stream() + .map(ServletRegistrationBean::getServlet) + .filter(DispatcherServlet.class::isInstance) + .count() == 1; } @Override @@ -503,8 +505,10 @@ public class WebMvcAutoConfiguration { @Override public FormattingConversionService mvcConversionService() { Format format = this.mvcProperties.getFormat(); - WebConversionService conversionService = new WebConversionService(new DateTimeFormatters() - .dateFormat(format.getDate()).timeFormat(format.getTime()).dateTimeFormat(format.getDateTime())); + WebConversionService conversionService = new WebConversionService( + new DateTimeFormatters().dateFormat(format.getDate()) + .timeFormat(format.getTime()) + .dateTimeFormat(format.getDateTime())); addFormatters(conversionService); return conversionService; } @@ -544,7 +548,7 @@ public class WebMvcAutoConfiguration { protected ExceptionHandlerExceptionResolver createExceptionHandlerExceptionResolver() { if (this.mvcRegistrations != null) { ExceptionHandlerExceptionResolver resolver = this.mvcRegistrations - .getExceptionHandlerExceptionResolver(); + .getExceptionHandlerExceptionResolver(); if (resolver != null) { return resolver; } @@ -654,7 +658,7 @@ public class WebMvcAutoConfiguration { @SuppressWarnings("deprecation") private static final String SKIP_ATTRIBUTE = org.springframework.web.accept.PathExtensionContentNegotiationStrategy.class - .getName() + ".SKIP"; + .getName() + ".SKIP"; private final ContentNegotiationStrategy delegate; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcProperties.java index 00c5f161a9..c2f8f0ef3d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -498,6 +498,7 @@ public class WebMvcProperties { /** * Matching strategy options. + * * @since 2.4.0 */ public enum MatchingStrategy { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorController.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorController.java index 5949e37dc8..c65f4cd292 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorController.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorController.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,7 +85,7 @@ public class BasicErrorController extends AbstractErrorController { public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { HttpStatus status = getStatus(request); Map model = Collections - .unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML))); + .unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML))); response.setStatus(status.value()); ModelAndView modelAndView = resolveErrorView(request, response, status, model); return (modelAndView != null) ? modelAndView : new ModelAndView("error", model); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.java index ed24e0d000..3e0a278c37 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.java @@ -212,11 +212,16 @@ public class ErrorMvcAutoConfiguration { if (response.getContentType() == null) { response.setContentType(getContentType()); } - builder.append("

Whitelabel Error Page

").append( - "

This application has no explicit mapping for /error, so you are seeing this as a fallback.

") - .append("
").append(timestamp).append("
") - .append("
There was an unexpected error (type=").append(htmlEscape(model.get("error"))) - .append(", status=").append(htmlEscape(model.get("status"))).append(").
"); + builder.append("

Whitelabel Error Page

") + .append("

This application has no explicit mapping for /error, so you are seeing this as a fallback.

") + .append("
") + .append(timestamp) + .append("
") + .append("
There was an unexpected error (type=") + .append(htmlEscape(model.get("error"))) + .append(", status=") + .append(htmlEscape(model.get("status"))) + .append(").
"); if (message != null) { builder.append("
").append(htmlEscape(message)).append("
"); } @@ -289,7 +294,7 @@ public class ErrorMvcAutoConfiguration { for (String errorControllerBean : errorControllerBeans) { try { beanFactory.getBeanDefinition(errorControllerBean) - .setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE); + .setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE); } catch (Throwable ex) { // Ignore diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfiguration.java index 69edbc4ede..77f7a6b9e1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -108,7 +108,7 @@ public class WebServicesAutoConfiguration { public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { Binder binder = Binder.get(this.applicationContext.getEnvironment()); List wsdlLocations = binder.bind("spring.webservices.wsdl-locations", Bindable.listOf(String.class)) - .orElse(Collections.emptyList()); + .orElse(Collections.emptyList()); for (String wsdlLocation : wsdlLocations) { registerBeans(wsdlLocation, "*.wsdl", SimpleWsdl11Definition.class, SimpleWsdl11Definition::new, registry); @@ -124,7 +124,8 @@ public class WebServicesAutoConfiguration { Function beanSupplier, BeanDefinitionRegistry registry) { for (Resource resource : getResources(location, pattern)) { BeanDefinition beanDefinition = BeanDefinitionBuilder - .genericBeanDefinition(type, () -> beanSupplier.apply(resource)).getBeanDefinition(); + .genericBeanDefinition(type, () -> beanSupplier.apply(resource)) + .getBeanDefinition(); registry.registerBeanDefinition(StringUtils.stripFilenameExtension(resource.getFilename()), beanDefinition); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfiguration.java index 65f59c7dd2..f5864514ac 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ public class WebServiceTemplateAutoConfiguration { ObjectProvider webServiceTemplateCustomizers) { WebServiceTemplateBuilder builder = new WebServiceTemplateBuilder(); List customizers = webServiceTemplateCustomizers.orderedStream() - .collect(Collectors.toList()); + .collect(Collectors.toList()); if (!customizers.isEmpty()) { builder = builder.customizers(customizers); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/Jetty10WebSocketServletWebServerCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/Jetty10WebSocketServletWebServerCustomizer.java index f8376cc07f..956755493d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/Jetty10WebSocketServletWebServerCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/Jetty10WebSocketServletWebServerCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,7 +71,7 @@ class Jetty10WebSocketServletWebServerCustomizer private void ensureWebSocketComponents(Server server, ServletContext servletContext) throws ClassNotFoundException { Class webSocketServerComponents = ClassUtils - .forName("org.eclipse.jetty.websocket.core.server.WebSocketServerComponents", null); + .forName("org.eclipse.jetty.websocket.core.server.WebSocketServerComponents", null); Method ensureWebSocketComponents = ReflectionUtils.findMethod(webSocketServerComponents, "ensureWebSocketComponents", Server.class, ServletContext.class); ReflectionUtils.invokeMethod(ensureWebSocketComponents, null, server, servletContext); @@ -84,7 +84,7 @@ class Jetty10WebSocketServletWebServerCustomizer private void ensureUpgradeFilter(ServletContext servletContext) throws ClassNotFoundException { Class webSocketUpgradeFilter = ClassUtils - .forName("org.eclipse.jetty.websocket.servlet.WebSocketUpgradeFilter", null); + .forName("org.eclipse.jetty.websocket.servlet.WebSocketUpgradeFilter", null); Method ensureFilter = ReflectionUtils.findMethod(webSocketUpgradeFilter, "ensureFilter", ServletContext.class); ReflectionUtils.invokeMethod(ensureFilter, null, servletContext); @@ -92,7 +92,7 @@ class Jetty10WebSocketServletWebServerCustomizer private void ensureMappings(ServletContext servletContext) throws ClassNotFoundException { Class webSocketMappings = ClassUtils - .forName("org.eclipse.jetty.websocket.core.server.WebSocketMappings", null); + .forName("org.eclipse.jetty.websocket.core.server.WebSocketMappings", null); Method ensureMappings = ReflectionUtils.findMethod(webSocketMappings, "ensureMappings", ServletContext.class); ReflectionUtils.invokeMethod(ensureMappings, null, servletContext); 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..326395d058 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,28 +39,29 @@ import static org.assertj.core.api.Assertions.assertThat; class AbstractDependsOnBeanFactoryPostProcessorTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(FooBarConfiguration.class); + .withUserConfiguration(FooBarConfiguration.class); @Test void fooBeansShouldDependOnBarBeanNames() { this.contextRunner - .withUserConfiguration(FooDependsOnBarNamePostProcessor.class, FooBarFactoryBeanConfiguration.class) - .run(this::assertThatFooDependsOnBar); + .withUserConfiguration(FooDependsOnBarNamePostProcessor.class, FooBarFactoryBeanConfiguration.class) + .run(this::assertThatFooDependsOnBar); } @Test void fooBeansShouldDependOnBarBeanTypes() { this.contextRunner - .withUserConfiguration(FooDependsOnBarTypePostProcessor.class, FooBarFactoryBeanConfiguration.class) - .run(this::assertThatFooDependsOnBar); + .withUserConfiguration(FooDependsOnBarTypePostProcessor.class, FooBarFactoryBeanConfiguration.class) + .run(this::assertThatFooDependsOnBar); } @Test void fooBeansShouldDependOnBarBeanNamesParentContext() { try (AnnotationConfigApplicationContext parentContext = new AnnotationConfigApplicationContext( FooBarFactoryBeanConfiguration.class)) { - this.contextRunner.withUserConfiguration(FooDependsOnBarNamePostProcessor.class).withParent(parentContext) - .run(this::assertThatFooDependsOnBar); + this.contextRunner.withUserConfiguration(FooDependsOnBarNamePostProcessor.class) + .withParent(parentContext) + .run(this::assertThatFooDependsOnBar); } } @@ -68,8 +69,9 @@ class AbstractDependsOnBeanFactoryPostProcessorTests { void fooBeansShouldDependOnBarBeanTypesParentContext() { try (AnnotationConfigApplicationContext parentContext = new AnnotationConfigApplicationContext( FooBarFactoryBeanConfiguration.class)) { - this.contextRunner.withUserConfiguration(FooDependsOnBarTypePostProcessor.class).withParent(parentContext) - .run(this::assertThatFooDependsOnBar); + this.contextRunner.withUserConfiguration(FooDependsOnBarTypePostProcessor.class) + .withParent(parentContext) + .run(this::assertThatFooDependsOnBar); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorIntegrationTests.java index 69e7ff697d..eefce28976 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,27 +40,27 @@ class AutoConfigurationImportSelectorIntegrationTests { @Test void singleSelectorWithNoImports() { this.contextRunner.withUserConfiguration(NoConfig.class) - .run((context) -> assertThat(getImportedConfigBeans(context)).isEmpty()); + .run((context) -> assertThat(getImportedConfigBeans(context)).isEmpty()); } @Test void singleSelector() { this.contextRunner.withUserConfiguration(SingleConfig.class) - .run((context) -> assertThat(getImportedConfigBeans(context)).containsExactly("ConfigC")); + .run((context) -> assertThat(getImportedConfigBeans(context)).containsExactly("ConfigC")); } @Test void multipleSelectorsShouldMergeAndSortCorrectly() { this.contextRunner.withUserConfiguration(Config.class, AnotherConfig.class) - .run((context) -> assertThat(getImportedConfigBeans(context)).containsExactly("ConfigA", "ConfigB", - "ConfigC", "ConfigD")); + .run((context) -> assertThat(getImportedConfigBeans(context)).containsExactly("ConfigA", "ConfigB", + "ConfigC", "ConfigD")); } @Test void multipleSelectorsWithRedundantImportsShouldMergeAndSortCorrectly() { this.contextRunner.withUserConfiguration(SingleConfig.class, Config.class, AnotherConfig.class) - .run((context) -> assertThat(getImportedConfigBeans(context)).containsExactly("ConfigA", "ConfigB", - "ConfigC", "ConfigD")); + .run((context) -> assertThat(getImportedConfigBeans(context)).containsExactly("ConfigA", "ConfigB", + "ConfigC", "ConfigD")); } private List getImportedConfigBeans(AssertableApplicationContext context) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java index e22f3840ee..d70f356c7a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,7 +77,7 @@ class AutoConfigurationImportSelectorTests { String[] imports = selectImports(EnableAutoConfigurationWithClassExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) - .contains(FreeMarkerAutoConfiguration.class.getName()); + .contains(FreeMarkerAutoConfiguration.class.getName()); } @Test @@ -85,7 +85,7 @@ class AutoConfigurationImportSelectorTests { String[] imports = selectImports(SpringBootApplicationWithClassExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) - .contains(FreeMarkerAutoConfiguration.class.getName()); + .contains(FreeMarkerAutoConfiguration.class.getName()); } @Test @@ -93,7 +93,7 @@ class AutoConfigurationImportSelectorTests { String[] imports = selectImports(EnableAutoConfigurationWithClassNameExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) - .contains(MustacheAutoConfiguration.class.getName()); + .contains(MustacheAutoConfiguration.class.getName()); } @Test @@ -101,7 +101,7 @@ class AutoConfigurationImportSelectorTests { String[] imports = selectImports(SpringBootApplicationWithClassNameExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) - .contains(MustacheAutoConfiguration.class.getName()); + .contains(MustacheAutoConfiguration.class.getName()); } @Test @@ -110,7 +110,7 @@ class AutoConfigurationImportSelectorTests { String[] imports = selectImports(BasicEnableAutoConfiguration.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) - .contains(FreeMarkerAutoConfiguration.class.getName()); + .contains(FreeMarkerAutoConfiguration.class.getName()); } @Test @@ -138,7 +138,7 @@ class AutoConfigurationImportSelectorTests { String[] imports = selectImports(BasicEnableAutoConfiguration.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 2); assertThat(this.importSelector.getLastEvent().getExclusions()) - .contains(FreeMarkerAutoConfiguration.class.getName(), MustacheAutoConfiguration.class.getName()); + .contains(FreeMarkerAutoConfiguration.class.getName(), MustacheAutoConfiguration.class.getName()); } @Test @@ -154,13 +154,13 @@ class AutoConfigurationImportSelectorTests { @Test void nonAutoConfigurationClassExclusionsShouldThrowException() { assertThatIllegalStateException() - .isThrownBy(() -> selectImports(EnableAutoConfigurationWithFaultyClassExclude.class)); + .isThrownBy(() -> selectImports(EnableAutoConfigurationWithFaultyClassExclude.class)); } @Test void nonAutoConfigurationClassNameExclusionsWhenPresentOnClassPathShouldThrowException() { assertThatIllegalStateException() - .isThrownBy(() -> selectImports(EnableAutoConfigurationWithFaultyClassNameExclude.class)); + .isThrownBy(() -> selectImports(EnableAutoConfigurationWithFaultyClassNameExclude.class)); } @Test @@ -215,7 +215,7 @@ class AutoConfigurationImportSelectorTests { private List getAutoConfigurationClassNames() { List autoConfigurationClassNames = new ArrayList<>(); ImportCandidates.load(AutoConfiguration.class, getClass().getClassLoader()) - .forEach(autoConfigurationClassNames::add); + .forEach(autoConfigurationClassNames::add); return autoConfigurationClassNames; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java index f7a2dd9486..d53a22ca76 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,14 +42,14 @@ class AutoConfigurationPackagesTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( ConfigWithAutoConfigurationPackage.class); assertThat(AutoConfigurationPackages.get(context.getBeanFactory())) - .containsExactly(getClass().getPackage().getName()); + .containsExactly(getClass().getPackage().getName()); } @Test void getWithoutSet() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EmptyConfig.class); assertThatIllegalStateException().isThrownBy(() -> AutoConfigurationPackages.get(context.getBeanFactory())) - .withMessageContaining("Unable to retrieve @EnableAutoConfiguration base packages"); + .withMessageContaining("Unable to retrieve @EnableAutoConfiguration base packages"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java index fa0284ceb1..6f00a40248 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -176,7 +176,7 @@ class AutoConfigurationSorterTests { void byAutoConfigureAfterWithCycle() { this.sorter = new AutoConfigurationSorter(new CachingMetadataReaderFactory(), this.autoConfigurationMetadata); assertThatIllegalStateException().isThrownBy(() -> this.sorter.getInPriorityOrder(Arrays.asList(A, B, C, D))) - .withMessageContaining("AutoConfigure cycle detected"); + .withMessageContaining("AutoConfigure cycle detected"); } @Test @@ -203,7 +203,7 @@ class AutoConfigurationSorterTests { this.autoConfigurationMetadata = getAutoConfigurationMetadata(A, B, D); this.sorter = new AutoConfigurationSorter(readerFactory, this.autoConfigurationMetadata); assertThatIllegalStateException().isThrownBy(() -> this.sorter.getInPriorityOrder(Arrays.asList(D, B))) - .withMessageContaining("AutoConfigure cycle detected"); + .withMessageContaining("AutoConfigure cycle detected"); } private AutoConfigurationMetadata getAutoConfigurationMetadata(String... classNames) throws Exception { @@ -221,7 +221,7 @@ class AutoConfigurationSorterTests { private void addAutoConfigureAfter(Properties properties, String className, AnnotationMetadata annotationMetadata) { Map autoConfigureAfter = annotationMetadata - .getAnnotationAttributes(AutoConfigureAfter.class.getName(), true); + .getAnnotationAttributes(AutoConfigureAfter.class.getName(), true); if (autoConfigureAfter != null) { String value = merge((String[]) autoConfigureAfter.get("value"), (String[]) autoConfigureAfter.get("name")); if (!value.isEmpty()) { @@ -233,7 +233,7 @@ class AutoConfigurationSorterTests { private void addAutoConfigureBefore(Properties properties, String className, AnnotationMetadata annotationMetadata) { Map autoConfigureBefore = annotationMetadata - .getAnnotationAttributes(AutoConfigureBefore.class.getName(), true); + .getAnnotationAttributes(AutoConfigureBefore.class.getName(), true); if (autoConfigureBefore != null) { String value = merge((String[]) autoConfigureBefore.get("value"), (String[]) autoConfigureBefore.get("name")); @@ -245,7 +245,7 @@ class AutoConfigurationSorterTests { private void addAutoConfigureOrder(Properties properties, String className, AnnotationMetadata annotationMetadata) { Map autoConfigureOrder = annotationMetadata - .getAnnotationAttributes(AutoConfigureOrder.class.getName()); + .getAnnotationAttributes(AutoConfigureOrder.class.getName()); if (autoConfigureOrder != null) { Integer order = (Integer) autoConfigureOrder.get("order"); if (order != null) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java index 1946622572..ec21420eab 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -121,9 +121,9 @@ class ImportAutoConfigurationImportSelectorTests { @Test void determineImportsWhenUsingMetaWithoutClassesShouldBeEqual() throws Exception { Set set1 = this.importSelector - .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedOne.class)); + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedOne.class)); Set set2 = this.importSelector - .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedTwo.class)); + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedTwo.class)); assertThat(set1).isEqualTo(set2); assertThat(set1.hashCode()).isEqualTo(set2.hashCode()); } @@ -131,27 +131,27 @@ class ImportAutoConfigurationImportSelectorTests { @Test void determineImportsWhenUsingNonMetaWithoutClassesShouldBeSame() throws Exception { Set set1 = this.importSelector - .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedOne.class)); + .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedOne.class)); Set set2 = this.importSelector - .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedTwo.class)); + .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedTwo.class)); assertThat(set1).isEqualTo(set2); } @Test void determineImportsWhenUsingNonMetaWithClassesShouldBeSame() throws Exception { Set set1 = this.importSelector - .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithItemsOne.class)); + .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithItemsOne.class)); Set set2 = this.importSelector - .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithItemsTwo.class)); + .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithItemsTwo.class)); assertThat(set1).isEqualTo(set2); } @Test void determineImportsWhenUsingMetaExcludeWithoutClassesShouldBeEqual() throws Exception { Set set1 = this.importSelector - .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); Set set2 = this.importSelector - .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedTwo.class)); + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedTwo.class)); assertThat(set1).isEqualTo(set2); assertThat(set1.hashCode()).isEqualTo(set2.hashCode()); } @@ -159,18 +159,18 @@ class ImportAutoConfigurationImportSelectorTests { @Test void determineImportsWhenUsingMetaDifferentExcludeWithoutClassesShouldBeDifferent() throws Exception { Set set1 = this.importSelector - .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); Set set2 = this.importSelector - .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedTwo.class)); + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedTwo.class)); assertThat(set1).isNotEqualTo(set2); } @Test void determineImportsShouldNotSetPackageImport() throws Exception { - Class packageImportsClass = ClassUtils.resolveClassName( - "org.springframework.boot.autoconfigure.AutoConfigurationPackages.PackageImports", null); + Class packageImportsClass = ClassUtils + .resolveClassName("org.springframework.boot.autoconfigure.AutoConfigurationPackages.PackageImports", null); Set selectedImports = this.importSelector - .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); for (Object selectedImport : selectedImports) { assertThat(selectedImport).isNotInstanceOf(packageImportsClass); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializerTests.java index ba4f4aa661..cee16660f5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,7 +56,7 @@ class SharedMetadataReaderFactoryContextInitializerTests { SpringApplication application = new SpringApplication(TestConfig.class); application.setWebApplicationType(WebApplicationType.NONE); List> initializers = (List>) ReflectionTestUtils - .getField(application, "initializers"); + .getField(application, "initializers"); // Simulate what would happen if an initializer was added using spring.factories // and happened to be loaded first initializers.add(0, new Initializer()); @@ -72,7 +72,8 @@ class SharedMetadataReaderFactoryContextInitializerTests { ConfigurationClassPostProcessor configurationAnnotationPostProcessor = mock( ConfigurationClassPostProcessor.class); BeanDefinition beanDefinition = BeanDefinitionBuilder - .genericBeanDefinition(ConfigurationClassPostProcessor.class).getBeanDefinition(); + .genericBeanDefinition(ConfigurationClassPostProcessor.class) + .getBeanDefinition(); ((AbstractBeanDefinition) beanDefinition).setInstanceSupplier(() -> configurationAnnotationPostProcessor); registry.registerBeanDefinition(AnnotationConfigUtils.CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME, beanDefinition); @@ -83,10 +84,10 @@ class SharedMetadataReaderFactoryContextInitializerTests { ConfigurationClassPostProcessor bean = context.getBean(ConfigurationClassPostProcessor.class); assertThat(bean).isSameAs(configurationAnnotationPostProcessor); ArgumentCaptor metadataReaderFactory = ArgumentCaptor - .forClass(MetadataReaderFactory.class); + .forClass(MetadataReaderFactory.class); then(configurationAnnotationPostProcessor).should().setMetadataReaderFactory(metadataReaderFactory.capture()); assertThat(metadataReaderFactory.getValue()) - .isInstanceOf(ConcurrentReferenceCachingMetadataReaderFactory.class); + .isInstanceOf(ConcurrentReferenceCachingMetadataReaderFactory.class); } static class TestConfig { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringBootApplicationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringBootApplicationTests.java index 7f4ec93757..bcdb2dfe6f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringBootApplicationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringBootApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,28 +38,28 @@ class SpringBootApplicationTests { @Test void proxyBeanMethodsIsEnabledByDefault() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(DefaultSpringBootApplication.class, Configuration.class); + .getMergedAnnotationAttributes(DefaultSpringBootApplication.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(true); } @Test void proxyBeanMethodsCanBeDisabled() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(NoBeanMethodProxyingSpringBootApplication.class, Configuration.class); + .getMergedAnnotationAttributes(NoBeanMethodProxyingSpringBootApplication.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(false); } @Test void nameGeneratorDefaultToBeanNameGenerator() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(DefaultSpringBootApplication.class, ComponentScan.class); + .getMergedAnnotationAttributes(DefaultSpringBootApplication.class, ComponentScan.class); assertThat(attributes.get("nameGenerator")).isEqualTo(BeanNameGenerator.class); } @Test void nameGeneratorCanBeSpecified() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(CustomNameGeneratorConfiguration.class, ComponentScan.class); + .getMergedAnnotationAttributes(CustomNameGeneratorConfiguration.class, ComponentScan.class); assertThat(attributes.get("nameGenerator")).isEqualTo(TestBeanNameGenerator.class); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java index bb78ced983..f417db4c52 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ public class TestAutoConfigurationPackageRegistrar implements ImportBeanDefiniti @Override public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { AnnotationAttributes attributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(TestAutoConfigurationPackage.class.getName(), true)); + .fromMap(metadata.getAnnotationAttributes(TestAutoConfigurationPackage.class.getName(), true)); AutoConfigurationPackages.register(registry, ClassUtils.getPackageName(attributes.getString("value"))); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java index 389ec27b0a..cbf6b84edf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,7 +61,7 @@ class SpringApplicationAdminJmxAutoConfigurationTests { private final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SpringApplicationAdminJmxAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SpringApplicationAdminJmxAutoConfiguration.class)); @Test void notRegisteredWhenThereAreNoMBeanExporter() { @@ -75,46 +75,48 @@ class SpringApplicationAdminJmxAutoConfigurationTests { @Test void notRegisteredByDefaultWhenThereAreMultipleMBeanExporters() { this.contextRunner.withUserConfiguration(MultipleMBeanExportersConfiguration.class) - .run((context) -> assertThatExceptionOfType(InstanceNotFoundException.class) - .isThrownBy(() -> this.server.getObjectInstance(createDefaultObjectName()))); + .run((context) -> assertThatExceptionOfType(InstanceNotFoundException.class) + .isThrownBy(() -> this.server.getObjectInstance(createDefaultObjectName()))); } @Test void registeredWithPropertyWhenThereAreMultipleMBeanExporters() { this.contextRunner.withUserConfiguration(MultipleMBeanExportersConfiguration.class) - .withPropertyValues(ENABLE_ADMIN_PROP).run((context) -> { - ObjectName objectName = createDefaultObjectName(); - ObjectInstance objectInstance = this.server.getObjectInstance(objectName); - assertThat(objectInstance).as("Lifecycle bean should have been registered").isNotNull(); - }); + .withPropertyValues(ENABLE_ADMIN_PROP) + .run((context) -> { + ObjectName objectName = createDefaultObjectName(); + ObjectInstance objectInstance = this.server.getObjectInstance(objectName); + assertThat(objectInstance).as("Lifecycle bean should have been registered").isNotNull(); + }); } @Test void registerWithCustomJmxNameWhenThereAreMultipleMBeanExporters() { String customJmxName = "org.acme:name=FooBar"; this.contextRunner.withUserConfiguration(MultipleMBeanExportersConfiguration.class) - .withSystemProperties("spring.application.admin.jmx-name=" + customJmxName) - .withPropertyValues(ENABLE_ADMIN_PROP).run((context) -> { - try { - this.server.getObjectInstance(createObjectName(customJmxName)); - } - catch (InstanceNotFoundException ex) { - fail("Admin MBean should have been exposed with custom name"); - } - assertThatExceptionOfType(InstanceNotFoundException.class) - .isThrownBy(() -> this.server.getObjectInstance(createDefaultObjectName())); - }); + .withSystemProperties("spring.application.admin.jmx-name=" + customJmxName) + .withPropertyValues(ENABLE_ADMIN_PROP) + .run((context) -> { + try { + this.server.getObjectInstance(createObjectName(customJmxName)); + } + catch (InstanceNotFoundException ex) { + fail("Admin MBean should have been exposed with custom name"); + } + assertThatExceptionOfType(InstanceNotFoundException.class) + .isThrownBy(() -> this.server.getObjectInstance(createDefaultObjectName())); + }); } @Test void registerWithSimpleWebApp() throws Exception { try (ConfigurableApplicationContext context = new SpringApplicationBuilder() - .sources(ServletWebServerFactoryAutoConfiguration.class, DispatcherServletAutoConfiguration.class, - MultipleMBeanExportersConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class) - .run("--" + ENABLE_ADMIN_PROP, "--server.port=0")) { + .sources(ServletWebServerFactoryAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + MultipleMBeanExportersConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class) + .run("--" + ENABLE_ADMIN_PROP, "--server.port=0")) { assertThat(context).isInstanceOf(ServletWebServerApplicationContext.class); assertThat(this.server.getAttribute(createDefaultObjectName(), "EmbeddedWebApplication")) - .isEqualTo(Boolean.TRUE); + .isEqualTo(Boolean.TRUE); int expected = ((ServletWebServerApplicationContext) context).getWebServer().getPort(); String actual = getProperty(createDefaultObjectName(), "local.server.port"); assertThat(actual).isEqualTo(String.valueOf(expected)); @@ -124,15 +126,15 @@ class SpringApplicationAdminJmxAutoConfigurationTests { @Test void onlyRegisteredOnceWhenThereIsAChildContext() { SpringApplicationBuilder parentBuilder = new SpringApplicationBuilder().web(WebApplicationType.NONE) - .sources(MultipleMBeanExportersConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class); + .sources(MultipleMBeanExportersConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class); SpringApplicationBuilder childBuilder = parentBuilder - .child(MultipleMBeanExportersConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class) - .web(WebApplicationType.NONE); + .child(MultipleMBeanExportersConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class) + .web(WebApplicationType.NONE); try (ConfigurableApplicationContext parent = parentBuilder.run("--" + ENABLE_ADMIN_PROP); ConfigurableApplicationContext child = childBuilder.run("--" + ENABLE_ADMIN_PROP)) { BeanFactoryUtils.beanOfType(parent.getBeanFactory(), SpringApplicationAdminMXBeanRegistrar.class); assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> BeanFactoryUtils - .beanOfType(child.getBeanFactory(), SpringApplicationAdminMXBeanRegistrar.class)); + .beanOfType(child.getBeanFactory(), SpringApplicationAdminMXBeanRegistrar.class)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java index 2a46639c3b..431ddc5259 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -101,7 +101,7 @@ import static org.mockito.Mockito.mock; class RabbitAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class)); @Test void testDefaultRabbitConfiguration() { @@ -116,13 +116,14 @@ class RabbitAutoConfigurationTests { assertThat(amqpAdmin).isNotNull(); assertThat(connectionFactory.getHost()).isEqualTo("localhost"); assertThat(getTargetConnectionFactory(context).getRequestedChannelMax()) - .isEqualTo(com.rabbitmq.client.ConnectionFactory.DEFAULT_CHANNEL_MAX); + .isEqualTo(com.rabbitmq.client.ConnectionFactory.DEFAULT_CHANNEL_MAX); assertThat(connectionFactory.isPublisherConfirms()).isFalse(); assertThat(connectionFactory.isPublisherReturns()).isFalse(); assertThat(connectionFactory.getRabbitConnectionFactory().getChannelRpcTimeout()) - .isEqualTo(com.rabbitmq.client.ConnectionFactory.DEFAULT_CHANNEL_RPC_TIMEOUT); + .isEqualTo(com.rabbitmq.client.ConnectionFactory.DEFAULT_CHANNEL_RPC_TIMEOUT); assertThat(context.containsBean("rabbitListenerContainerFactory")) - .as("Listener container factory should be created by default").isTrue(); + .as("Listener container factory should be created by default") + .isTrue(); }); } @@ -150,22 +151,22 @@ class RabbitAutoConfigurationTests { @SuppressWarnings("unchecked") void testConnectionFactoryWithOverrides() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.host:remote-server", "spring.rabbitmq.port:9000", - "spring.rabbitmq.address-shuffle-mode=random", "spring.rabbitmq.username:alice", - "spring.rabbitmq.password:secret", "spring.rabbitmq.virtual_host:/vhost", - "spring.rabbitmq.connection-timeout:123", "spring.rabbitmq.channel-rpc-timeout:140") - .run((context) -> { - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(connectionFactory.getHost()).isEqualTo("remote-server"); - assertThat(connectionFactory.getPort()).isEqualTo(9000); - assertThat(connectionFactory).hasFieldOrPropertyWithValue("addressShuffleMode", - AddressShuffleMode.RANDOM); - assertThat(connectionFactory.getVirtualHost()).isEqualTo("/vhost"); - com.rabbitmq.client.ConnectionFactory rcf = connectionFactory.getRabbitConnectionFactory(); - assertThat(rcf.getConnectionTimeout()).isEqualTo(123); - assertThat(rcf.getChannelRpcTimeout()).isEqualTo(140); - assertThat((List
) ReflectionTestUtils.getField(connectionFactory, "addresses")).hasSize(1); - }); + .withPropertyValues("spring.rabbitmq.host:remote-server", "spring.rabbitmq.port:9000", + "spring.rabbitmq.address-shuffle-mode=random", "spring.rabbitmq.username:alice", + "spring.rabbitmq.password:secret", "spring.rabbitmq.virtual_host:/vhost", + "spring.rabbitmq.connection-timeout:123", "spring.rabbitmq.channel-rpc-timeout:140") + .run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory.getHost()).isEqualTo("remote-server"); + assertThat(connectionFactory.getPort()).isEqualTo(9000); + assertThat(connectionFactory).hasFieldOrPropertyWithValue("addressShuffleMode", + AddressShuffleMode.RANDOM); + assertThat(connectionFactory.getVirtualHost()).isEqualTo("/vhost"); + com.rabbitmq.client.ConnectionFactory rcf = connectionFactory.getRabbitConnectionFactory(); + assertThat(rcf.getConnectionTimeout()).isEqualTo(123); + assertThat(rcf.getChannelRpcTimeout()).isEqualTo(140); + assertThat((List
) ReflectionTestUtils.getField(connectionFactory, "addresses")).hasSize(1); + }); } @Test @@ -189,68 +190,75 @@ class RabbitAutoConfigurationTests { @Test void testConnectionFactoryEmptyVirtualHost() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.virtual_host:").run((context) -> { - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(connectionFactory.getVirtualHost()).isEqualTo("/"); - }); + .withPropertyValues("spring.rabbitmq.virtual_host:") + .run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory.getVirtualHost()).isEqualTo("/"); + }); } @Test void testConnectionFactoryVirtualHostNoLeadingSlash() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.virtual_host:foo").run((context) -> { - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(connectionFactory.getVirtualHost()).isEqualTo("foo"); - }); + .withPropertyValues("spring.rabbitmq.virtual_host:foo") + .run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory.getVirtualHost()).isEqualTo("foo"); + }); } @Test void testConnectionFactoryVirtualHostMultiLeadingSlashes() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.virtual_host:///foo").run((context) -> { - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(connectionFactory.getVirtualHost()).isEqualTo("///foo"); - }); + .withPropertyValues("spring.rabbitmq.virtual_host:///foo") + .run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory.getVirtualHost()).isEqualTo("///foo"); + }); } @Test void testConnectionFactoryDefaultVirtualHost() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.virtual_host:/").run((context) -> { - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(connectionFactory.getVirtualHost()).isEqualTo("/"); - }); + .withPropertyValues("spring.rabbitmq.virtual_host:/") + .run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory.getVirtualHost()).isEqualTo("/"); + }); } @Test void testConnectionFactoryPublisherConfirmTypeCorrelated() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.publisher-confirm-type=correlated").run((context) -> { - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(connectionFactory.isPublisherConfirms()).isTrue(); - assertThat(connectionFactory.isSimplePublisherConfirms()).isFalse(); - }); + .withPropertyValues("spring.rabbitmq.publisher-confirm-type=correlated") + .run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory.isPublisherConfirms()).isTrue(); + assertThat(connectionFactory.isSimplePublisherConfirms()).isFalse(); + }); } @Test void testConnectionFactoryPublisherConfirmTypeSimple() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.publisher-confirm-type=simple").run((context) -> { - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(connectionFactory.isPublisherConfirms()).isFalse(); - assertThat(connectionFactory.isSimplePublisherConfirms()).isTrue(); - }); + .withPropertyValues("spring.rabbitmq.publisher-confirm-type=simple") + .run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory.isPublisherConfirms()).isFalse(); + assertThat(connectionFactory.isSimplePublisherConfirms()).isTrue(); + }); } @Test void testConnectionFactoryPublisherReturns() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.publisher-returns=true").run((context) -> { - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - assertThat(connectionFactory.isPublisherReturns()).isTrue(); - assertThat(getMandatory(rabbitTemplate)).isTrue(); - }); + .withPropertyValues("spring.rabbitmq.publisher-returns=true") + .run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + assertThat(connectionFactory.isPublisherReturns()).isTrue(); + assertThat(getMandatory(rabbitTemplate)).isTrue(); + }); } @Test @@ -264,108 +272,113 @@ class RabbitAutoConfigurationTests { @Test void testRabbitTemplateRetry() { - this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues( - "spring.rabbitmq.template.retry.enabled:true", "spring.rabbitmq.template.retry.maxAttempts:4", - "spring.rabbitmq.template.retry.initialInterval:2000", "spring.rabbitmq.template.retry.multiplier:1.5", - "spring.rabbitmq.template.retry.maxInterval:5000", "spring.rabbitmq.template.receiveTimeout:123", - "spring.rabbitmq.template.replyTimeout:456").run((context) -> { - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - assertThat(rabbitTemplate).hasFieldOrPropertyWithValue("receiveTimeout", 123L); - assertThat(rabbitTemplate).hasFieldOrPropertyWithValue("replyTimeout", 456L); - RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(rabbitTemplate, - "retryTemplate"); - assertThat(retryTemplate).isNotNull(); - SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) ReflectionTestUtils.getField(retryTemplate, - "retryPolicy"); - ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) ReflectionTestUtils - .getField(retryTemplate, "backOffPolicy"); - assertThat(retryPolicy.getMaxAttempts()).isEqualTo(4); - assertThat(backOffPolicy.getInitialInterval()).isEqualTo(2000); - assertThat(backOffPolicy.getMultiplier()).isEqualTo(1.5); - assertThat(backOffPolicy.getMaxInterval()).isEqualTo(5000); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.rabbitmq.template.retry.enabled:true", + "spring.rabbitmq.template.retry.maxAttempts:4", + "spring.rabbitmq.template.retry.initialInterval:2000", + "spring.rabbitmq.template.retry.multiplier:1.5", "spring.rabbitmq.template.retry.maxInterval:5000", + "spring.rabbitmq.template.receiveTimeout:123", "spring.rabbitmq.template.replyTimeout:456") + .run((context) -> { + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + assertThat(rabbitTemplate).hasFieldOrPropertyWithValue("receiveTimeout", 123L); + assertThat(rabbitTemplate).hasFieldOrPropertyWithValue("replyTimeout", 456L); + RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(rabbitTemplate, + "retryTemplate"); + assertThat(retryTemplate).isNotNull(); + SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) ReflectionTestUtils.getField(retryTemplate, + "retryPolicy"); + ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) ReflectionTestUtils + .getField(retryTemplate, "backOffPolicy"); + assertThat(retryPolicy.getMaxAttempts()).isEqualTo(4); + assertThat(backOffPolicy.getInitialInterval()).isEqualTo(2000); + assertThat(backOffPolicy.getMultiplier()).isEqualTo(1.5); + assertThat(backOffPolicy.getMaxInterval()).isEqualTo(5000); + }); } @Test void testRabbitTemplateRetryWithCustomizer() { this.contextRunner.withUserConfiguration(RabbitRetryTemplateCustomizerConfiguration.class) - .withPropertyValues("spring.rabbitmq.template.retry.enabled:true", - "spring.rabbitmq.template.retry.initialInterval:2000") - .run((context) -> { - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(rabbitTemplate, - "retryTemplate"); - assertThat(retryTemplate).isNotNull(); - ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) ReflectionTestUtils - .getField(retryTemplate, "backOffPolicy"); - assertThat(backOffPolicy) - .isSameAs(context.getBean(RabbitRetryTemplateCustomizerConfiguration.class).backOffPolicy); - assertThat(backOffPolicy.getInitialInterval()).isEqualTo(100); - }); + .withPropertyValues("spring.rabbitmq.template.retry.enabled:true", + "spring.rabbitmq.template.retry.initialInterval:2000") + .run((context) -> { + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(rabbitTemplate, + "retryTemplate"); + assertThat(retryTemplate).isNotNull(); + ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) ReflectionTestUtils + .getField(retryTemplate, "backOffPolicy"); + assertThat(backOffPolicy) + .isSameAs(context.getBean(RabbitRetryTemplateCustomizerConfiguration.class).backOffPolicy); + assertThat(backOffPolicy.getInitialInterval()).isEqualTo(100); + }); } @Test void testRabbitTemplateExchangeAndRoutingKey() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.template.exchange:my-exchange", - "spring.rabbitmq.template.routing-key:my-routing-key") - .run((context) -> { - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - assertThat(rabbitTemplate.getExchange()).isEqualTo("my-exchange"); - assertThat(rabbitTemplate.getRoutingKey()).isEqualTo("my-routing-key"); - }); + .withPropertyValues("spring.rabbitmq.template.exchange:my-exchange", + "spring.rabbitmq.template.routing-key:my-routing-key") + .run((context) -> { + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + assertThat(rabbitTemplate.getExchange()).isEqualTo("my-exchange"); + assertThat(rabbitTemplate.getRoutingKey()).isEqualTo("my-routing-key"); + }); } @Test void testRabbitTemplateDefaultReceiveQueue() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.template.default-receive-queue:default-queue").run((context) -> { - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - assertThat(rabbitTemplate).hasFieldOrPropertyWithValue("defaultReceiveQueue", "default-queue"); - }); + .withPropertyValues("spring.rabbitmq.template.default-receive-queue:default-queue") + .run((context) -> { + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + assertThat(rabbitTemplate).hasFieldOrPropertyWithValue("defaultReceiveQueue", "default-queue"); + }); } @Test void testRabbitTemplateMandatory() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.template.mandatory:true").run((context) -> { - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - assertThat(getMandatory(rabbitTemplate)).isTrue(); - }); + .withPropertyValues("spring.rabbitmq.template.mandatory:true") + .run((context) -> { + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + assertThat(getMandatory(rabbitTemplate)).isTrue(); + }); } @Test void testRabbitTemplateMandatoryDisabledEvenIfPublisherReturnsIsSet() { - this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues( - "spring.rabbitmq.template.mandatory:false", "spring.rabbitmq.publisher-returns=true").run((context) -> { - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - assertThat(getMandatory(rabbitTemplate)).isFalse(); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.rabbitmq.template.mandatory:false", "spring.rabbitmq.publisher-returns=true") + .run((context) -> { + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + assertThat(getMandatory(rabbitTemplate)).isFalse(); + }); } @Test void testRabbitTemplateConfigurersIsAvailable() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(RabbitTemplateConfigurer.class)); + .run((context) -> assertThat(context).hasSingleBean(RabbitTemplateConfigurer.class)); } @Test void testRabbitTemplateConfigurerUsesConfig() { this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class) - .withPropertyValues("spring.rabbitmq.template.exchange:my-exchange", - "spring.rabbitmq.template.routing-key:my-routing-key", - "spring.rabbitmq.template.default-receive-queue:default-queue") - .run((context) -> { - RabbitTemplateConfigurer configurer = context.getBean(RabbitTemplateConfigurer.class); - RabbitTemplate template = mock(RabbitTemplate.class); - ConnectionFactory connectionFactory = mock(ConnectionFactory.class); - configurer.configure(template, connectionFactory); - then(template).should() - .setMessageConverter(context.getBean("myMessageConverter", MessageConverter.class)); - then(template).should().setExchange("my-exchange"); - then(template).should().setRoutingKey("my-routing-key"); - then(template).should().setDefaultReceiveQueue("default-queue"); - }); + .withPropertyValues("spring.rabbitmq.template.exchange:my-exchange", + "spring.rabbitmq.template.routing-key:my-routing-key", + "spring.rabbitmq.template.default-receive-queue:default-queue") + .run((context) -> { + RabbitTemplateConfigurer configurer = context.getBean(RabbitTemplateConfigurer.class); + RabbitTemplate template = mock(RabbitTemplate.class); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + configurer.configure(template, connectionFactory); + then(template).should() + .setMessageConverter(context.getBean("myMessageConverter", MessageConverter.class)); + then(template).should().setExchange("my-exchange"); + then(template).should().setRoutingKey("my-routing-key"); + then(template).should().setDefaultReceiveQueue("default-queue"); + }); } @Test @@ -382,16 +395,16 @@ class RabbitAutoConfigurationTests { @Test void testConnectionFactoryCacheSettings() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.cache.channel.size=23", - "spring.rabbitmq.cache.channel.checkoutTimeout=1000", - "spring.rabbitmq.cache.connection.mode=CONNECTION", "spring.rabbitmq.cache.connection.size=2") - .run((context) -> { - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(connectionFactory.getChannelCacheSize()).isEqualTo(23); - assertThat(connectionFactory.getCacheMode()).isEqualTo(CacheMode.CONNECTION); - assertThat(connectionFactory.getConnectionCacheSize()).isEqualTo(2); - assertThat(connectionFactory).hasFieldOrPropertyWithValue("channelCheckoutTimeout", 1000L); - }); + .withPropertyValues("spring.rabbitmq.cache.channel.size=23", + "spring.rabbitmq.cache.channel.checkoutTimeout=1000", + "spring.rabbitmq.cache.connection.mode=CONNECTION", "spring.rabbitmq.cache.connection.size=2") + .run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory.getChannelCacheSize()).isEqualTo(23); + assertThat(connectionFactory.getCacheMode()).isEqualTo(CacheMode.CONNECTION); + assertThat(connectionFactory.getConnectionCacheSize()).isEqualTo(2); + assertThat(connectionFactory).hasFieldOrPropertyWithValue("channelCheckoutTimeout", 1000L); + }); } @Test @@ -414,17 +427,17 @@ class RabbitAutoConfigurationTests { void testStaticQueues() { // There should NOT be an AmqpAdmin bean when dynamic is switch to false this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.dynamic:false") - .run((context) -> assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> context.getBean(AmqpAdmin.class)) - .withMessageContaining("No qualifying bean of type '" + AmqpAdmin.class.getName() + "'")); + .withPropertyValues("spring.rabbitmq.dynamic:false") + .run((context) -> assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> context.getBean(AmqpAdmin.class)) + .withMessageContaining("No qualifying bean of type '" + AmqpAdmin.class.getName() + "'")); } @Test void testEnableRabbitCreateDefaultContainerFactory() { this.contextRunner.withUserConfiguration(EnableRabbitConfiguration.class).run((context) -> { RabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", RabbitListenerContainerFactory.class); + .getBean("rabbitListenerContainerFactory", RabbitListenerContainerFactory.class); assertThat(rabbitListenerContainerFactory.getClass()).isEqualTo(SimpleRabbitListenerContainerFactory.class); }); } @@ -433,7 +446,7 @@ class RabbitAutoConfigurationTests { void testRabbitListenerContainerFactoryBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration5.class).run((context) -> { SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); + .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); rabbitListenerContainerFactory.setBatchSize(10); then(rabbitListenerContainerFactory).should().setBatchSize(10); assertThat(rabbitListenerContainerFactory.getAdviceChain()).isNull(); @@ -443,84 +456,82 @@ class RabbitAutoConfigurationTests { @Test void testSimpleRabbitListenerContainerFactoryWithCustomSettings() { this.contextRunner - .withUserConfiguration(MessageConvertersConfiguration.class, MessageRecoverersConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.simple.retry.enabled:true", - "spring.rabbitmq.listener.simple.retry.maxAttempts:4", - "spring.rabbitmq.listener.simple.retry.initialInterval:2000", - "spring.rabbitmq.listener.simple.retry.multiplier:1.5", - "spring.rabbitmq.listener.simple.retry.maxInterval:5000", - "spring.rabbitmq.listener.simple.autoStartup:false", - "spring.rabbitmq.listener.simple.acknowledgeMode:manual", - "spring.rabbitmq.listener.simple.concurrency:5", - "spring.rabbitmq.listener.simple.maxConcurrency:10", - "spring.rabbitmq.listener.simple.prefetch:40", - "spring.rabbitmq.listener.simple.defaultRequeueRejected:false", - "spring.rabbitmq.listener.simple.idleEventInterval:5", - "spring.rabbitmq.listener.simple.batchSize:20", - "spring.rabbitmq.listener.simple.missingQueuesFatal:false") - .run((context) -> { - SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); - assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("concurrentConsumers", 5); - assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("maxConcurrentConsumers", - 10); - assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("batchSize", 20); - assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("missingQueuesFatal", false); - checkCommonProps(context, rabbitListenerContainerFactory); - }); + .withUserConfiguration(MessageConvertersConfiguration.class, MessageRecoverersConfiguration.class) + .withPropertyValues("spring.rabbitmq.listener.simple.retry.enabled:true", + "spring.rabbitmq.listener.simple.retry.maxAttempts:4", + "spring.rabbitmq.listener.simple.retry.initialInterval:2000", + "spring.rabbitmq.listener.simple.retry.multiplier:1.5", + "spring.rabbitmq.listener.simple.retry.maxInterval:5000", + "spring.rabbitmq.listener.simple.autoStartup:false", + "spring.rabbitmq.listener.simple.acknowledgeMode:manual", + "spring.rabbitmq.listener.simple.concurrency:5", + "spring.rabbitmq.listener.simple.maxConcurrency:10", "spring.rabbitmq.listener.simple.prefetch:40", + "spring.rabbitmq.listener.simple.defaultRequeueRejected:false", + "spring.rabbitmq.listener.simple.idleEventInterval:5", + "spring.rabbitmq.listener.simple.batchSize:20", + "spring.rabbitmq.listener.simple.missingQueuesFatal:false") + .run((context) -> { + SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context + .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); + assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("concurrentConsumers", 5); + assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("maxConcurrentConsumers", 10); + assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("batchSize", 20); + assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("missingQueuesFatal", false); + checkCommonProps(context, rabbitListenerContainerFactory); + }); } @Test void testDirectRabbitListenerContainerFactoryWithCustomSettings() { this.contextRunner - .withUserConfiguration(MessageConvertersConfiguration.class, MessageRecoverersConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.type:direct", - "spring.rabbitmq.listener.direct.retry.enabled:true", - "spring.rabbitmq.listener.direct.retry.maxAttempts:4", - "spring.rabbitmq.listener.direct.retry.initialInterval:2000", - "spring.rabbitmq.listener.direct.retry.multiplier:1.5", - "spring.rabbitmq.listener.direct.retry.maxInterval:5000", - "spring.rabbitmq.listener.direct.autoStartup:false", - "spring.rabbitmq.listener.direct.acknowledgeMode:manual", - "spring.rabbitmq.listener.direct.consumers-per-queue:5", - "spring.rabbitmq.listener.direct.prefetch:40", - "spring.rabbitmq.listener.direct.defaultRequeueRejected:false", - "spring.rabbitmq.listener.direct.idleEventInterval:5", - "spring.rabbitmq.listener.direct.missingQueuesFatal:true") - .run((context) -> { - DirectRabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", DirectRabbitListenerContainerFactory.class); - assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("consumersPerQueue", 5); - assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("missingQueuesFatal", true); - checkCommonProps(context, rabbitListenerContainerFactory); - }); + .withUserConfiguration(MessageConvertersConfiguration.class, MessageRecoverersConfiguration.class) + .withPropertyValues("spring.rabbitmq.listener.type:direct", + "spring.rabbitmq.listener.direct.retry.enabled:true", + "spring.rabbitmq.listener.direct.retry.maxAttempts:4", + "spring.rabbitmq.listener.direct.retry.initialInterval:2000", + "spring.rabbitmq.listener.direct.retry.multiplier:1.5", + "spring.rabbitmq.listener.direct.retry.maxInterval:5000", + "spring.rabbitmq.listener.direct.autoStartup:false", + "spring.rabbitmq.listener.direct.acknowledgeMode:manual", + "spring.rabbitmq.listener.direct.consumers-per-queue:5", + "spring.rabbitmq.listener.direct.prefetch:40", + "spring.rabbitmq.listener.direct.defaultRequeueRejected:false", + "spring.rabbitmq.listener.direct.idleEventInterval:5", + "spring.rabbitmq.listener.direct.missingQueuesFatal:true") + .run((context) -> { + DirectRabbitListenerContainerFactory rabbitListenerContainerFactory = context + .getBean("rabbitListenerContainerFactory", DirectRabbitListenerContainerFactory.class); + assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("consumersPerQueue", 5); + assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("missingQueuesFatal", true); + checkCommonProps(context, rabbitListenerContainerFactory); + }); } @Test void testSimpleRabbitListenerContainerFactoryRetryWithCustomizer() { this.contextRunner.withUserConfiguration(RabbitRetryTemplateCustomizerConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.simple.retry.enabled:true", - "spring.rabbitmq.listener.simple.retry.maxAttempts:4") - .run((context) -> { - SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); - assertListenerRetryTemplate(rabbitListenerContainerFactory, - context.getBean(RabbitRetryTemplateCustomizerConfiguration.class).retryPolicy); - }); + .withPropertyValues("spring.rabbitmq.listener.simple.retry.enabled:true", + "spring.rabbitmq.listener.simple.retry.maxAttempts:4") + .run((context) -> { + SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context + .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); + assertListenerRetryTemplate(rabbitListenerContainerFactory, + context.getBean(RabbitRetryTemplateCustomizerConfiguration.class).retryPolicy); + }); } @Test void testDirectRabbitListenerContainerFactoryRetryWithCustomizer() { this.contextRunner.withUserConfiguration(RabbitRetryTemplateCustomizerConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.type:direct", - "spring.rabbitmq.listener.direct.retry.enabled:true", - "spring.rabbitmq.listener.direct.retry.maxAttempts:4") - .run((context) -> { - DirectRabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", DirectRabbitListenerContainerFactory.class); - assertListenerRetryTemplate(rabbitListenerContainerFactory, - context.getBean(RabbitRetryTemplateCustomizerConfiguration.class).retryPolicy); - }); + .withPropertyValues("spring.rabbitmq.listener.type:direct", + "spring.rabbitmq.listener.direct.retry.enabled:true", + "spring.rabbitmq.listener.direct.retry.maxAttempts:4") + .run((context) -> { + DirectRabbitListenerContainerFactory rabbitListenerContainerFactory = context + .getBean("rabbitListenerContainerFactory", DirectRabbitListenerContainerFactory.class); + assertListenerRetryTemplate(rabbitListenerContainerFactory, + context.getBean(RabbitRetryTemplateCustomizerConfiguration.class).retryPolicy); + }); } private void assertListenerRetryTemplate(AbstractRabbitListenerContainerFactory rabbitListenerContainerFactory, @@ -535,59 +546,61 @@ class RabbitAutoConfigurationTests { @Test void testRabbitListenerContainerFactoryConfigurersAreAvailable() { - this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues( - "spring.rabbitmq.listener.simple.concurrency:5", "spring.rabbitmq.listener.simple.maxConcurrency:10", - "spring.rabbitmq.listener.simple.prefetch:40", "spring.rabbitmq.listener.direct.consumers-per-queue:5", - "spring.rabbitmq.listener.direct.prefetch:40").run((context) -> { - assertThat(context).hasSingleBean(SimpleRabbitListenerContainerFactoryConfigurer.class); - assertThat(context).hasSingleBean(DirectRabbitListenerContainerFactoryConfigurer.class); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.rabbitmq.listener.simple.concurrency:5", + "spring.rabbitmq.listener.simple.maxConcurrency:10", "spring.rabbitmq.listener.simple.prefetch:40", + "spring.rabbitmq.listener.direct.consumers-per-queue:5", + "spring.rabbitmq.listener.direct.prefetch:40") + .run((context) -> { + assertThat(context).hasSingleBean(SimpleRabbitListenerContainerFactoryConfigurer.class); + assertThat(context).hasSingleBean(DirectRabbitListenerContainerFactoryConfigurer.class); + }); } @Test void testSimpleRabbitListenerContainerFactoryConfigurerUsesConfig() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.simple.concurrency:5", - "spring.rabbitmq.listener.simple.maxConcurrency:10", - "spring.rabbitmq.listener.simple.prefetch:40") - .run((context) -> { - SimpleRabbitListenerContainerFactoryConfigurer configurer = context - .getBean(SimpleRabbitListenerContainerFactoryConfigurer.class); - SimpleRabbitListenerContainerFactory factory = mock(SimpleRabbitListenerContainerFactory.class); - configurer.configure(factory, mock(ConnectionFactory.class)); - then(factory).should().setConcurrentConsumers(5); - then(factory).should().setMaxConcurrentConsumers(10); - then(factory).should().setPrefetchCount(40); - }); + .withPropertyValues("spring.rabbitmq.listener.simple.concurrency:5", + "spring.rabbitmq.listener.simple.maxConcurrency:10", "spring.rabbitmq.listener.simple.prefetch:40") + .run((context) -> { + SimpleRabbitListenerContainerFactoryConfigurer configurer = context + .getBean(SimpleRabbitListenerContainerFactoryConfigurer.class); + SimpleRabbitListenerContainerFactory factory = mock(SimpleRabbitListenerContainerFactory.class); + configurer.configure(factory, mock(ConnectionFactory.class)); + then(factory).should().setConcurrentConsumers(5); + then(factory).should().setMaxConcurrentConsumers(10); + then(factory).should().setPrefetchCount(40); + }); } @Test void testSimpleRabbitListenerContainerFactoryConfigurerEnableDeBatchingWithConsumerBatchEnabled() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.simple.consumer-batch-enabled:true").run((context) -> { - SimpleRabbitListenerContainerFactoryConfigurer configurer = context - .getBean(SimpleRabbitListenerContainerFactoryConfigurer.class); - SimpleRabbitListenerContainerFactory factory = mock(SimpleRabbitListenerContainerFactory.class); - configurer.configure(factory, mock(ConnectionFactory.class)); - then(factory).should().setConsumerBatchEnabled(true); - }); + .withPropertyValues("spring.rabbitmq.listener.simple.consumer-batch-enabled:true") + .run((context) -> { + SimpleRabbitListenerContainerFactoryConfigurer configurer = context + .getBean(SimpleRabbitListenerContainerFactoryConfigurer.class); + SimpleRabbitListenerContainerFactory factory = mock(SimpleRabbitListenerContainerFactory.class); + configurer.configure(factory, mock(ConnectionFactory.class)); + then(factory).should().setConsumerBatchEnabled(true); + }); } @Test void testDirectRabbitListenerContainerFactoryConfigurerUsesConfig() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.direct.consumers-per-queue:5", - "spring.rabbitmq.listener.direct.prefetch:40", - "spring.rabbitmq.listener.direct.de-batching-enabled:false") - .run((context) -> { - DirectRabbitListenerContainerFactoryConfigurer configurer = context - .getBean(DirectRabbitListenerContainerFactoryConfigurer.class); - DirectRabbitListenerContainerFactory factory = mock(DirectRabbitListenerContainerFactory.class); - configurer.configure(factory, mock(ConnectionFactory.class)); - then(factory).should().setConsumersPerQueue(5); - then(factory).should().setPrefetchCount(40); - then(factory).should().setDeBatchingEnabled(false); - }); + .withPropertyValues("spring.rabbitmq.listener.direct.consumers-per-queue:5", + "spring.rabbitmq.listener.direct.prefetch:40", + "spring.rabbitmq.listener.direct.de-batching-enabled:false") + .run((context) -> { + DirectRabbitListenerContainerFactoryConfigurer configurer = context + .getBean(DirectRabbitListenerContainerFactoryConfigurer.class); + DirectRabbitListenerContainerFactory factory = mock(DirectRabbitListenerContainerFactory.class); + configurer.configure(factory, mock(ConnectionFactory.class)); + then(factory).should().setConsumersPerQueue(5); + then(factory).should().setPrefetchCount(40); + then(factory).should().setDeBatchingEnabled(false); + }); } private void checkCommonProps(AssertableApplicationContext context, @@ -632,19 +645,21 @@ class RabbitAutoConfigurationTests { @Test void customizeRequestedHeartBeat() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.requestedHeartbeat:20").run((context) -> { - com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); - assertThat(rabbitConnectionFactory.getRequestedHeartbeat()).isEqualTo(20); - }); + .withPropertyValues("spring.rabbitmq.requestedHeartbeat:20") + .run((context) -> { + com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); + assertThat(rabbitConnectionFactory.getRequestedHeartbeat()).isEqualTo(20); + }); } @Test void customizeRequestedChannelMax() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.requestedChannelMax:12").run((context) -> { - com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); - assertThat(rabbitConnectionFactory.getRequestedChannelMax()).isEqualTo(12); - }); + .withPropertyValues("spring.rabbitmq.requestedChannelMax:12") + .run((context) -> { + com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); + assertThat(rabbitConnectionFactory.getRequestedChannelMax()).isEqualTo(12); + }); } @Test @@ -659,218 +674,223 @@ class RabbitAutoConfigurationTests { @Test void enableSsl() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.ssl.enabled:true").run((context) -> { - com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); - assertThat(rabbitConnectionFactory.isSSL()).isTrue(); - assertThat(rabbitConnectionFactory.getSocketFactory()).as("SocketFactory must use SSL") - .isInstanceOf(SSLSocketFactory.class); - }); + .withPropertyValues("spring.rabbitmq.ssl.enabled:true") + .run((context) -> { + com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); + assertThat(rabbitConnectionFactory.isSSL()).isTrue(); + assertThat(rabbitConnectionFactory.getSocketFactory()).as("SocketFactory must use SSL") + .isInstanceOf(SSLSocketFactory.class); + }); } @Test // Make sure that we at least attempt to load the store void enableSslWithNonExistingKeystoreShouldFail() { - this.contextRunner - .withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.keyStore=foo", "spring.rabbitmq.ssl.keyStorePassword=secret") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasMessageContaining("foo"); - assertThat(context).getFailure().hasMessageContaining("does not exist"); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.rabbitmq.ssl.enabled:true", "spring.rabbitmq.ssl.keyStore=foo", + "spring.rabbitmq.ssl.keyStorePassword=secret") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().hasMessageContaining("foo"); + assertThat(context).getFailure().hasMessageContaining("does not exist"); + }); } @Test // Make sure that we at least attempt to load the store void enableSslWithNonExistingTrustStoreShouldFail() { - this.contextRunner - .withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.trustStore=bar", "spring.rabbitmq.ssl.trustStorePassword=secret") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasMessageContaining("bar"); - assertThat(context).getFailure().hasMessageContaining("does not exist"); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.rabbitmq.ssl.enabled:true", "spring.rabbitmq.ssl.trustStore=bar", + "spring.rabbitmq.ssl.trustStorePassword=secret") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().hasMessageContaining("bar"); + assertThat(context).getFailure().hasMessageContaining("does not exist"); + }); } @Test void enableSslWithInvalidKeystoreTypeShouldFail() { - this.contextRunner - .withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.keyStore=foo", "spring.rabbitmq.ssl.keyStoreType=fooType") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasMessageContaining("fooType"); - assertThat(context).getFailure().hasRootCauseInstanceOf(NoSuchAlgorithmException.class); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.rabbitmq.ssl.enabled:true", "spring.rabbitmq.ssl.keyStore=foo", + "spring.rabbitmq.ssl.keyStoreType=fooType") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().hasMessageContaining("fooType"); + assertThat(context).getFailure().hasRootCauseInstanceOf(NoSuchAlgorithmException.class); + }); } @Test void enableSslWithInvalidTrustStoreTypeShouldFail() { - this.contextRunner - .withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.trustStore=bar", "spring.rabbitmq.ssl.trustStoreType=barType") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasMessageContaining("barType"); - assertThat(context).getFailure().hasRootCauseInstanceOf(NoSuchAlgorithmException.class); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.rabbitmq.ssl.enabled:true", "spring.rabbitmq.ssl.trustStore=bar", + "spring.rabbitmq.ssl.trustStoreType=barType") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().hasMessageContaining("barType"); + assertThat(context).getFailure().hasRootCauseInstanceOf(NoSuchAlgorithmException.class); + }); } @Test void enableSslWithKeystoreTypeAndTrustStoreTypeShouldWork() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.keyStore=/org/springframework/boot/autoconfigure/amqp/test.jks", - "spring.rabbitmq.ssl.keyStoreType=jks", "spring.rabbitmq.ssl.keyStorePassword=secret", - "spring.rabbitmq.ssl.trustStore=/org/springframework/boot/autoconfigure/amqp/test.jks", - "spring.rabbitmq.ssl.trustStoreType=jks", "spring.rabbitmq.ssl.trustStorePassword=secret") - .run((context) -> assertThat(context).hasNotFailed()); + .withPropertyValues("spring.rabbitmq.ssl.enabled:true", + "spring.rabbitmq.ssl.keyStore=/org/springframework/boot/autoconfigure/amqp/test.jks", + "spring.rabbitmq.ssl.keyStoreType=jks", "spring.rabbitmq.ssl.keyStorePassword=secret", + "spring.rabbitmq.ssl.trustStore=/org/springframework/boot/autoconfigure/amqp/test.jks", + "spring.rabbitmq.ssl.trustStoreType=jks", "spring.rabbitmq.ssl.trustStorePassword=secret") + .run((context) -> assertThat(context).hasNotFailed()); } @Test void enableSslWithValidateServerCertificateFalse(CapturedOutput output) { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.validateServerCertificate=false") - .run((context) -> { - com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); - assertThat(rabbitConnectionFactory.isSSL()).isTrue(); - assertThat(output).contains("TrustEverythingTrustManager", "SECURITY ALERT"); - }); + .withPropertyValues("spring.rabbitmq.ssl.enabled:true", + "spring.rabbitmq.ssl.validateServerCertificate=false") + .run((context) -> { + com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); + assertThat(rabbitConnectionFactory.isSSL()).isTrue(); + assertThat(output).contains("TrustEverythingTrustManager", "SECURITY ALERT"); + }); } @Test void enableSslWithValidateServerCertificateDefault(CapturedOutput output) { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.ssl.enabled:true").run((context) -> { - com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); - assertThat(rabbitConnectionFactory.isSSL()).isTrue(); - assertThat(output).doesNotContain("TrustEverythingTrustManager", "SECURITY ALERT"); - }); + .withPropertyValues("spring.rabbitmq.ssl.enabled:true") + .run((context) -> { + com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); + assertThat(rabbitConnectionFactory.isSSL()).isTrue(); + assertThat(output).doesNotContain("TrustEverythingTrustManager", "SECURITY ALERT"); + }); } @Test void enableSslWithValidStoreAlgorithmShouldWork() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.keyStore=/org/springframework/boot/autoconfigure/amqp/test.jks", - "spring.rabbitmq.ssl.keyStoreType=jks", "spring.rabbitmq.ssl.keyStorePassword=secret", - "spring.rabbitmq.ssl.keyStoreAlgorithm=PKIX", - "spring.rabbitmq.ssl.trustStore=/org/springframework/boot/autoconfigure/amqp/test.jks", - "spring.rabbitmq.ssl.trustStoreType=jks", "spring.rabbitmq.ssl.trustStorePassword=secret", - "spring.rabbitmq.ssl.trustStoreAlgorithm=PKIX") - .run((context) -> assertThat(context).hasNotFailed()); + .withPropertyValues("spring.rabbitmq.ssl.enabled:true", + "spring.rabbitmq.ssl.keyStore=/org/springframework/boot/autoconfigure/amqp/test.jks", + "spring.rabbitmq.ssl.keyStoreType=jks", "spring.rabbitmq.ssl.keyStorePassword=secret", + "spring.rabbitmq.ssl.keyStoreAlgorithm=PKIX", + "spring.rabbitmq.ssl.trustStore=/org/springframework/boot/autoconfigure/amqp/test.jks", + "spring.rabbitmq.ssl.trustStoreType=jks", "spring.rabbitmq.ssl.trustStorePassword=secret", + "spring.rabbitmq.ssl.trustStoreAlgorithm=PKIX") + .run((context) -> assertThat(context).hasNotFailed()); } @Test void enableSslWithInvalidKeyStoreAlgorithmShouldFail() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.keyStore=/org/springframework/boot/autoconfigure/amqp/test.jks", - "spring.rabbitmq.ssl.keyStoreType=jks", "spring.rabbitmq.ssl.keyStorePassword=secret", - "spring.rabbitmq.ssl.keyStoreAlgorithm=test-invalid-algo") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasMessageContaining("test-invalid-algo"); - assertThat(context).getFailure().hasRootCauseInstanceOf(NoSuchAlgorithmException.class); - }); + .withPropertyValues("spring.rabbitmq.ssl.enabled:true", + "spring.rabbitmq.ssl.keyStore=/org/springframework/boot/autoconfigure/amqp/test.jks", + "spring.rabbitmq.ssl.keyStoreType=jks", "spring.rabbitmq.ssl.keyStorePassword=secret", + "spring.rabbitmq.ssl.keyStoreAlgorithm=test-invalid-algo") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().hasMessageContaining("test-invalid-algo"); + assertThat(context).getFailure().hasRootCauseInstanceOf(NoSuchAlgorithmException.class); + }); } @Test void enableSslWithInvalidTrustStoreAlgorithmShouldFail() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.trustStore=/org/springframework/boot/autoconfigure/amqp/test.jks", - "spring.rabbitmq.ssl.trustStoreType=jks", "spring.rabbitmq.ssl.trustStorePassword=secret", - "spring.rabbitmq.ssl.trustStoreAlgorithm=test-invalid-algo") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasMessageContaining("test-invalid-algo"); - assertThat(context).getFailure().hasRootCauseInstanceOf(NoSuchAlgorithmException.class); - }); + .withPropertyValues("spring.rabbitmq.ssl.enabled:true", + "spring.rabbitmq.ssl.trustStore=/org/springframework/boot/autoconfigure/amqp/test.jks", + "spring.rabbitmq.ssl.trustStoreType=jks", "spring.rabbitmq.ssl.trustStorePassword=secret", + "spring.rabbitmq.ssl.trustStoreAlgorithm=test-invalid-algo") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().hasMessageContaining("test-invalid-algo"); + assertThat(context).getFailure().hasRootCauseInstanceOf(NoSuchAlgorithmException.class); + }); } @Test void whenACredentialsProviderIsAvailableThenConnectionFactoryIsConfiguredToUseIt() { this.contextRunner.withUserConfiguration(CredentialsProviderConfiguration.class) - .run((context) -> assertThat(getTargetConnectionFactory(context).params(null).getCredentialsProvider()) - .isEqualTo(CredentialsProviderConfiguration.credentialsProvider)); + .run((context) -> assertThat(getTargetConnectionFactory(context).params(null).getCredentialsProvider()) + .isEqualTo(CredentialsProviderConfiguration.credentialsProvider)); } @Test void whenAPrimaryCredentialsProviderIsAvailableThenConnectionFactoryIsConfiguredToUseIt() { this.contextRunner.withUserConfiguration(PrimaryCredentialsProviderConfiguration.class) - .run((context) -> assertThat(getTargetConnectionFactory(context).params(null).getCredentialsProvider()) - .isEqualTo(PrimaryCredentialsProviderConfiguration.credentialsProvider)); + .run((context) -> assertThat(getTargetConnectionFactory(context).params(null).getCredentialsProvider()) + .isEqualTo(PrimaryCredentialsProviderConfiguration.credentialsProvider)); } @Test void whenMultipleCredentialsProvidersAreAvailableThenConnectionFactoryUsesDefaultProvider() { this.contextRunner.withUserConfiguration(MultipleCredentialsProvidersConfiguration.class) - .run((context) -> assertThat(getTargetConnectionFactory(context).params(null).getCredentialsProvider()) - .isInstanceOf(DefaultCredentialsProvider.class)); + .run((context) -> assertThat(getTargetConnectionFactory(context).params(null).getCredentialsProvider()) + .isInstanceOf(DefaultCredentialsProvider.class)); } @Test void whenACredentialsRefreshServiceIsAvailableThenConnectionFactoryIsConfiguredToUseIt() { - this.contextRunner.withUserConfiguration(CredentialsRefreshServiceConfiguration.class).run( - (context) -> assertThat(getTargetConnectionFactory(context).params(null).getCredentialsRefreshService()) - .isEqualTo(CredentialsRefreshServiceConfiguration.credentialsRefreshService)); + this.contextRunner.withUserConfiguration(CredentialsRefreshServiceConfiguration.class) + .run((context) -> assertThat( + getTargetConnectionFactory(context).params(null).getCredentialsRefreshService()) + .isEqualTo(CredentialsRefreshServiceConfiguration.credentialsRefreshService)); } @Test void whenAPrimaryCredentialsRefreshServiceIsAvailableThenConnectionFactoryIsConfiguredToUseIt() { - this.contextRunner.withUserConfiguration(PrimaryCredentialsRefreshServiceConfiguration.class).run( - (context) -> assertThat(getTargetConnectionFactory(context).params(null).getCredentialsRefreshService()) - .isEqualTo(PrimaryCredentialsRefreshServiceConfiguration.credentialsRefreshService)); + this.contextRunner.withUserConfiguration(PrimaryCredentialsRefreshServiceConfiguration.class) + .run((context) -> assertThat( + getTargetConnectionFactory(context).params(null).getCredentialsRefreshService()) + .isEqualTo(PrimaryCredentialsRefreshServiceConfiguration.credentialsRefreshService)); } @Test void whenMultipleCredentialsRefreshServiceAreAvailableThenConnectionFactoryHasNoCredentialsRefreshService() { - this.contextRunner.withUserConfiguration(MultipleCredentialsRefreshServicesConfiguration.class).run( - (context) -> assertThat(getTargetConnectionFactory(context).params(null).getCredentialsRefreshService()) - .isNull()); + this.contextRunner.withUserConfiguration(MultipleCredentialsRefreshServicesConfiguration.class) + .run((context) -> assertThat( + getTargetConnectionFactory(context).params(null).getCredentialsRefreshService()) + .isNull()); } @Test void whenAConnectionFactoryCustomizerIsDefinedThenItCustomizesTheConnectionFactory() { this.contextRunner.withUserConfiguration(SaslConfigCustomizerConfiguration.class) - .run((context) -> assertThat(getTargetConnectionFactory(context).getSaslConfig()) - .isInstanceOf(JDKSaslConfig.class)); + .run((context) -> assertThat(getTargetConnectionFactory(context).getSaslConfig()) + .isInstanceOf(JDKSaslConfig.class)); } @Test void whenMultipleConnectionFactoryCustomizersAreDefinedThenTheyAreCalledInOrder() { this.contextRunner.withUserConfiguration(MultipleConnectionFactoryCustomizersConfiguration.class) - .run((context) -> { - ConnectionFactoryCustomizer firstCustomizer = context.getBean("firstCustomizer", - ConnectionFactoryCustomizer.class); - ConnectionFactoryCustomizer secondCustomizer = context.getBean("secondCustomizer", - ConnectionFactoryCustomizer.class); - InOrder inOrder = inOrder(firstCustomizer, secondCustomizer); - com.rabbitmq.client.ConnectionFactory targetConnectionFactory = getTargetConnectionFactory(context); - then(firstCustomizer).should(inOrder).customize(targetConnectionFactory); - then(secondCustomizer).should(inOrder).customize(targetConnectionFactory); - inOrder.verifyNoMoreInteractions(); - }); + .run((context) -> { + ConnectionFactoryCustomizer firstCustomizer = context.getBean("firstCustomizer", + ConnectionFactoryCustomizer.class); + ConnectionFactoryCustomizer secondCustomizer = context.getBean("secondCustomizer", + ConnectionFactoryCustomizer.class); + InOrder inOrder = inOrder(firstCustomizer, secondCustomizer); + com.rabbitmq.client.ConnectionFactory targetConnectionFactory = getTargetConnectionFactory(context); + then(firstCustomizer).should(inOrder).customize(targetConnectionFactory); + then(secondCustomizer).should(inOrder).customize(targetConnectionFactory); + inOrder.verifyNoMoreInteractions(); + }); } @Test @SuppressWarnings("unchecked") void whenASimpleContainerCustomizerIsDefinedThenItIsCalledToConfigureTheContainer() { this.contextRunner.withUserConfiguration(SimpleContainerCustomizerConfiguration.class) - .run((context) -> then(context.getBean(ContainerCustomizer.class)).should() - .configure(any(SimpleMessageListenerContainer.class))); + .run((context) -> then(context.getBean(ContainerCustomizer.class)).should() + .configure(any(SimpleMessageListenerContainer.class))); } @Test @SuppressWarnings("unchecked") void whenADirectContainerCustomizerIsDefinedThenItIsCalledToConfigureTheContainer() { this.contextRunner.withUserConfiguration(DirectContainerCustomizerConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.type:direct") - .run((context) -> then(context.getBean(ContainerCustomizer.class)).should() - .configure(any(DirectMessageListenerContainer.class))); + .withPropertyValues("spring.rabbitmq.listener.type:direct") + .run((context) -> then(context.getBean(ContainerCustomizer.class)).should() + .configure(any(DirectMessageListenerContainer.class))); } private com.rabbitmq.client.ConnectionFactory getTargetConnectionFactory(AssertableApplicationContext context) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java index 8a13cd4b3b..78c36a1e81 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java @@ -237,7 +237,7 @@ class RabbitPropertiesTests { void customAddresses() { this.properties.setAddresses("user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); assertThat(this.properties.getAddresses()) - .isEqualTo("user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); + .isEqualTo("user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitStreamConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitStreamConfigurationTests.java index 6b9f6c9f31..22440e22a7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitStreamConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitStreamConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,31 +53,34 @@ import static org.mockito.Mockito.mock; class RabbitStreamConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class)); @Test @SuppressWarnings("unchecked") void whenListenerTypeIsStreamThenStreamListenerContainerAndEnvironmentAreAutoConfigured() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.type:stream").run((context) -> { - RabbitListenerEndpointRegistry registry = context.getBean(RabbitListenerEndpointRegistry.class); - MessageListenerContainer listenerContainer = registry.getListenerContainer("test"); - assertThat(listenerContainer).isInstanceOf(StreamListenerContainer.class); - assertThat(listenerContainer).extracting("consumerCustomizer").isNotNull(); - assertThat(context.getBean(StreamRabbitListenerContainerFactory.class)) - .extracting("nativeListener", InstanceOfAssertFactories.BOOLEAN).isFalse(); - then(context.getBean(ContainerCustomizer.class)).should().configure(listenerContainer); - assertThat(context).hasSingleBean(Environment.class); - }); + .withPropertyValues("spring.rabbitmq.listener.type:stream") + .run((context) -> { + RabbitListenerEndpointRegistry registry = context.getBean(RabbitListenerEndpointRegistry.class); + MessageListenerContainer listenerContainer = registry.getListenerContainer("test"); + assertThat(listenerContainer).isInstanceOf(StreamListenerContainer.class); + assertThat(listenerContainer).extracting("consumerCustomizer").isNotNull(); + assertThat(context.getBean(StreamRabbitListenerContainerFactory.class)) + .extracting("nativeListener", InstanceOfAssertFactories.BOOLEAN) + .isFalse(); + then(context.getBean(ContainerCustomizer.class)).should().configure(listenerContainer); + assertThat(context).hasSingleBean(Environment.class); + }); } @Test void whenNativeListenerIsEnabledThenContainerFactoryIsConfiguredToUseNativeListeners() { this.contextRunner - .withPropertyValues("spring.rabbitmq.listener.type:stream", - "spring.rabbitmq.listener.stream.native-listener:true") - .run((context) -> assertThat(context.getBean(StreamRabbitListenerContainerFactory.class)) - .extracting("nativeListener", InstanceOfAssertFactories.BOOLEAN).isTrue()); + .withPropertyValues("spring.rabbitmq.listener.type:stream", + "spring.rabbitmq.listener.stream.native-listener:true") + .run((context) -> assertThat(context.getBean(StreamRabbitListenerContainerFactory.class)) + .extracting("nativeListener", InstanceOfAssertFactories.BOOLEAN) + .isTrue()); } @Test @@ -85,18 +88,18 @@ class RabbitStreamConfigurationTests { this.contextRunner.withUserConfiguration(CustomEnvironmentConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(Environment.class); assertThat(context.getBean(Environment.class)) - .isSameAs(context.getBean(CustomEnvironmentConfiguration.class).environment); + .isSameAs(context.getBean(CustomEnvironmentConfiguration.class).environment); }); } @Test void whenCustomMessageListenerContainerFactoryIsDefinedThenAutoConfiguredContainerFactoryBacksOff() { this.contextRunner.withUserConfiguration(CustomMessageListenerContainerFactoryConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(RabbitListenerContainerFactory.class); - assertThat(context.getBean(RabbitListenerContainerFactory.class)).isSameAs(context.getBean( - CustomMessageListenerContainerFactoryConfiguration.class).listenerContainerFactory); - }); + .run((context) -> { + assertThat(context).hasSingleBean(RabbitListenerContainerFactory.class); + assertThat(context.getBean(RabbitListenerContainerFactory.class)).isSameAs(context + .getBean(CustomMessageListenerContainerFactoryConfiguration.class).listenerContainerFactory); + }); } @Test @@ -157,56 +160,56 @@ class RabbitStreamConfigurationTests { @Test void testDefaultRabbitStreamTemplateConfiguration() { this.contextRunner - .withPropertyValues("spring.rabbitmq.listener.type:stream", "spring.rabbitmq.stream.name:stream-test") - .run((context) -> { - assertThat(context).hasSingleBean(RabbitStreamTemplate.class); - assertThat(context.getBean(RabbitStreamTemplate.class)).hasFieldOrPropertyWithValue("streamName", - "stream-test"); - }); + .withPropertyValues("spring.rabbitmq.listener.type:stream", "spring.rabbitmq.stream.name:stream-test") + .run((context) -> { + assertThat(context).hasSingleBean(RabbitStreamTemplate.class); + assertThat(context.getBean(RabbitStreamTemplate.class)).hasFieldOrPropertyWithValue("streamName", + "stream-test"); + }); } @Test void testDefaultRabbitStreamTemplateConfigurationWithoutStreamName() { this.contextRunner.withPropertyValues("spring.rabbitmq.listener.type:stream") - .run((context) -> assertThat(context).doesNotHaveBean(RabbitStreamTemplate.class)); + .run((context) -> assertThat(context).doesNotHaveBean(RabbitStreamTemplate.class)); } @Test void testRabbitStreamTemplateConfigurationWithCustomMessageConverter() { this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.type:stream", "spring.rabbitmq.stream.name:stream-test") - .run((context) -> { - assertThat(context).hasSingleBean(RabbitStreamTemplate.class); - RabbitStreamTemplate streamTemplate = context.getBean(RabbitStreamTemplate.class); - assertThat(streamTemplate).hasFieldOrPropertyWithValue("streamName", "stream-test"); - assertThat(streamTemplate).extracting("messageConverter") - .isSameAs(context.getBean(MessageConverter.class)); - }); + .withPropertyValues("spring.rabbitmq.listener.type:stream", "spring.rabbitmq.stream.name:stream-test") + .run((context) -> { + assertThat(context).hasSingleBean(RabbitStreamTemplate.class); + RabbitStreamTemplate streamTemplate = context.getBean(RabbitStreamTemplate.class); + assertThat(streamTemplate).hasFieldOrPropertyWithValue("streamName", "stream-test"); + assertThat(streamTemplate).extracting("messageConverter") + .isSameAs(context.getBean(MessageConverter.class)); + }); } @Test void testRabbitStreamTemplateConfigurationWithCustomStreamMessageConverter() { this.contextRunner - .withBean("myStreamMessageConverter", StreamMessageConverter.class, - () -> mock(StreamMessageConverter.class)) - .withPropertyValues("spring.rabbitmq.listener.type:stream", "spring.rabbitmq.stream.name:stream-test") - .run((context) -> { - assertThat(context).hasSingleBean(RabbitStreamTemplate.class); - assertThat(context.getBean(RabbitStreamTemplate.class)).extracting("messageConverter") - .isSameAs(context.getBean("myStreamMessageConverter")); - }); + .withBean("myStreamMessageConverter", StreamMessageConverter.class, + () -> mock(StreamMessageConverter.class)) + .withPropertyValues("spring.rabbitmq.listener.type:stream", "spring.rabbitmq.stream.name:stream-test") + .run((context) -> { + assertThat(context).hasSingleBean(RabbitStreamTemplate.class); + assertThat(context.getBean(RabbitStreamTemplate.class)).extracting("messageConverter") + .isSameAs(context.getBean("myStreamMessageConverter")); + }); } @Test void testRabbitStreamTemplateConfigurationWithCustomProducerCustomizer() { this.contextRunner - .withBean("myProducerCustomizer", ProducerCustomizer.class, () -> mock(ProducerCustomizer.class)) - .withPropertyValues("spring.rabbitmq.listener.type:stream", "spring.rabbitmq.stream.name:stream-test") - .run((context) -> { - assertThat(context).hasSingleBean(RabbitStreamTemplate.class); - assertThat(context.getBean(RabbitStreamTemplate.class)).extracting("producerCustomizer") - .isSameAs(context.getBean("myProducerCustomizer")); - }); + .withBean("myProducerCustomizer", ProducerCustomizer.class, () -> mock(ProducerCustomizer.class)) + .withPropertyValues("spring.rabbitmq.listener.type:stream", "spring.rabbitmq.stream.name:stream-test") + .run((context) -> { + assertThat(context).hasSingleBean(RabbitStreamTemplate.class); + assertThat(context.getBean(RabbitStreamTemplate.class)).extracting("producerCustomizer") + .isSameAs(context.getBean("myProducerCustomizer")); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java index 18b69aa51f..bbe4063c42 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,18 +46,19 @@ import static org.assertj.core.api.Assertions.assertThat; class AopAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AopAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(AopAutoConfiguration.class)); @Test void aopDisabled() { - this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.aop.auto:false") - .run((context) -> { - TestAspect aspect = context.getBean(TestAspect.class); - assertThat(aspect.isCalled()).isFalse(); - TestBean bean = context.getBean(TestBean.class); - bean.foo(); - assertThat(aspect.isCalled()).isFalse(); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.aop.auto:false") + .run((context) -> { + TestAspect aspect = context.getBean(TestAspect.class); + assertThat(aspect.isCalled()).isFalse(); + TestBean bean = context.getBean(TestBean.class); + bean.foo(); + assertThat(aspect.isCalled()).isFalse(); + }); } @Test @@ -68,13 +69,15 @@ class AopAutoConfigurationTests { @Test void aopWithEnabledProxyTargetClass() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.aop.proxy-target-class:true").run(proxyTargetClassEnabled()); + .withPropertyValues("spring.aop.proxy-target-class:true") + .run(proxyTargetClassEnabled()); } @Test void aopWithDisabledProxyTargetClass() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.aop.proxy-target-class:false").run(proxyTargetClassDisabled()); + .withPropertyValues("spring.aop.proxy-target-class:false") + .run(proxyTargetClassDisabled()); } @Test @@ -86,11 +89,11 @@ class AopAutoConfigurationTests { @Test void whenGlobalMethodSecurityIsEnabledAndAspectJIsNotAvailableThenClassProxyingIsStillUsedByDefault() { this.contextRunner.withClassLoader(new FilteredClassLoader(Advice.class)) - .withUserConfiguration(ExampleController.class, EnableGlobalMethodSecurityConfiguration.class) - .run((context) -> { - ExampleController exampleController = context.getBean(ExampleController.class); - assertThat(AopUtils.isCglibProxy(exampleController)).isTrue(); - }); + .withUserConfiguration(ExampleController.class, EnableGlobalMethodSecurityConfiguration.class) + .run((context) -> { + ExampleController exampleController = context.getBean(ExampleController.class); + assertThat(AopUtils.isCglibProxy(exampleController)).isTrue(); + }); } private ContextConsumer proxyTargetClassEnabled() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/NonAspectJAopAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/NonAspectJAopAutoConfigurationTests.java index 9c4c46ce10..76b3242a42 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/NonAspectJAopAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/NonAspectJAopAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,13 +35,13 @@ import static org.assertj.core.api.Assertions.assertThat; class NonAspectJAopAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AopAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(AopAutoConfiguration.class)); @Test void whenAspectJIsAbsentAndProxyTargetClassIsEnabledProxyCreatorBeanIsDefined() { this.contextRunner.run((context) -> { BeanDefinition autoProxyCreator = context.getBeanFactory() - .getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME); + .getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME); assertThat(autoProxyCreator.getPropertyValues().get("proxyTargetClass")).isEqualTo(Boolean.TRUE); }); } @@ -49,7 +49,7 @@ class NonAspectJAopAutoConfigurationTests { @Test void whenAspectJIsAbsentAndProxyTargetClassIsDisabledNoProxyCreatorBeanIsDefined() { this.contextRunner.withPropertyValues("spring.aop.proxy-target-class:false") - .run((context) -> assertThat(context).doesNotHaveBean(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME)); + .run((context) -> assertThat(context).doesNotHaveBean(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java index 9b6721470f..6b1062e41b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,286 +85,293 @@ import static org.mockito.Mockito.mock; class BatchAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class, TransactionAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class, TransactionAutoConfiguration.class)); @Test void testDefaultContext() { this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - assertThat(context).hasSingleBean(JobExplorer.class); - assertThat(context.getBean(BatchProperties.class).getJdbc().getInitializeSchema()) - .isEqualTo(DatabaseInitializationMode.EMBEDDED); - assertThat(new JdbcTemplate(context.getBean(DataSource.class)) - .queryForList("select * from BATCH_JOB_EXECUTION")).isEmpty(); - }); + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + assertThat(context).hasSingleBean(JobExplorer.class); + assertThat(context.getBean(BatchProperties.class).getJdbc().getInitializeSchema()) + .isEqualTo(DatabaseInitializationMode.EMBEDDED); + assertThat(new JdbcTemplate(context.getBean(DataSource.class)) + .queryForList("select * from BATCH_JOB_EXECUTION")).isEmpty(); + }); } @Test void whenThereIsNoDataSourceAutoConfigurationBacksOff() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(BatchConfigurer.class)); + .run((context) -> assertThat(context).doesNotHaveBean(BatchConfigurer.class)); } @Test void whenThereIsAnEntityManagerFactoryButNoDataSourceAutoConfigurationBacksOff() { this.contextRunner.withUserConfiguration(TestConfiguration.class, EntityManagerFactoryConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(BatchConfigurer.class)); + .run((context) -> assertThat(context).doesNotHaveBean(BatchConfigurer.class)); } @Test void testNoBatchConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).doesNotHaveBean(JobLauncher.class); - assertThat(context).doesNotHaveBean(JobRepository.class); - }); + .run((context) -> { + assertThat(context).doesNotHaveBean(JobLauncher.class); + assertThat(context).doesNotHaveBean(JobRepository.class); + }); } @Test void testDefinesAndLaunchesJob() { this.contextRunner.withUserConfiguration(JobConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - context.getBean(JobLauncherApplicationRunner.class) - .run(new DefaultApplicationArguments("jobParam=test")); - JobParameters jobParameters = new JobParametersBuilder().addString("jobParam", "test") - .toJobParameters(); - assertThat(context.getBean(JobRepository.class).getLastJobExecution("job", jobParameters)) - .isNotNull(); - }); + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + context.getBean(JobLauncherApplicationRunner.class) + .run(new DefaultApplicationArguments("jobParam=test")); + JobParameters jobParameters = new JobParametersBuilder().addString("jobParam", "test") + .toJobParameters(); + assertThat(context.getBean(JobRepository.class).getLastJobExecution("job", jobParameters)).isNotNull(); + }); } @Test void testDefinesAndLaunchesJobIgnoreOptionArguments() { this.contextRunner.withUserConfiguration(JobConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - context.getBean(JobLauncherApplicationRunner.class) - .run(new DefaultApplicationArguments("--spring.property=value", "jobParam=test")); - JobParameters jobParameters = new JobParametersBuilder().addString("jobParam", "test") - .toJobParameters(); - assertThat(context.getBean(JobRepository.class).getLastJobExecution("job", jobParameters)) - .isNotNull(); - }); + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + context.getBean(JobLauncherApplicationRunner.class) + .run(new DefaultApplicationArguments("--spring.property=value", "jobParam=test")); + JobParameters jobParameters = new JobParametersBuilder().addString("jobParam", "test") + .toJobParameters(); + assertThat(context.getBean(JobRepository.class).getLastJobExecution("job", jobParameters)).isNotNull(); + }); } @Test void testDefinesAndLaunchesNamedJob() { this.contextRunner - .withUserConfiguration(NamedJobConfigurationWithRegisteredJob.class, - EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.batch.job.names:discreteRegisteredJob").run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - context.getBean(JobLauncherApplicationRunner.class).run(); - assertThat(context.getBean(JobRepository.class).getLastJobExecution("discreteRegisteredJob", - new JobParameters())).isNotNull(); - }); + .withUserConfiguration(NamedJobConfigurationWithRegisteredJob.class, EmbeddedDataSourceConfiguration.class) + .withPropertyValues("spring.batch.job.names:discreteRegisteredJob") + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + context.getBean(JobLauncherApplicationRunner.class).run(); + assertThat(context.getBean(JobRepository.class) + .getLastJobExecution("discreteRegisteredJob", new JobParameters())).isNotNull(); + }); } @Test void testDefinesAndLaunchesLocalJob() { this.contextRunner - .withUserConfiguration(NamedJobConfigurationWithLocalJob.class, EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.batch.job.names:discreteLocalJob").run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - context.getBean(JobLauncherApplicationRunner.class).run(); - assertThat(context.getBean(JobRepository.class).getLastJobExecution("discreteLocalJob", - new JobParameters())).isNotNull(); - }); + .withUserConfiguration(NamedJobConfigurationWithLocalJob.class, EmbeddedDataSourceConfiguration.class) + .withPropertyValues("spring.batch.job.names:discreteLocalJob") + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + context.getBean(JobLauncherApplicationRunner.class).run(); + assertThat(context.getBean(JobRepository.class) + .getLastJobExecution("discreteLocalJob", new JobParameters())).isNotNull(); + }); } @Test void testDisableLaunchesJob() { this.contextRunner.withUserConfiguration(JobConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.batch.job.enabled:false").run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - assertThat(context).doesNotHaveBean(CommandLineRunner.class); - }); + .withPropertyValues("spring.batch.job.enabled:false") + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + assertThat(context).doesNotHaveBean(CommandLineRunner.class); + }); } @Test void testDisableSchemaLoader() { this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.datasource.generate-unique-name=true", - "spring.batch.jdbc.initialize-schema:never") - .run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - assertThat(context.getBean(BatchProperties.class).getJdbc().getInitializeSchema()) - .isEqualTo(DatabaseInitializationMode.NEVER); - assertThat(context).doesNotHaveBean(BatchDataSourceScriptDatabaseInitializer.class); - assertThatExceptionOfType(BadSqlGrammarException.class) - .isThrownBy(() -> new JdbcTemplate(context.getBean(DataSource.class)) - .queryForList("select * from BATCH_JOB_EXECUTION")); - }); + .withPropertyValues("spring.datasource.generate-unique-name=true", + "spring.batch.jdbc.initialize-schema:never") + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + assertThat(context.getBean(BatchProperties.class).getJdbc().getInitializeSchema()) + .isEqualTo(DatabaseInitializationMode.NEVER); + assertThat(context).doesNotHaveBean(BatchDataSourceScriptDatabaseInitializer.class); + assertThatExceptionOfType(BadSqlGrammarException.class) + .isThrownBy(() -> new JdbcTemplate(context.getBean(DataSource.class)) + .queryForList("select * from BATCH_JOB_EXECUTION")); + }); } @Test void testUsingJpa() { - this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, - HibernateJpaAutoConfiguration.class).run((context) -> { - PlatformTransactionManager transactionManager = context.getBean(PlatformTransactionManager.class); - // It's a lazy proxy, but it does render its target if you ask for - // toString(): - assertThat(transactionManager.toString().contains("JpaTransactionManager")).isTrue(); - assertThat(context).hasSingleBean(EntityManagerFactory.class); - // Ensure the JobRepository can be used (no problem with isolation - // level) - assertThat(context.getBean(JobRepository.class).getLastJobExecution("job", new JobParameters())) - .isNull(); - }); + this.contextRunner + .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + HibernateJpaAutoConfiguration.class) + .run((context) -> { + PlatformTransactionManager transactionManager = context.getBean(PlatformTransactionManager.class); + // It's a lazy proxy, but it does render its target if you ask for + // toString(): + assertThat(transactionManager.toString().contains("JpaTransactionManager")).isTrue(); + assertThat(context).hasSingleBean(EntityManagerFactory.class); + // Ensure the JobRepository can be used (no problem with isolation + // level) + assertThat(context.getBean(JobRepository.class).getLastJobExecution("job", new JobParameters())) + .isNull(); + }); } @Test void testDefaultIsolationLevelWithJpaLogsWarning(CapturedOutput output) { - this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, - HibernateJpaAutoConfiguration.class).run((context) -> { - assertThat(context.getBean(BasicBatchConfigurer.class).determineIsolationLevel()) - .isEqualTo("ISOLATION_DEFAULT"); - assertThat(output).contains("JPA does not support custom isolation levels") - .contains("set 'spring.batch.jdbc.isolation-level-for-create' to 'default'"); - }); + this.contextRunner + .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + HibernateJpaAutoConfiguration.class) + .run((context) -> { + assertThat(context.getBean(BasicBatchConfigurer.class).determineIsolationLevel()) + .isEqualTo("ISOLATION_DEFAULT"); + assertThat(output).contains("JPA does not support custom isolation levels") + .contains("set 'spring.batch.jdbc.isolation-level-for-create' to 'default'"); + }); } @Test void testCustomIsolationLevelWithJpaDoesNotLogWarning(CapturedOutput output) { this.contextRunner.withPropertyValues("spring.batch.jdbc.isolation-level-for-create=default") - .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, - HibernateJpaAutoConfiguration.class) - .run((context) -> { - assertThat(context.getBean(BasicBatchConfigurer.class).determineIsolationLevel()) - .isEqualTo("ISOLATION_DEFAULT"); - assertThat(output).doesNotContain("JPA does not support custom isolation levels") - .doesNotContain("set 'spring.batch.jdbc.isolation-level-for-create' to 'default'"); - }); + .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + HibernateJpaAutoConfiguration.class) + .run((context) -> { + assertThat(context.getBean(BasicBatchConfigurer.class).determineIsolationLevel()) + .isEqualTo("ISOLATION_DEFAULT"); + assertThat(output).doesNotContain("JPA does not support custom isolation levels") + .doesNotContain("set 'spring.batch.jdbc.isolation-level-for-create' to 'default'"); + }); } @Test void testRenamePrefix() { this.contextRunner - .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, - HibernateJpaAutoConfiguration.class) - .withPropertyValues("spring.datasource.generate-unique-name=true", - "spring.batch.jdbc.schema:classpath:batch/custom-schema.sql", - "spring.batch.jdbc.tablePrefix:PREFIX_") - .run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - assertThat(context.getBean(BatchProperties.class).getJdbc().getInitializeSchema()) - .isEqualTo(DatabaseInitializationMode.EMBEDDED); - assertThat(new JdbcTemplate(context.getBean(DataSource.class)) - .queryForList("select * from PREFIX_JOB_EXECUTION")).isEmpty(); - JobExplorer jobExplorer = context.getBean(JobExplorer.class); - assertThat(jobExplorer.findRunningJobExecutions("test")).isEmpty(); - JobRepository jobRepository = context.getBean(JobRepository.class); - assertThat(jobRepository.getLastJobExecution("test", new JobParameters())).isNull(); - }); + .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + HibernateJpaAutoConfiguration.class) + .withPropertyValues("spring.datasource.generate-unique-name=true", + "spring.batch.jdbc.schema:classpath:batch/custom-schema.sql", + "spring.batch.jdbc.tablePrefix:PREFIX_") + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + assertThat(context.getBean(BatchProperties.class).getJdbc().getInitializeSchema()) + .isEqualTo(DatabaseInitializationMode.EMBEDDED); + assertThat(new JdbcTemplate(context.getBean(DataSource.class)) + .queryForList("select * from PREFIX_JOB_EXECUTION")).isEmpty(); + JobExplorer jobExplorer = context.getBean(JobExplorer.class); + assertThat(jobExplorer.findRunningJobExecutions("test")).isEmpty(); + JobRepository jobRepository = context.getBean(JobRepository.class); + assertThat(jobRepository.getLastJobExecution("test", new JobParameters())).isNull(); + }); } @Test void testCustomizeJpaTransactionManagerUsingProperties() { this.contextRunner - .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, - HibernateJpaAutoConfiguration.class) - .withPropertyValues("spring.transaction.default-timeout:30", - "spring.transaction.rollback-on-commit-failure:true") - .run((context) -> { - assertThat(context).hasSingleBean(BatchConfigurer.class); - JpaTransactionManager transactionManager = JpaTransactionManager.class - .cast(context.getBean(BatchConfigurer.class).getTransactionManager()); - assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); - assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); - }); + .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + HibernateJpaAutoConfiguration.class) + .withPropertyValues("spring.transaction.default-timeout:30", + "spring.transaction.rollback-on-commit-failure:true") + .run((context) -> { + assertThat(context).hasSingleBean(BatchConfigurer.class); + JpaTransactionManager transactionManager = JpaTransactionManager.class + .cast(context.getBean(BatchConfigurer.class).getTransactionManager()); + assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); + assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); + }); } @Test void testCustomizeDataSourceTransactionManagerUsingProperties() { this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.transaction.default-timeout:30", - "spring.transaction.rollback-on-commit-failure:true") - .run((context) -> { - assertThat(context).hasSingleBean(BatchConfigurer.class); - DataSourceTransactionManager transactionManager = DataSourceTransactionManager.class - .cast(context.getBean(BatchConfigurer.class).getTransactionManager()); - assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); - assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); - }); + .withPropertyValues("spring.transaction.default-timeout:30", + "spring.transaction.rollback-on-commit-failure:true") + .run((context) -> { + assertThat(context).hasSingleBean(BatchConfigurer.class); + DataSourceTransactionManager transactionManager = DataSourceTransactionManager.class + .cast(context.getBean(BatchConfigurer.class).getTransactionManager()); + assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); + assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); + }); } @Test void testBatchDataSource() { this.contextRunner.withUserConfiguration(TestConfiguration.class, BatchDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(BatchConfigurer.class) - .hasSingleBean(BatchDataSourceScriptDatabaseInitializer.class).hasBean("batchDataSource"); - DataSource batchDataSource = context.getBean("batchDataSource", DataSource.class); - assertThat(context.getBean(BatchConfigurer.class)).hasFieldOrPropertyWithValue("dataSource", - batchDataSource); - assertThat(context.getBean(BatchDataSourceScriptDatabaseInitializer.class)) - .hasFieldOrPropertyWithValue("dataSource", batchDataSource); - }); + .run((context) -> { + assertThat(context).hasSingleBean(BatchConfigurer.class) + .hasSingleBean(BatchDataSourceScriptDatabaseInitializer.class) + .hasBean("batchDataSource"); + DataSource batchDataSource = context.getBean("batchDataSource", DataSource.class); + assertThat(context.getBean(BatchConfigurer.class)).hasFieldOrPropertyWithValue("dataSource", + batchDataSource); + assertThat(context.getBean(BatchDataSourceScriptDatabaseInitializer.class)) + .hasFieldOrPropertyWithValue("dataSource", batchDataSource); + }); } @Test void jobRepositoryBeansDependOnBatchDataSourceInitializer() { this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - String[] jobRepositoryNames = beanFactory.getBeanNamesForType(JobRepository.class); - assertThat(jobRepositoryNames).isNotEmpty(); - for (String jobRepositoryName : jobRepositoryNames) { - assertThat(beanFactory.getBeanDefinition(jobRepositoryName).getDependsOn()) - .contains("batchDataSourceInitializer"); - } - }); + .run((context) -> { + ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); + String[] jobRepositoryNames = beanFactory.getBeanNamesForType(JobRepository.class); + assertThat(jobRepositoryNames).isNotEmpty(); + for (String jobRepositoryName : jobRepositoryNames) { + assertThat(beanFactory.getBeanDefinition(jobRepositoryName).getDependsOn()) + .contains("batchDataSourceInitializer"); + } + }); } @Test void jobRepositoryBeansDependOnFlyway() { this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withUserConfiguration(FlywayAutoConfiguration.class) - .withPropertyValues("spring.batch.initialize-schema=never").run((context) -> { - ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - String[] jobRepositoryNames = beanFactory.getBeanNamesForType(JobRepository.class); - assertThat(jobRepositoryNames).isNotEmpty(); - for (String jobRepositoryName : jobRepositoryNames) { - assertThat(beanFactory.getBeanDefinition(jobRepositoryName).getDependsOn()).contains("flyway", - "flywayInitializer"); - } - }); + .withUserConfiguration(FlywayAutoConfiguration.class) + .withPropertyValues("spring.batch.initialize-schema=never") + .run((context) -> { + ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); + String[] jobRepositoryNames = beanFactory.getBeanNamesForType(JobRepository.class); + assertThat(jobRepositoryNames).isNotEmpty(); + for (String jobRepositoryName : jobRepositoryNames) { + assertThat(beanFactory.getBeanDefinition(jobRepositoryName).getDependsOn()).contains("flyway", + "flywayInitializer"); + } + }); } @Test void jobRepositoryBeansDependOnLiquibase() { this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withUserConfiguration(LiquibaseAutoConfiguration.class) - .withPropertyValues("spring.batch.initialize-schema=never").run((context) -> { - ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - String[] jobRepositoryNames = beanFactory.getBeanNamesForType(JobRepository.class); - assertThat(jobRepositoryNames).isNotEmpty(); - for (String jobRepositoryName : jobRepositoryNames) { - assertThat(beanFactory.getBeanDefinition(jobRepositoryName).getDependsOn()) - .contains("liquibase"); - } - }); + .withUserConfiguration(LiquibaseAutoConfiguration.class) + .withPropertyValues("spring.batch.initialize-schema=never") + .run((context) -> { + ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); + String[] jobRepositoryNames = beanFactory.getBeanNamesForType(JobRepository.class); + assertThat(jobRepositoryNames).isNotEmpty(); + for (String jobRepositoryName : jobRepositoryNames) { + assertThat(beanFactory.getBeanDefinition(jobRepositoryName).getDependsOn()).contains("liquibase"); + } + }); } @Test void whenTheUserDefinesTheirOwnBatchDatabaseInitializerThenTheAutoConfiguredInitializerBacksOff() { this.contextRunner - .withUserConfiguration(TestConfiguration.class, CustomBatchDatabaseInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(BatchDataSourceScriptDatabaseInitializer.class) - .doesNotHaveBean("batchDataSourceScriptDatabaseInitializer").hasBean("customInitializer")); + .withUserConfiguration(TestConfiguration.class, CustomBatchDatabaseInitializerConfiguration.class) + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(BatchDataSourceScriptDatabaseInitializer.class) + .doesNotHaveBean("batchDataSourceScriptDatabaseInitializer") + .hasBean("customInitializer")); } @Test void whenTheUserDefinesTheirOwnDatabaseInitializerThenTheAutoConfiguredBatchInitializerRemains() { this.contextRunner.withUserConfiguration(TestConfiguration.class, CustomDatabaseInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(BatchDataSourceScriptDatabaseInitializer.class) - .hasBean("customInitializer")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(BatchDataSourceScriptDatabaseInitializer.class) + .hasBean("customInitializer")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJdbcTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJdbcTests.java index 3974c7e909..b86337bdd8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJdbcTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJdbcTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,8 @@ import static org.mockito.Mockito.mock; class BatchAutoConfigurationWithoutJdbcTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class, TransactionAutoConfiguration.class)) - .withUserConfiguration(BatchConfiguration.class); + .withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class, TransactionAutoConfiguration.class)) + .withUserConfiguration(BatchConfiguration.class); @Test void whenThereIsNoJdbcOnTheClasspathThenComponentsAreStillAutoConfigured() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJpaTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJpaTests.java index 5c3860daab..db8320ce63 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJpaTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJpaTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,51 +47,52 @@ import static org.assertj.core.api.Assertions.assertThat; class BatchAutoConfigurationWithoutJpaTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class, TransactionAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class, TransactionAutoConfiguration.class)); @Test void jdbcWithDefaultSettings() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.datasource.generate-unique-name=true").run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - assertThat(context).hasSingleBean(JobExplorer.class); - assertThat(context).hasSingleBean(JobRepository.class); - assertThat(context).hasSingleBean(PlatformTransactionManager.class); - assertThat(context.getBean(PlatformTransactionManager.class).toString()) - .contains("DataSourceTransactionManager"); - assertThat(context.getBean(BatchProperties.class).getJdbc().getInitializeSchema()) - .isEqualTo(DatabaseInitializationMode.EMBEDDED); - assertThat(context.getBean(BasicBatchConfigurer.class).determineIsolationLevel()).isNull(); - assertThat(new JdbcTemplate(context.getBean(DataSource.class)) - .queryForList("select * from BATCH_JOB_EXECUTION")).isEmpty(); - assertThat(context.getBean(JobExplorer.class).findRunningJobExecutions("test")).isEmpty(); - assertThat(context.getBean(JobRepository.class).getLastJobExecution("test", new JobParameters())) - .isNull(); - }); + .withPropertyValues("spring.datasource.generate-unique-name=true") + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + assertThat(context).hasSingleBean(JobExplorer.class); + assertThat(context).hasSingleBean(JobRepository.class); + assertThat(context).hasSingleBean(PlatformTransactionManager.class); + assertThat(context.getBean(PlatformTransactionManager.class).toString()) + .contains("DataSourceTransactionManager"); + assertThat(context.getBean(BatchProperties.class).getJdbc().getInitializeSchema()) + .isEqualTo(DatabaseInitializationMode.EMBEDDED); + assertThat(context.getBean(BasicBatchConfigurer.class).determineIsolationLevel()).isNull(); + assertThat(new JdbcTemplate(context.getBean(DataSource.class)) + .queryForList("select * from BATCH_JOB_EXECUTION")).isEmpty(); + assertThat(context.getBean(JobExplorer.class).findRunningJobExecutions("test")).isEmpty(); + assertThat(context.getBean(JobRepository.class).getLastJobExecution("test", new JobParameters())) + .isNull(); + }); } @Test void jdbcWithCustomPrefix() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.datasource.generate-unique-name=true", - "spring.batch.jdbc.schema:classpath:batch/custom-schema.sql", - "spring.batch.jdbc.tablePrefix:PREFIX_") - .run((context) -> { - assertThat(new JdbcTemplate(context.getBean(DataSource.class)) - .queryForList("select * from PREFIX_JOB_EXECUTION")).isEmpty(); - assertThat(context.getBean(JobExplorer.class).findRunningJobExecutions("test")).isEmpty(); - assertThat(context.getBean(JobRepository.class).getLastJobExecution("test", new JobParameters())) - .isNull(); - }); + .withPropertyValues("spring.datasource.generate-unique-name=true", + "spring.batch.jdbc.schema:classpath:batch/custom-schema.sql", + "spring.batch.jdbc.tablePrefix:PREFIX_") + .run((context) -> { + assertThat(new JdbcTemplate(context.getBean(DataSource.class)) + .queryForList("select * from PREFIX_JOB_EXECUTION")).isEmpty(); + assertThat(context.getBean(JobExplorer.class).findRunningJobExecutions("test")).isEmpty(); + assertThat(context.getBean(JobRepository.class).getLastJobExecution("test", new JobParameters())) + .isNull(); + }); } @Test void jdbcWithCustomIsolationLevel() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.datasource.generate-unique-name=true", - "spring.batch.jdbc.isolation-level-for-create=read_committed") - .run((context) -> assertThat(context.getBean(BasicBatchConfigurer.class).determineIsolationLevel()) - .isEqualTo("ISOLATION_READ_COMMITTED")); + .withPropertyValues("spring.datasource.generate-unique-name=true", + "spring.batch.jdbc.isolation-level-for-create=read_committed") + .run((context) -> assertThat(context.getBean(BasicBatchConfigurer.class).determineIsolationLevel()) + .isEqualTo("ISOLATION_READ_COMMITTED")); } @EnableBatchProcessing diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchDataSourceScriptDatabaseInitializerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchDataSourceScriptDatabaseInitializerTests.java index 4ac56d5d18..95751079c7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchDataSourceScriptDatabaseInitializerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchDataSourceScriptDatabaseInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +57,7 @@ class BatchDataSourceScriptDatabaseInitializerTests { DatabaseInitializationSettings settings = BatchDataSourceScriptDatabaseInitializer.getSettings(dataSource, properties.getJdbc()); assertThat(settings.getSchemaLocations()) - .containsOnly("classpath:org/springframework/batch/core/schema-test.sql"); + .containsOnly("classpath:org/springframework/batch/core/schema-test.sql"); then(dataSource).shouldHaveNoInteractions(); } @@ -78,16 +78,17 @@ class BatchDataSourceScriptDatabaseInitializerTests { properties.getJdbc()); List schemaLocations = settings.getSchemaLocations(); assertThat(schemaLocations) - .allSatisfy((location) -> assertThat(resourceLoader.getResource(location).exists()).isTrue()); + .allSatisfy((location) -> assertThat(resourceLoader.getResource(location).exists()).isTrue()); } @Test void batchHasExpectedBuiltInSchemas() throws IOException { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); List schemaNames = Stream - .of(resolver.getResources("classpath:org/springframework/batch/core/schema-*.sql")) - .map((resource) -> resource.getFilename()).filter((resourceName) -> !resourceName.contains("-drop-")) - .collect(Collectors.toList()); + .of(resolver.getResources("classpath:org/springframework/batch/core/schema-*.sql")) + .map((resource) -> resource.getFilename()) + .filter((resourceName) -> !resourceName.contains("-drop-")) + .collect(Collectors.toList()); assertThat(schemaNames).containsExactlyInAnyOrder("schema-derby.sql", "schema-sqlserver.sql", "schema-mysql.sql", "schema-sqlite.sql", "schema-postgresql.sql", "schema-oracle10g.sql", "schema-db2.sql", "schema-sqlf.sql", "schema-hsqldb.sql", "schema-sybase.sql", "schema-h2.sql"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherApplicationRunnerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherApplicationRunnerTests.java index b9d0e26ab6..7f9ace8933 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherApplicationRunnerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherApplicationRunnerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,9 +68,8 @@ import static org.assertj.core.api.Assertions.fail; class JobLauncherApplicationRunnerTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class, TransactionAutoConfiguration.class)) - .withUserConfiguration(BatchConfiguration.class); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, TransactionAutoConfiguration.class)) + .withUserConfiguration(BatchConfiguration.class); @Test void basicExecution() { @@ -99,8 +98,9 @@ class JobLauncherApplicationRunnerTests { this.contextRunner.run((context) -> { JobLauncherApplicationRunnerContext jobLauncherContext = new JobLauncherApplicationRunnerContext(context); Job job = jobLauncherContext.jobBuilder() - .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet()).build()) - .incrementer(new RunIdIncrementer()).build(); + .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet()).build()) + .incrementer(new RunIdIncrementer()) + .build(); jobLauncherContext.runner.execute(job, new JobParameters()); jobLauncherContext.runner.execute(job, new JobParametersBuilder().addLong("run.id", 1L).toJobParameters()); assertThat(jobLauncherContext.jobInstances()).hasSize(1); @@ -112,7 +112,8 @@ class JobLauncherApplicationRunnerTests { this.contextRunner.run((context) -> { JobLauncherApplicationRunnerContext jobLauncherContext = new JobLauncherApplicationRunnerContext(context); Job job = jobLauncherContext.jobBuilder() - .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet()).build()).build(); + .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet()).build()) + .build(); // start a job instance JobParameters jobParameters = new JobParametersBuilder().addString("name", "foo").toJobParameters(); jobLauncherContext.runner.execute(job, jobParameters); @@ -128,9 +129,11 @@ class JobLauncherApplicationRunnerTests { void retryFailedExecutionOnNonRestartableJob() { this.contextRunner.run((context) -> { JobLauncherApplicationRunnerContext jobLauncherContext = new JobLauncherApplicationRunnerContext(context); - Job job = jobLauncherContext.jobBuilder().preventRestart() - .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet()).build()) - .incrementer(new RunIdIncrementer()).build(); + Job job = jobLauncherContext.jobBuilder() + .preventRestart() + .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet()).build()) + .incrementer(new RunIdIncrementer()) + .build(); jobLauncherContext.runner.execute(job, new JobParameters()); jobLauncherContext.runner.execute(job, new JobParameters()); // A failed job that is not restartable does not re-use the job params of @@ -150,10 +153,12 @@ class JobLauncherApplicationRunnerTests { this.contextRunner.run((context) -> { JobLauncherApplicationRunnerContext jobLauncherContext = new JobLauncherApplicationRunnerContext(context); Job job = jobLauncherContext.jobBuilder() - .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet()).build()) - .incrementer(new RunIdIncrementer()).build(); - JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false).addLong("foo", 2L, false) - .toJobParameters(); + .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet()).build()) + .incrementer(new RunIdIncrementer()) + .build(); + JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false) + .addLong("foo", 2L, false) + .toJobParameters(); jobLauncherContext.runner.execute(job, jobParameters); assertThat(jobLauncherContext.jobInstances()).hasSize(1); // try to re-run a failed execution with non identifying parameters diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/AbstractCacheAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/AbstractCacheAutoConfigurationTests.java index 01833b5ef9..9a95f4162c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/AbstractCacheAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/AbstractCacheAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,7 @@ import static org.assertj.core.api.Assertions.assertThat; abstract class AbstractCacheAutoConfigurationTests { protected final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class)); protected T getCacheManager(AssertableApplicationContext loaded, Class type) { CacheManager cacheManager = loaded.getBean(CacheManager.class); @@ -63,7 +63,7 @@ abstract class AbstractCacheAutoConfigurationTests { CacheManager cacheManager = getCacheManager(context, CacheManager.class); List expected = new ArrayList<>(Arrays.asList(expectedCustomizerNames)); Map customizer = context - .getBeansOfType(CacheManagerTestCustomizer.class); + .getBeansOfType(CacheManagerTestCustomizer.class); customizer.forEach((key, value) -> { if (expected.contains(key)) { expected.remove(key); 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 e23f19c4fd..3441a91ddd 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -95,70 +95,72 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { @Test void noEnableCaching() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(CacheManager.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CacheManager.class)); } @Test void cacheManagerBackOff() { this.contextRunner.withUserConfiguration(CustomCacheManagerConfiguration.class) - .run((context) -> assertThat(getCacheManager(context, ConcurrentMapCacheManager.class).getCacheNames()) - .containsOnly("custom1")); + .run((context) -> assertThat(getCacheManager(context, ConcurrentMapCacheManager.class).getCacheNames()) + .containsOnly("custom1")); } @Test void cacheManagerFromSupportBackOff() { this.contextRunner.withUserConfiguration(CustomCacheManagerFromSupportConfiguration.class) - .run((context) -> assertThat(getCacheManager(context, ConcurrentMapCacheManager.class).getCacheNames()) - .containsOnly("custom1")); + .run((context) -> assertThat(getCacheManager(context, ConcurrentMapCacheManager.class).getCacheNames()) + .containsOnly("custom1")); } @Test void cacheResolverFromSupportBackOff() { this.contextRunner.withUserConfiguration(CustomCacheResolverFromSupportConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(CacheManager.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CacheManager.class)); } @Test void customCacheResolverCanBeDefined() { this.contextRunner.withUserConfiguration(SpecificCacheResolverConfiguration.class) - .withPropertyValues("spring.cache.type=simple").run((context) -> { - getCacheManager(context, ConcurrentMapCacheManager.class); - assertThat(context).hasSingleBean(CacheResolver.class); - }); + .withPropertyValues("spring.cache.type=simple") + .run((context) -> { + getCacheManager(context, ConcurrentMapCacheManager.class); + assertThat(context).hasSingleBean(CacheResolver.class); + }); } @Test void notSupportedCachingMode() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=foobar") - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("Failed to bind properties under 'spring.cache.type'")); + .withPropertyValues("spring.cache.type=foobar") + .run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("Failed to bind properties under 'spring.cache.type'")); } @Test void simpleCacheExplicit() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=simple") - .run((context) -> assertThat(getCacheManager(context, ConcurrentMapCacheManager.class).getCacheNames()) - .isEmpty()); + .withPropertyValues("spring.cache.type=simple") + .run((context) -> assertThat(getCacheManager(context, ConcurrentMapCacheManager.class).getCacheNames()) + .isEmpty()); } @Test void simpleCacheWithCustomizers() { this.contextRunner.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) - .withPropertyValues("spring.cache.type=simple") - .run(verifyCustomizers("allCacheManagerCustomizer", "simpleCacheManagerCustomizer")); + .withPropertyValues("spring.cache.type=simple") + .run(verifyCustomizers("allCacheManagerCustomizer", "simpleCacheManagerCustomizer")); } @Test void simpleCacheExplicitWithCacheNames() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=simple", "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") - .run((context) -> { - ConcurrentMapCacheManager cacheManager = getCacheManager(context, ConcurrentMapCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - }); + .withPropertyValues("spring.cache.type=simple", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar") + .run((context) -> { + ConcurrentMapCacheManager cacheManager = getCacheManager(context, ConcurrentMapCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); + }); } @Test @@ -174,228 +176,236 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { @Test void genericCacheExplicit() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=generic") - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("No cache manager could be auto-configured") - .hasMessageContaining("GENERIC")); + .withPropertyValues("spring.cache.type=generic") + .run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("No cache manager could be auto-configured") + .hasMessageContaining("GENERIC")); } @Test void genericCacheWithCustomizers() { this.contextRunner.withUserConfiguration(GenericCacheAndCustomizersConfiguration.class) - .withPropertyValues("spring.cache.type=generic") - .run(verifyCustomizers("allCacheManagerCustomizer", "genericCacheManagerCustomizer")); + .withPropertyValues("spring.cache.type=generic") + .run(verifyCustomizers("allCacheManagerCustomizer", "genericCacheManagerCustomizer")); } @Test void genericCacheExplicitWithCaches() { this.contextRunner.withUserConfiguration(GenericCacheConfiguration.class) - .withPropertyValues("spring.cache.type=generic").run((context) -> { - SimpleCacheManager cacheManager = getCacheManager(context, SimpleCacheManager.class); - assertThat(cacheManager.getCache("first")).isEqualTo(context.getBean("firstCache")); - assertThat(cacheManager.getCache("second")).isEqualTo(context.getBean("secondCache")); - assertThat(cacheManager.getCacheNames()).hasSize(2); - }); + .withPropertyValues("spring.cache.type=generic") + .run((context) -> { + SimpleCacheManager cacheManager = getCacheManager(context, SimpleCacheManager.class); + assertThat(cacheManager.getCache("first")).isEqualTo(context.getBean("firstCache")); + assertThat(cacheManager.getCache("second")).isEqualTo(context.getBean("secondCache")); + assertThat(cacheManager.getCacheNames()).hasSize(2); + }); } @Test void couchbaseCacheExplicit() { this.contextRunner.withUserConfiguration(CouchbaseConfiguration.class) - .withPropertyValues("spring.cache.type=couchbase").run((context) -> { - CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); - assertThat(cacheManager.getCacheNames()).isEmpty(); - }); + .withPropertyValues("spring.cache.type=couchbase") + .run((context) -> { + CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); + assertThat(cacheManager.getCacheNames()).isEmpty(); + }); } @Test void couchbaseCacheWithCustomizers() { this.contextRunner.withUserConfiguration(CouchbaseWithCustomizersConfiguration.class) - .withPropertyValues("spring.cache.type=couchbase") - .run(verifyCustomizers("allCacheManagerCustomizer", "couchbaseCacheManagerCustomizer")); + .withPropertyValues("spring.cache.type=couchbase") + .run(verifyCustomizers("allCacheManagerCustomizer", "couchbaseCacheManagerCustomizer")); } @Test void couchbaseCacheExplicitWithCaches() { this.contextRunner.withUserConfiguration(CouchbaseConfiguration.class) - .withPropertyValues("spring.cache.type=couchbase", "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") - .run((context) -> { - CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - Cache cache = cacheManager.getCache("foo"); - assertThat(cache).isInstanceOf(CouchbaseCache.class); - assertThat(((CouchbaseCache) cache).getCacheConfiguration().getExpiry()).hasSeconds(0); - }); + .withPropertyValues("spring.cache.type=couchbase", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar") + .run((context) -> { + CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); + Cache cache = cacheManager.getCache("foo"); + assertThat(cache).isInstanceOf(CouchbaseCache.class); + assertThat(((CouchbaseCache) cache).getCacheConfiguration().getExpiry()).hasSeconds(0); + }); } @Test void couchbaseCacheExplicitWithTtl() { this.contextRunner.withUserConfiguration(CouchbaseConfiguration.class) - .withPropertyValues("spring.cache.type=couchbase", "spring.cache.cacheNames=foo,bar", - "spring.cache.couchbase.expiration=2000") - .run((context) -> { - CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - Cache cache = cacheManager.getCache("foo"); - assertThat(cache).isInstanceOf(CouchbaseCache.class); - assertThat(((CouchbaseCache) cache).getCacheConfiguration().getExpiry()).hasSeconds(2); - }); + .withPropertyValues("spring.cache.type=couchbase", "spring.cache.cacheNames=foo,bar", + "spring.cache.couchbase.expiration=2000") + .run((context) -> { + CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); + Cache cache = cacheManager.getCache("foo"); + assertThat(cache).isInstanceOf(CouchbaseCache.class); + assertThat(((CouchbaseCache) cache).getCacheConfiguration().getExpiry()).hasSeconds(2); + }); } @Test void couchbaseCacheWithCouchbaseCacheManagerBuilderCustomizer() { this.contextRunner.withUserConfiguration(CouchbaseConfiguration.class) - .withPropertyValues("spring.cache.type=couchbase", "spring.cache.couchbase.expiration=15s") - .withBean(CouchbaseCacheManagerBuilderCustomizer.class, () -> (builder) -> builder.cacheDefaults( - CouchbaseCacheConfiguration.defaultCacheConfig().entryExpiry(java.time.Duration.ofSeconds(10)))) - .run((context) -> { - CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); - CouchbaseCacheConfiguration couchbaseCacheConfiguration = getDefaultCouchbaseCacheConfiguration( - cacheManager); - assertThat(couchbaseCacheConfiguration.getExpiry()).isEqualTo(java.time.Duration.ofSeconds(10)); - }); + .withPropertyValues("spring.cache.type=couchbase", "spring.cache.couchbase.expiration=15s") + .withBean(CouchbaseCacheManagerBuilderCustomizer.class, + () -> (builder) -> builder.cacheDefaults(CouchbaseCacheConfiguration.defaultCacheConfig() + .entryExpiry(java.time.Duration.ofSeconds(10)))) + .run((context) -> { + CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); + CouchbaseCacheConfiguration couchbaseCacheConfiguration = getDefaultCouchbaseCacheConfiguration( + cacheManager); + assertThat(couchbaseCacheConfiguration.getExpiry()).isEqualTo(java.time.Duration.ofSeconds(10)); + }); } @Test void redisCacheExplicit() { this.contextRunner.withUserConfiguration(RedisConfiguration.class) - .withPropertyValues("spring.cache.type=redis", "spring.cache.redis.time-to-live=15000", - "spring.cache.redis.cacheNullValues=false", "spring.cache.redis.keyPrefix=prefix", - "spring.cache.redis.useKeyPrefix=true") - .run((context) -> { - RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); - assertThat(cacheManager.getCacheNames()).isEmpty(); - RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); - assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofSeconds(15)); - assertThat(redisCacheConfiguration.getAllowCacheNullValues()).isFalse(); - assertThat(redisCacheConfiguration.getKeyPrefixFor("MyCache")).isEqualTo("prefixMyCache::"); - assertThat(redisCacheConfiguration.usePrefix()).isTrue(); - }); + .withPropertyValues("spring.cache.type=redis", "spring.cache.redis.time-to-live=15000", + "spring.cache.redis.cacheNullValues=false", "spring.cache.redis.keyPrefix=prefix", + "spring.cache.redis.useKeyPrefix=true") + .run((context) -> { + RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); + assertThat(cacheManager.getCacheNames()).isEmpty(); + RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); + assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofSeconds(15)); + assertThat(redisCacheConfiguration.getAllowCacheNullValues()).isFalse(); + assertThat(redisCacheConfiguration.getKeyPrefixFor("MyCache")).isEqualTo("prefixMyCache::"); + assertThat(redisCacheConfiguration.usePrefix()).isTrue(); + }); } @Test void redisCacheWithRedisCacheConfiguration() { this.contextRunner.withUserConfiguration(RedisWithCacheConfigurationConfiguration.class) - .withPropertyValues("spring.cache.type=redis", "spring.cache.redis.time-to-live=15000", - "spring.cache.redis.keyPrefix=foo") - .run((context) -> { - RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); - assertThat(cacheManager.getCacheNames()).isEmpty(); - RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); - assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofSeconds(30)); - assertThat(redisCacheConfiguration.getKeyPrefixFor("")).isEqualTo("bar::"); - }); + .withPropertyValues("spring.cache.type=redis", "spring.cache.redis.time-to-live=15000", + "spring.cache.redis.keyPrefix=foo") + .run((context) -> { + RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); + assertThat(cacheManager.getCacheNames()).isEmpty(); + RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); + assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofSeconds(30)); + assertThat(redisCacheConfiguration.getKeyPrefixFor("")).isEqualTo("bar::"); + }); } @Test void redisCacheWithRedisCacheManagerBuilderCustomizer() { this.contextRunner.withUserConfiguration(RedisWithRedisCacheManagerBuilderCustomizerConfiguration.class) - .withPropertyValues("spring.cache.type=redis", "spring.cache.redis.time-to-live=15000") - .run((context) -> { - RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); - RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); - assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofSeconds(10)); - }); + .withPropertyValues("spring.cache.type=redis", "spring.cache.redis.time-to-live=15000") + .run((context) -> { + RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); + RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); + assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofSeconds(10)); + }); } @Test void redisCacheWithCustomizers() { this.contextRunner.withUserConfiguration(RedisWithCustomizersConfiguration.class) - .withPropertyValues("spring.cache.type=redis") - .run(verifyCustomizers("allCacheManagerCustomizer", "redisCacheManagerCustomizer")); + .withPropertyValues("spring.cache.type=redis") + .run(verifyCustomizers("allCacheManagerCustomizer", "redisCacheManagerCustomizer")); } @Test void redisCacheExplicitWithCaches() { - this.contextRunner.withUserConfiguration(RedisConfiguration.class).withPropertyValues("spring.cache.type=redis", - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar").run((context) -> { - RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); - assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofMinutes(0)); - assertThat(redisCacheConfiguration.getAllowCacheNullValues()).isTrue(); - assertThat(redisCacheConfiguration.getKeyPrefixFor("test")).isEqualTo("test::"); - assertThat(redisCacheConfiguration.usePrefix()).isTrue(); - }); + this.contextRunner.withUserConfiguration(RedisConfiguration.class) + .withPropertyValues("spring.cache.type=redis", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar") + .run((context) -> { + RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); + RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); + assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofMinutes(0)); + assertThat(redisCacheConfiguration.getAllowCacheNullValues()).isTrue(); + assertThat(redisCacheConfiguration.getKeyPrefixFor("test")).isEqualTo("test::"); + assertThat(redisCacheConfiguration.usePrefix()).isTrue(); + }); } @Test void noOpCacheExplicit() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=none").run((context) -> { - NoOpCacheManager cacheManager = getCacheManager(context, NoOpCacheManager.class); - assertThat(cacheManager.getCacheNames()).isEmpty(); - }); + .withPropertyValues("spring.cache.type=none") + .run((context) -> { + NoOpCacheManager cacheManager = getCacheManager(context, NoOpCacheManager.class); + assertThat(cacheManager.getCacheNames()).isEmpty(); + }); } @Test void jCacheCacheNoProviderExplicit() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache") - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("No cache manager could be auto-configured") - .hasMessageContaining("JCACHE")); + .withPropertyValues("spring.cache.type=jcache") + .run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("No cache manager could be auto-configured") + .hasMessageContaining("JCACHE")); } @Test void jCacheCacheWithProvider() { String cachingProviderFqn = MockCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - assertThat(cacheManager.getCacheNames()).isEmpty(); - assertThat(context.getBean(javax.cache.CacheManager.class)) - .isEqualTo(cacheManager.getCacheManager()); - }); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + assertThat(cacheManager.getCacheNames()).isEmpty(); + assertThat(context.getBean(javax.cache.CacheManager.class)).isEqualTo(cacheManager.getCacheManager()); + }); } @Test void jCacheCacheWithCaches() { String cachingProviderFqn = MockCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - }); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); + }); } @Test void jCacheCacheWithCachesAndCustomConfig() { String cachingProviderFqn = MockCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(JCacheCustomConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.cacheNames[0]=one", "spring.cache.cacheNames[1]=two") - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("one", "two"); - CompleteConfiguration defaultCacheConfiguration = context - .getBean(CompleteConfiguration.class); - MockCacheManager mockCacheManager = (MockCacheManager) cacheManager.getCacheManager(); - assertThat(mockCacheManager.getConfigurations()).containsEntry("one", defaultCacheConfiguration) - .containsEntry("two", defaultCacheConfiguration); - }); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.cacheNames[0]=one", "spring.cache.cacheNames[1]=two") + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("one", "two"); + CompleteConfiguration defaultCacheConfiguration = context.getBean(CompleteConfiguration.class); + MockCacheManager mockCacheManager = (MockCacheManager) cacheManager.getCacheManager(); + assertThat(mockCacheManager.getConfigurations()).containsEntry("one", defaultCacheConfiguration) + .containsEntry("two", defaultCacheConfiguration); + }); } @Test void jCacheCacheWithExistingJCacheManager() { this.contextRunner.withUserConfiguration(JCacheCustomCacheManager.class) - .withPropertyValues("spring.cache.type=jcache").run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - assertThat(cacheManager.getCacheManager()).isEqualTo(context.getBean("customJCacheCacheManager")); - }); + .withPropertyValues("spring.cache.type=jcache") + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + assertThat(cacheManager.getCacheManager()).isEqualTo(context.getBean("customJCacheCacheManager")); + }); } @Test void jCacheCacheWithUnknownProvider() { String wrongCachingProviderClassName = "org.acme.FooBar"; this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + wrongCachingProviderClassName) - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining(wrongCachingProviderClassName)); + .withPropertyValues("spring.cache.type=jcache", + "spring.cache.jcache.provider=" + wrongCachingProviderClassName) + .run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining(wrongCachingProviderClassName)); } @Test @@ -403,13 +413,13 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { String cachingProviderFqn = MockCachingProvider.class.getName(); String configLocation = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; this.contextRunner.withUserConfiguration(JCacheCustomConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.jcache.config=" + configLocation) - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - Resource configResource = new ClassPathResource(configLocation); - assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); - }); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.jcache.config=" + configLocation) + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + Resource configResource = new ClassPathResource(configLocation); + assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); + }); } @Test @@ -417,69 +427,72 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { String cachingProviderFqn = MockCachingProvider.class.getName(); String configLocation = "org/springframework/boot/autoconfigure/cache/does-not-exist.xml"; this.contextRunner.withUserConfiguration(JCacheCustomConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.jcache.config=" + configLocation) - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("does not exist").hasMessageContaining(configLocation)); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.jcache.config=" + configLocation) + .run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("does not exist") + .hasMessageContaining(configLocation)); } @Test void jCacheCacheUseBeanClassLoader() { String cachingProviderFqn = MockCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - assertThat(cacheManager.getCacheManager().getClassLoader()).isEqualTo(context.getClassLoader()); - }); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + assertThat(cacheManager.getCacheManager().getClassLoader()).isEqualTo(context.getClassLoader()); + }); } @Test void hazelcastCacheExplicit() { this.contextRunner.withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)) - .withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=hazelcast").run((context) -> { - HazelcastCacheManager cacheManager = getCacheManager(context, HazelcastCacheManager.class); - // NOTE: the hazelcast implementation knows about a cache in a lazy - // manner. - cacheManager.getCache("defaultCache"); - assertThat(cacheManager.getCacheNames()).containsOnly("defaultCache"); - assertThat(context.getBean(HazelcastInstance.class)).isEqualTo(cacheManager.getHazelcastInstance()); - }); + .withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=hazelcast") + .run((context) -> { + HazelcastCacheManager cacheManager = getCacheManager(context, HazelcastCacheManager.class); + // NOTE: the hazelcast implementation knows about a cache in a lazy + // manner. + cacheManager.getCache("defaultCache"); + assertThat(cacheManager.getCacheNames()).containsOnly("defaultCache"); + assertThat(context.getBean(HazelcastInstance.class)).isEqualTo(cacheManager.getHazelcastInstance()); + }); } @Test void hazelcastCacheWithCustomizers() { this.contextRunner.withUserConfiguration(HazelcastCacheAndCustomizersConfiguration.class) - .withPropertyValues("spring.cache.type=hazelcast") - .run(verifyCustomizers("allCacheManagerCustomizer", "hazelcastCacheManagerCustomizer")); + .withPropertyValues("spring.cache.type=hazelcast") + .run(verifyCustomizers("allCacheManagerCustomizer", "hazelcastCacheManagerCustomizer")); } @Test void hazelcastCacheWithExistingHazelcastInstance() { this.contextRunner.withUserConfiguration(HazelcastCustomHazelcastInstance.class) - .withPropertyValues("spring.cache.type=hazelcast").run((context) -> { - HazelcastCacheManager cacheManager = getCacheManager(context, HazelcastCacheManager.class); - assertThat(cacheManager.getHazelcastInstance()) - .isEqualTo(context.getBean("customHazelcastInstance")); - }); + .withPropertyValues("spring.cache.type=hazelcast") + .run((context) -> { + HazelcastCacheManager cacheManager = getCacheManager(context, HazelcastCacheManager.class); + assertThat(cacheManager.getHazelcastInstance()).isEqualTo(context.getBean("customHazelcastInstance")); + }); } @Test void hazelcastCacheWithHazelcastAutoConfiguration() { String hazelcastConfig = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; this.contextRunner.withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)) - .withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=hazelcast", "spring.hazelcast.config=" + hazelcastConfig) - .run((context) -> { - HazelcastCacheManager cacheManager = getCacheManager(context, HazelcastCacheManager.class); - HazelcastInstance hazelcastInstance = context.getBean(HazelcastInstance.class); - assertThat(cacheManager.getHazelcastInstance()).isSameAs(hazelcastInstance); - assertThat(hazelcastInstance.getConfig().getConfigurationFile()) - .isEqualTo(new ClassPathResource(hazelcastConfig).getFile()); - assertThat(cacheManager.getCache("foobar")).isNotNull(); - assertThat(cacheManager.getCacheNames()).containsOnly("foobar"); - }); + .withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=hazelcast", "spring.hazelcast.config=" + hazelcastConfig) + .run((context) -> { + HazelcastCacheManager cacheManager = getCacheManager(context, HazelcastCacheManager.class); + HazelcastInstance hazelcastInstance = context.getBean(HazelcastInstance.class); + assertThat(cacheManager.getHazelcastInstance()).isSameAs(hazelcastInstance); + assertThat(hazelcastInstance.getConfig().getConfigurationFile()) + .isEqualTo(new ClassPathResource(hazelcastConfig).getFile()); + assertThat(cacheManager.getCache("foobar")).isNotNull(); + assertThat(cacheManager.getCacheNames()).containsOnly("foobar"); + }); } @Test @@ -487,14 +500,13 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { String cachingProviderFqn = HazelcastServerCachingProvider.class.getName(); try { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(1); - }); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); + assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(1); + }); } finally { Caching.getCachingProvider(cachingProviderFqn).close(); @@ -507,15 +519,14 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { try { String configLocation = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.jcache.config=" + configLocation) - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - Resource configResource = new ClassPathResource(configLocation); - assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); - assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(1); - }); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.jcache.config=" + configLocation) + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + Resource configResource = new ClassPathResource(configLocation); + assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); + assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(1); + }); } finally { Caching.getCachingProvider(cachingProviderFqn).close(); @@ -526,69 +537,67 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { void hazelcastAsJCacheWithExistingHazelcastInstance() { String cachingProviderFqn = HazelcastServerCachingProvider.class.getName(); this.contextRunner.withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)) - .withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - javax.cache.CacheManager jCacheManager = cacheManager.getCacheManager(); - assertThat(jCacheManager).isInstanceOf(com.hazelcast.cache.HazelcastCacheManager.class); - assertThat(context).hasSingleBean(HazelcastInstance.class); - HazelcastInstance hazelcastInstance = context.getBean(HazelcastInstance.class); - assertThat(((com.hazelcast.cache.HazelcastCacheManager) jCacheManager).getHazelcastInstance()) - .isSameAs(hazelcastInstance); - assertThat(hazelcastInstance.getName()).isEqualTo("default-instance"); - assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(1); - }); + .withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + javax.cache.CacheManager jCacheManager = cacheManager.getCacheManager(); + assertThat(jCacheManager).isInstanceOf(com.hazelcast.cache.HazelcastCacheManager.class); + assertThat(context).hasSingleBean(HazelcastInstance.class); + HazelcastInstance hazelcastInstance = context.getBean(HazelcastInstance.class); + assertThat(((com.hazelcast.cache.HazelcastCacheManager) jCacheManager).getHazelcastInstance()) + .isSameAs(hazelcastInstance); + assertThat(hazelcastInstance.getName()).isEqualTo("default-instance"); + assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(1); + }); } @Test void infinispanCacheWithConfig() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=infinispan", "spring.cache.infinispan.config=infinispan.xml") - .run((context) -> { - SpringEmbeddedCacheManager cacheManager = getCacheManager(context, - SpringEmbeddedCacheManager.class); - assertThat(cacheManager.getCacheNames()).contains("foo", "bar"); - }); + .withPropertyValues("spring.cache.type=infinispan", "spring.cache.infinispan.config=infinispan.xml") + .run((context) -> { + SpringEmbeddedCacheManager cacheManager = getCacheManager(context, SpringEmbeddedCacheManager.class); + assertThat(cacheManager.getCacheNames()).contains("foo", "bar"); + }); } @Test void infinispanCacheWithCustomizers() { this.contextRunner.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) - .withPropertyValues("spring.cache.type=infinispan") - .run(verifyCustomizers("allCacheManagerCustomizer", "infinispanCacheManagerCustomizer")); + .withPropertyValues("spring.cache.type=infinispan") + .run(verifyCustomizers("allCacheManagerCustomizer", "infinispanCacheManagerCustomizer")); } @Test void infinispanCacheWithCaches() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=infinispan", "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") - .run((context) -> assertThat(getCacheManager(context, SpringEmbeddedCacheManager.class).getCacheNames()) - .containsOnly("foo", "bar")); + .withPropertyValues("spring.cache.type=infinispan", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar") + .run((context) -> assertThat(getCacheManager(context, SpringEmbeddedCacheManager.class).getCacheNames()) + .containsOnly("foo", "bar")); } @Test void infinispanCacheWithCachesAndCustomConfig() { this.contextRunner.withUserConfiguration(InfinispanCustomConfiguration.class) - .withPropertyValues("spring.cache.type=infinispan", "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") - .run((context) -> { - assertThat(getCacheManager(context, SpringEmbeddedCacheManager.class).getCacheNames()) - .containsOnly("foo", "bar"); - then(context.getBean(ConfigurationBuilder.class)).should(times(2)).build(); - }); + .withPropertyValues("spring.cache.type=infinispan", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar") + .run((context) -> { + assertThat(getCacheManager(context, SpringEmbeddedCacheManager.class).getCacheNames()) + .containsOnly("foo", "bar"); + then(context.getBean(ConfigurationBuilder.class)).should(times(2)).build(); + }); } @Test void infinispanAsJCacheWithCaches() { String cachingProviderClassName = JCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderClassName, "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") - .run((context) -> assertThat(getCacheManager(context, JCacheCacheManager.class).getCacheNames()) - .containsOnly("foo", "bar")); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderClassName, + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") + .run((context) -> assertThat(getCacheManager(context, JCacheCacheManager.class).getCacheNames()) + .containsOnly("foo", "bar")); } @Test @@ -596,14 +605,13 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { String cachingProviderClassName = JCachingProvider.class.getName(); String configLocation = "infinispan.xml"; this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderClassName, - "spring.cache.jcache.config=" + configLocation) - .run((context) -> { - Resource configResource = new ClassPathResource(configLocation); - assertThat(getCacheManager(context, JCacheCacheManager.class).getCacheManager().getURI()) - .isEqualTo(configResource.getURI()); - }); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderClassName, + "spring.cache.jcache.config=" + configLocation) + .run((context) -> { + Resource configResource = new ClassPathResource(configLocation); + assertThat(getCacheManager(context, JCacheCacheManager.class).getCacheManager().getURI()) + .isEqualTo(configResource.getURI()); + }); } @Test @@ -611,13 +619,12 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { String cachingProviderFqn = HazelcastServerCachingProvider.class.getName(); try { this.contextRunner.withUserConfiguration(JCacheWithCustomizerConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") - .run((context) -> - // see customizer - assertThat(getCacheManager(context, JCacheCacheManager.class).getCacheNames()).containsOnly("foo", - "custom1")); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") + .run((context) -> + // see customizer + assertThat(getCacheManager(context, JCacheCacheManager.class).getCacheNames()).containsOnly("foo", + "custom1")); } finally { Caching.getCachingProvider(cachingProviderFqn).close(); @@ -627,53 +634,54 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { @Test void cache2kCacheWithExplicitCaches() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=cache2k", "spring.cache.cacheNames=foo,bar").run((context) -> { - SpringCache2kCacheManager manager = getCacheManager(context, SpringCache2kCacheManager.class); - assertThat(manager.getCacheNames()).containsExactlyInAnyOrder("foo", "bar"); - }); + .withPropertyValues("spring.cache.type=cache2k", "spring.cache.cacheNames=foo,bar") + .run((context) -> { + SpringCache2kCacheManager manager = getCacheManager(context, SpringCache2kCacheManager.class); + assertThat(manager.getCacheNames()).containsExactlyInAnyOrder("foo", "bar"); + }); } @Test void cache2kCacheWithCustomizedDefaults() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=cache2k") - .withBean(Cache2kBuilderCustomizer.class, - () -> (builder) -> builder.valueType(String.class).loader((key) -> "default")) - .run((context) -> { - SpringCache2kCacheManager manager = getCacheManager(context, SpringCache2kCacheManager.class); - assertThat(manager.getCacheNames()).isEmpty(); - Cache dynamic = manager.getCache("dynamic"); - assertThat(dynamic.get("1")).satisfies(hasEntry("default")); - assertThat(dynamic.get("2")).satisfies(hasEntry("default")); - }); + .withPropertyValues("spring.cache.type=cache2k") + .withBean(Cache2kBuilderCustomizer.class, + () -> (builder) -> builder.valueType(String.class).loader((key) -> "default")) + .run((context) -> { + SpringCache2kCacheManager manager = getCacheManager(context, SpringCache2kCacheManager.class); + assertThat(manager.getCacheNames()).isEmpty(); + Cache dynamic = manager.getCache("dynamic"); + assertThat(dynamic.get("1")).satisfies(hasEntry("default")); + assertThat(dynamic.get("2")).satisfies(hasEntry("default")); + }); } @Test void cache2kCacheWithCustomizedDefaultsAndExplicitCaches() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=cache2k", "spring.cache.cacheNames=foo,bar") - .withBean(Cache2kBuilderCustomizer.class, - () -> (builder) -> builder.valueType(String.class).loader((key) -> "default")) - .run((context) -> { - SpringCache2kCacheManager manager = getCacheManager(context, SpringCache2kCacheManager.class); - assertThat(manager.getCacheNames()).containsExactlyInAnyOrder("foo", "bar"); - assertThat(manager.getCache("foo").get("1")).satisfies(hasEntry("default")); - assertThat(manager.getCache("bar").get("1")).satisfies(hasEntry("default")); - }); + .withPropertyValues("spring.cache.type=cache2k", "spring.cache.cacheNames=foo,bar") + .withBean(Cache2kBuilderCustomizer.class, + () -> (builder) -> builder.valueType(String.class).loader((key) -> "default")) + .run((context) -> { + SpringCache2kCacheManager manager = getCacheManager(context, SpringCache2kCacheManager.class); + assertThat(manager.getCacheNames()).containsExactlyInAnyOrder("foo", "bar"); + assertThat(manager.getCache("foo").get("1")).satisfies(hasEntry("default")); + assertThat(manager.getCache("bar").get("1")).satisfies(hasEntry("default")); + }); } @Test void cache2kCacheWithCacheManagerCustomizer() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=cache2k") - .withBean(CacheManagerCustomizer.class, - () -> cache2kCacheManagerCustomizer((cacheManager) -> cacheManager.addCache("custom", - (builder) -> builder.valueType(String.class).loader((key) -> "custom")))) - .run((context) -> { - SpringCache2kCacheManager manager = getCacheManager(context, SpringCache2kCacheManager.class); - assertThat(manager.getCacheNames()).containsExactlyInAnyOrder("custom"); - assertThat(manager.getCache("custom").get("1")).satisfies(hasEntry("custom")); - }); + .withPropertyValues("spring.cache.type=cache2k") + .withBean(CacheManagerCustomizer.class, + () -> cache2kCacheManagerCustomizer((cacheManager) -> cacheManager.addCache("custom", + (builder) -> builder.valueType(String.class).loader((key) -> "custom")))) + .run((context) -> { + SpringCache2kCacheManager manager = getCacheManager(context, SpringCache2kCacheManager.class); + assertThat(manager.getCacheNames()).containsExactlyInAnyOrder("custom"); + assertThat(manager.getCache("custom").get("1")).satisfies(hasEntry("custom")); + }); } private CacheManagerCustomizer cache2kCacheManagerCustomizer( @@ -684,62 +692,64 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { @Test void cache2kCacheWithCustomizers() { this.contextRunner.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) - .withPropertyValues("spring.cache.type=cache2k") - .run(verifyCustomizers("allCacheManagerCustomizer", "cache2kCacheManagerCustomizer")); + .withPropertyValues("spring.cache.type=cache2k") + .run(verifyCustomizers("allCacheManagerCustomizer", "cache2kCacheManagerCustomizer")); } @Test void caffeineCacheWithExplicitCaches() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=caffeine", "spring.cache.cacheNames=foo").run((context) -> { - CaffeineCacheManager manager = getCacheManager(context, CaffeineCacheManager.class); - assertThat(manager.getCacheNames()).containsOnly("foo"); - Cache foo = manager.getCache("foo"); - foo.get("1"); - // See next tests: no spec given so stats should be disabled - assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()).isEqualTo(0L); - }); + .withPropertyValues("spring.cache.type=caffeine", "spring.cache.cacheNames=foo") + .run((context) -> { + CaffeineCacheManager manager = getCacheManager(context, CaffeineCacheManager.class); + assertThat(manager.getCacheNames()).containsOnly("foo"); + Cache foo = manager.getCache("foo"); + foo.get("1"); + // See next tests: no spec given so stats should be disabled + assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()).isEqualTo(0L); + }); } @Test void caffeineCacheWithCustomizers() { this.contextRunner.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) - .withPropertyValues("spring.cache.type=caffeine") - .run(verifyCustomizers("allCacheManagerCustomizer", "caffeineCacheManagerCustomizer")); + .withPropertyValues("spring.cache.type=caffeine") + .run(verifyCustomizers("allCacheManagerCustomizer", "caffeineCacheManagerCustomizer")); } @Test void caffeineCacheWithExplicitCacheBuilder() { this.contextRunner.withUserConfiguration(CaffeineCacheBuilderConfiguration.class) - .withPropertyValues("spring.cache.type=caffeine", "spring.cache.cacheNames=foo,bar") - .run(this::validateCaffeineCacheWithStats); + .withPropertyValues("spring.cache.type=caffeine", "spring.cache.cacheNames=foo,bar") + .run(this::validateCaffeineCacheWithStats); } @Test void caffeineCacheExplicitWithSpec() { this.contextRunner.withUserConfiguration(CaffeineCacheSpecConfiguration.class) - .withPropertyValues("spring.cache.type=caffeine", "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") - .run(this::validateCaffeineCacheWithStats); + .withPropertyValues("spring.cache.type=caffeine", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar") + .run(this::validateCaffeineCacheWithStats); } @Test void caffeineCacheExplicitWithSpecString() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=caffeine", "spring.cache.caffeine.spec=recordStats", - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .run(this::validateCaffeineCacheWithStats); + .withPropertyValues("spring.cache.type=caffeine", "spring.cache.caffeine.spec=recordStats", + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") + .run(this::validateCaffeineCacheWithStats); } @Test void autoConfiguredCacheManagerCanBeSwapped() { this.contextRunner.withUserConfiguration(CacheManagerPostProcessorConfiguration.class) - .withPropertyValues("spring.cache.type=caffeine").run((context) -> { - getCacheManager(context, SimpleCacheManager.class); - CacheManagerPostProcessor postProcessor = context.getBean(CacheManagerPostProcessor.class); - assertThat(postProcessor.cacheManagers).hasSize(1); - assertThat(postProcessor.cacheManagers.get(0)).isInstanceOf(CaffeineCacheManager.class); - }); + .withPropertyValues("spring.cache.type=caffeine") + .run((context) -> { + getCacheManager(context, SimpleCacheManager.class); + CacheManagerPostProcessor postProcessor = context.getBean(CacheManagerPostProcessor.class); + assertThat(postProcessor.cacheManagers).hasSize(1); + assertThat(postProcessor.cacheManagers.get(0)).isInstanceOf(CaffeineCacheManager.class); + }); } private Consumer hasEntry(Object value) { @@ -844,7 +854,8 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { @Bean org.springframework.data.redis.cache.RedisCacheConfiguration customRedisCacheConfiguration() { return org.springframework.data.redis.cache.RedisCacheConfiguration.defaultCacheConfig() - .entryTtl(java.time.Duration.ofSeconds(30)).prefixCacheNameWith("bar"); + .entryTtl(java.time.Duration.ofSeconds(30)) + .prefixCacheNameWith("bar"); } } @@ -855,8 +866,8 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { @Bean RedisCacheManagerBuilderCustomizer ttlRedisCacheManagerBuilderCustomizer() { - return (builder) -> builder.cacheDefaults( - RedisCacheConfiguration.defaultCacheConfig().entryTtl(java.time.Duration.ofSeconds(10))); + return (builder) -> builder + .cacheDefaults(RedisCacheConfiguration.defaultCacheConfig().entryTtl(java.time.Duration.ofSeconds(10))); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache2CacheAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache2CacheAutoConfigurationTests.java index 25cf51d336..1764cbfd60 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache2CacheAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache2CacheAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,44 +38,45 @@ import static org.assertj.core.api.Assertions.assertThat; class EhCache2CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class)); @Test void ehCacheWithCaches() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=ehcache").run((context) -> { - EhCacheCacheManager cacheManager = getCacheManager(context, EhCacheCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("cacheTest1", "cacheTest2"); - assertThat(context.getBean(net.sf.ehcache.CacheManager.class)) - .isEqualTo(cacheManager.getCacheManager()); - }); + .withPropertyValues("spring.cache.type=ehcache") + .run((context) -> { + EhCacheCacheManager cacheManager = getCacheManager(context, EhCacheCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("cacheTest1", "cacheTest2"); + assertThat(context.getBean(net.sf.ehcache.CacheManager.class)) + .isEqualTo(cacheManager.getCacheManager()); + }); } @Test void ehCacheWithCustomizers() { this.contextRunner.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) - .withPropertyValues("spring.cache.type=ehcache") - .run(verifyCustomizers("allCacheManagerCustomizer", "ehcacheCacheManagerCustomizer")); + .withPropertyValues("spring.cache.type=ehcache") + .run(verifyCustomizers("allCacheManagerCustomizer", "ehcacheCacheManagerCustomizer")); } @Test void ehCacheWithConfig() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=ehcache", - "spring.cache.ehcache.config=cache/ehcache-override.xml") - .run((context) -> { - EhCacheCacheManager cacheManager = getCacheManager(context, EhCacheCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("cacheOverrideTest1", "cacheOverrideTest2"); - }); + .withPropertyValues("spring.cache.type=ehcache", "spring.cache.ehcache.config=cache/ehcache-override.xml") + .run((context) -> { + EhCacheCacheManager cacheManager = getCacheManager(context, EhCacheCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("cacheOverrideTest1", "cacheOverrideTest2"); + }); } @Test void ehCacheWithExistingCacheManager() { this.contextRunner.withUserConfiguration(EhCacheCustomCacheManager.class) - .withPropertyValues("spring.cache.type=ehcache").run((context) -> { - EhCacheCacheManager cacheManager = getCacheManager(context, EhCacheCacheManager.class); - assertThat(cacheManager.getCacheManager()).isEqualTo(context.getBean("customEhCacheCacheManager")); - }); + .withPropertyValues("spring.cache.type=ehcache") + .run((context) -> { + EhCacheCacheManager cacheManager = getCacheManager(context, EhCacheCacheManager.class); + assertThat(cacheManager.getCacheManager()).isEqualTo(context.getBean("customEhCacheCacheManager")); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache3CacheAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache3CacheAutoConfigurationTests.java index d3b0d56ec4..3ee060cffe 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache3CacheAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache3CacheAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,12 +40,12 @@ class EhCache3CacheAutoConfigurationTests extends AbstractCacheAutoConfiguration void ehcache3AsJCacheWithCaches() { String cachingProviderFqn = EhcacheCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - }); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); + }); } @Test @@ -53,15 +53,15 @@ class EhCache3CacheAutoConfigurationTests extends AbstractCacheAutoConfiguration String cachingProviderFqn = EhcacheCachingProvider.class.getName(); String configLocation = "ehcache3.xml"; this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.jcache.config=" + configLocation) - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.jcache.config=" + configLocation) + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - Resource configResource = new ClassPathResource(configLocation); - assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - }); + Resource configResource = new ClassPathResource(configLocation); + assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationIntegrationTests.java index 198289618f..e8a2fc34c2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,19 +46,19 @@ class CassandraAutoConfigurationIntegrationTests { static final CassandraContainer cassandra = new CassandraContainer(); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CassandraAutoConfiguration.class)).withPropertyValues( - "spring.data.cassandra.contact-points:" + cassandra.getHost() + ":" - + cassandra.getFirstMappedPort(), - "spring.data.cassandra.local-datacenter=datacenter1", - "spring.data.cassandra.connection.connect-timeout=60s", - "spring.data.cassandra.connection.init-query-timeout=60s", - "spring.data.cassandra.request.timeout=60s"); + .withConfiguration(AutoConfigurations.of(CassandraAutoConfiguration.class)) + .withPropertyValues( + "spring.data.cassandra.contact-points:" + cassandra.getHost() + ":" + cassandra.getFirstMappedPort(), + "spring.data.cassandra.local-datacenter=datacenter1", + "spring.data.cassandra.connection.connect-timeout=60s", + "spring.data.cassandra.connection.init-query-timeout=60s", "spring.data.cassandra.request.timeout=60s"); @Test void whenTheContextIsClosedThenTheDriverConfigLoaderIsClosed() { this.contextRunner.withUserConfiguration(DriverConfigLoaderSpyConfiguration.class).run((context) -> { assertThat(((BeanDefinitionRegistry) context.getSourceApplicationContext()) - .getBeanDefinition("cassandraDriverConfigLoader").getDestroyMethodName()).isEmpty(); + .getBeanDefinition("cassandraDriverConfigLoader") + .getDestroyMethodName()).isEmpty(); // Initialize lazy bean context.getBean(CqlSession.class); DriverConfigLoader driverConfigLoader = context.getBean(DriverConfigLoader.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java index 971ec02b7e..ebb87e8b25 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; class CassandraAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CassandraAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(CassandraAutoConfiguration.class)); @Test void cqlSessionBuildHasScopePrototype() { @@ -66,96 +66,114 @@ class CassandraAutoConfigurationTests { void driverConfigLoaderWithDefaultConfiguration() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(DriverConfigLoader.class); - assertThat(context.getBean(DriverConfigLoader.class).getInitialConfig().getDefaultProfile() - .isDefined(DefaultDriverOption.SESSION_NAME)).isFalse(); + assertThat(context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile() + .isDefined(DefaultDriverOption.SESSION_NAME)).isFalse(); }); } @Test void driverConfigLoaderWithContactPoints() { - this.contextRunner.withPropertyValues("spring.data.cassandra.contact-points=cluster.example.com:9042", - "spring.data.cassandra.local-datacenter=cassandra-eu1").run((context) -> { - assertThat(context).hasSingleBean(DriverConfigLoader.class); - DriverExecutionProfile configuration = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); - assertThat(configuration.getStringList(DefaultDriverOption.CONTACT_POINTS)) - .containsOnly("cluster.example.com:9042"); - assertThat(configuration.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) - .isEqualTo("cassandra-eu1"); - }); + this.contextRunner + .withPropertyValues("spring.data.cassandra.contact-points=cluster.example.com:9042", + "spring.data.cassandra.local-datacenter=cassandra-eu1") + .run((context) -> { + assertThat(context).hasSingleBean(DriverConfigLoader.class); + DriverExecutionProfile configuration = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); + assertThat(configuration.getStringList(DefaultDriverOption.CONTACT_POINTS)) + .containsOnly("cluster.example.com:9042"); + assertThat(configuration.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) + .isEqualTo("cassandra-eu1"); + }); } @Test void driverConfigLoaderWithContactPointAndNoPort() { this.contextRunner - .withPropertyValues("spring.data.cassandra.contact-points=cluster.example.com,another.example.com:9041", - "spring.data.cassandra.local-datacenter=cassandra-eu1") - .run((context) -> { - assertThat(context).hasSingleBean(DriverConfigLoader.class); - DriverExecutionProfile configuration = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); - assertThat(configuration.getStringList(DefaultDriverOption.CONTACT_POINTS)) - .containsOnly("cluster.example.com:9042", "another.example.com:9041"); - assertThat(configuration.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) - .isEqualTo("cassandra-eu1"); - }); + .withPropertyValues("spring.data.cassandra.contact-points=cluster.example.com,another.example.com:9041", + "spring.data.cassandra.local-datacenter=cassandra-eu1") + .run((context) -> { + assertThat(context).hasSingleBean(DriverConfigLoader.class); + DriverExecutionProfile configuration = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); + assertThat(configuration.getStringList(DefaultDriverOption.CONTACT_POINTS)) + .containsOnly("cluster.example.com:9042", "another.example.com:9041"); + assertThat(configuration.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) + .isEqualTo("cassandra-eu1"); + }); } @Test void driverConfigLoaderWithContactPointAndNoPortAndCustomPort() { this.contextRunner - .withPropertyValues("spring.data.cassandra.contact-points=cluster.example.com:9041,another.example.com", - "spring.data.cassandra.port=9043", "spring.data.cassandra.local-datacenter=cassandra-eu1") - .run((context) -> { - assertThat(context).hasSingleBean(DriverConfigLoader.class); - DriverExecutionProfile configuration = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); - assertThat(configuration.getStringList(DefaultDriverOption.CONTACT_POINTS)) - .containsOnly("cluster.example.com:9041", "another.example.com:9043"); - assertThat(configuration.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) - .isEqualTo("cassandra-eu1"); - }); + .withPropertyValues("spring.data.cassandra.contact-points=cluster.example.com:9041,another.example.com", + "spring.data.cassandra.port=9043", "spring.data.cassandra.local-datacenter=cassandra-eu1") + .run((context) -> { + assertThat(context).hasSingleBean(DriverConfigLoader.class); + DriverExecutionProfile configuration = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); + assertThat(configuration.getStringList(DefaultDriverOption.CONTACT_POINTS)) + .containsOnly("cluster.example.com:9041", "another.example.com:9043"); + assertThat(configuration.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) + .isEqualTo("cassandra-eu1"); + }); } @Test void driverConfigLoaderWithCustomSessionName() { this.contextRunner.withPropertyValues("spring.data.cassandra.session-name=testcluster").run((context) -> { assertThat(context).hasSingleBean(DriverConfigLoader.class); - assertThat(context.getBean(DriverConfigLoader.class).getInitialConfig().getDefaultProfile() - .getString(DefaultDriverOption.SESSION_NAME)).isEqualTo("testcluster"); + assertThat(context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile() + .getString(DefaultDriverOption.SESSION_NAME)).isEqualTo("testcluster"); }); } @Test void driverConfigLoaderWithCustomSessionNameAndCustomizer() { this.contextRunner.withUserConfiguration(SimpleDriverConfigLoaderBuilderCustomizerConfig.class) - .withPropertyValues("spring.data.cassandra.session-name=testcluster").run((context) -> { - assertThat(context).hasSingleBean(DriverConfigLoader.class); - assertThat(context.getBean(DriverConfigLoader.class).getInitialConfig().getDefaultProfile() - .getString(DefaultDriverOption.SESSION_NAME)).isEqualTo("overridden-name"); - }); + .withPropertyValues("spring.data.cassandra.session-name=testcluster") + .run((context) -> { + assertThat(context).hasSingleBean(DriverConfigLoader.class); + assertThat(context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile() + .getString(DefaultDriverOption.SESSION_NAME)).isEqualTo("overridden-name"); + }); } @Test void driverConfigLoaderCustomizeConnectionOptions() { - this.contextRunner.withPropertyValues("spring.data.cassandra.connection.connect-timeout=200ms", - "spring.data.cassandra.connection.init-query-timeout=10").run((context) -> { - DriverExecutionProfile config = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); - assertThat(config.getInt(DefaultDriverOption.CONNECTION_CONNECT_TIMEOUT)).isEqualTo(200); - assertThat(config.getInt(DefaultDriverOption.CONNECTION_INIT_QUERY_TIMEOUT)).isEqualTo(10); - }); + this.contextRunner + .withPropertyValues("spring.data.cassandra.connection.connect-timeout=200ms", + "spring.data.cassandra.connection.init-query-timeout=10") + .run((context) -> { + DriverExecutionProfile config = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); + assertThat(config.getInt(DefaultDriverOption.CONNECTION_CONNECT_TIMEOUT)).isEqualTo(200); + assertThat(config.getInt(DefaultDriverOption.CONNECTION_INIT_QUERY_TIMEOUT)).isEqualTo(10); + }); } @Test void driverConfigLoaderCustomizePoolOptions() { - this.contextRunner.withPropertyValues("spring.data.cassandra.pool.idle-timeout=42", - "spring.data.cassandra.pool.heartbeat-interval=62").run((context) -> { - DriverExecutionProfile config = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); - assertThat(config.getInt(DefaultDriverOption.HEARTBEAT_TIMEOUT)).isEqualTo(42); - assertThat(config.getInt(DefaultDriverOption.HEARTBEAT_INTERVAL)).isEqualTo(62); - }); + this.contextRunner + .withPropertyValues("spring.data.cassandra.pool.idle-timeout=42", + "spring.data.cassandra.pool.heartbeat-interval=62") + .run((context) -> { + DriverExecutionProfile config = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); + assertThat(config.getInt(DefaultDriverOption.HEARTBEAT_TIMEOUT)).isEqualTo(42); + assertThat(config.getInt(DefaultDriverOption.HEARTBEAT_INTERVAL)).isEqualTo(62); + }); } @Test @@ -163,99 +181,113 @@ class CassandraAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.data.cassandra.request.timeout=5s", "spring.data.cassandra.request.consistency=two", "spring.data.cassandra.request.serial-consistency=quorum", "spring.data.cassandra.request.page-size=42") - .run((context) -> { - DriverExecutionProfile config = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); - assertThat(config.getInt(DefaultDriverOption.REQUEST_TIMEOUT)).isEqualTo(5000); - assertThat(config.getString(DefaultDriverOption.REQUEST_CONSISTENCY)).isEqualTo("TWO"); - assertThat(config.getString(DefaultDriverOption.REQUEST_SERIAL_CONSISTENCY)).isEqualTo("QUORUM"); - assertThat(config.getInt(DefaultDriverOption.REQUEST_PAGE_SIZE)).isEqualTo(42); - }); + .run((context) -> { + DriverExecutionProfile config = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); + assertThat(config.getInt(DefaultDriverOption.REQUEST_TIMEOUT)).isEqualTo(5000); + assertThat(config.getString(DefaultDriverOption.REQUEST_CONSISTENCY)).isEqualTo("TWO"); + assertThat(config.getString(DefaultDriverOption.REQUEST_SERIAL_CONSISTENCY)).isEqualTo("QUORUM"); + assertThat(config.getInt(DefaultDriverOption.REQUEST_PAGE_SIZE)).isEqualTo(42); + }); } @Test void driverConfigLoaderCustomizeControlConnectionOptions() { this.contextRunner.withPropertyValues("spring.data.cassandra.controlconnection.timeout=200ms") - .run((context) -> { - DriverExecutionProfile config = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); - assertThat(config.getInt(DefaultDriverOption.CONTROL_CONNECTION_TIMEOUT)).isEqualTo(200); - }); + .run((context) -> { + DriverExecutionProfile config = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); + assertThat(config.getInt(DefaultDriverOption.CONTROL_CONNECTION_TIMEOUT)).isEqualTo(200); + }); } @Test void driverConfigLoaderUsePassThroughLimitingRequestThrottlerByDefault() { this.contextRunner.withPropertyValues().run((context) -> { - DriverExecutionProfile config = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); + DriverExecutionProfile config = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); assertThat(config.getString(DefaultDriverOption.REQUEST_THROTTLER_CLASS)) - .isEqualTo(PassThroughRequestThrottler.class.getSimpleName()); + .isEqualTo(PassThroughRequestThrottler.class.getSimpleName()); }); } @Test void driverConfigLoaderWithRateLimitingRequiresExtraConfiguration() { this.contextRunner.withPropertyValues("spring.data.cassandra.request.throttler.type=rate-limiting") - .run((context) -> assertThatThrownBy(() -> context.getBean(CqlSession.class)) - .hasMessageContaining("Error instantiating class RateLimitingRequestThrottler") - .hasMessageContaining("No configuration setting found for key")); + .run((context) -> assertThatThrownBy(() -> context.getBean(CqlSession.class)) + .hasMessageContaining("Error instantiating class RateLimitingRequestThrottler") + .hasMessageContaining("No configuration setting found for key")); } @Test void driverConfigLoaderCustomizeConcurrencyLimitingRequestThrottler() { - this.contextRunner.withPropertyValues("spring.data.cassandra.request.throttler.type=concurrency-limiting", - "spring.data.cassandra.request.throttler.max-concurrent-requests=62", - "spring.data.cassandra.request.throttler.max-queue-size=72").run((context) -> { - DriverExecutionProfile config = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); - assertThat(config.getString(DefaultDriverOption.REQUEST_THROTTLER_CLASS)) - .isEqualTo(ConcurrencyLimitingRequestThrottler.class.getSimpleName()); - assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_CONCURRENT_REQUESTS)) - .isEqualTo(62); - assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_QUEUE_SIZE)).isEqualTo(72); - }); + this.contextRunner + .withPropertyValues("spring.data.cassandra.request.throttler.type=concurrency-limiting", + "spring.data.cassandra.request.throttler.max-concurrent-requests=62", + "spring.data.cassandra.request.throttler.max-queue-size=72") + .run((context) -> { + DriverExecutionProfile config = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); + assertThat(config.getString(DefaultDriverOption.REQUEST_THROTTLER_CLASS)) + .isEqualTo(ConcurrencyLimitingRequestThrottler.class.getSimpleName()); + assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_CONCURRENT_REQUESTS)).isEqualTo(62); + assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_QUEUE_SIZE)).isEqualTo(72); + }); } @Test void driverConfigLoaderCustomizeRateLimitingRequestThrottler() { - this.contextRunner.withPropertyValues("spring.data.cassandra.request.throttler.type=rate-limiting", - "spring.data.cassandra.request.throttler.max-requests-per-second=62", - "spring.data.cassandra.request.throttler.max-queue-size=72", - "spring.data.cassandra.request.throttler.drain-interval=16ms").run((context) -> { - DriverExecutionProfile config = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); - assertThat(config.getString(DefaultDriverOption.REQUEST_THROTTLER_CLASS)) - .isEqualTo(RateLimitingRequestThrottler.class.getSimpleName()); - assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_REQUESTS_PER_SECOND)) - .isEqualTo(62); - assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_QUEUE_SIZE)).isEqualTo(72); - assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_DRAIN_INTERVAL)).isEqualTo(16); - }); + this.contextRunner + .withPropertyValues("spring.data.cassandra.request.throttler.type=rate-limiting", + "spring.data.cassandra.request.throttler.max-requests-per-second=62", + "spring.data.cassandra.request.throttler.max-queue-size=72", + "spring.data.cassandra.request.throttler.drain-interval=16ms") + .run((context) -> { + DriverExecutionProfile config = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); + assertThat(config.getString(DefaultDriverOption.REQUEST_THROTTLER_CLASS)) + .isEqualTo(RateLimitingRequestThrottler.class.getSimpleName()); + assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_REQUESTS_PER_SECOND)).isEqualTo(62); + assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_QUEUE_SIZE)).isEqualTo(72); + assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_DRAIN_INTERVAL)).isEqualTo(16); + }); } @Test void driverConfigLoaderWithConfigComplementSettings() { String configLocation = "org/springframework/boot/autoconfigure/cassandra/simple.conf"; - this.contextRunner.withPropertyValues("spring.data.cassandra.session-name=testcluster", - "spring.data.cassandra.config=" + configLocation).run((context) -> { - assertThat(context).hasSingleBean(DriverConfigLoader.class); - assertThat(context.getBean(DriverConfigLoader.class).getInitialConfig().getDefaultProfile() - .getString(DefaultDriverOption.SESSION_NAME)).isEqualTo("testcluster"); - assertThat(context.getBean(DriverConfigLoader.class).getInitialConfig().getDefaultProfile() - .getDuration(DefaultDriverOption.REQUEST_TIMEOUT)).isEqualTo(Duration.ofMillis(500)); - }); + this.contextRunner + .withPropertyValues("spring.data.cassandra.session-name=testcluster", + "spring.data.cassandra.config=" + configLocation) + .run((context) -> { + assertThat(context).hasSingleBean(DriverConfigLoader.class); + assertThat(context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile() + .getString(DefaultDriverOption.SESSION_NAME)).isEqualTo("testcluster"); + assertThat(context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile() + .getDuration(DefaultDriverOption.REQUEST_TIMEOUT)).isEqualTo(Duration.ofMillis(500)); + }); } @Test // gh-31238 void driverConfigLoaderWithConfigOverridesDefaults() { String configLocation = "org/springframework/boot/autoconfigure/cassandra/override-defaults.conf"; this.contextRunner.withPropertyValues("spring.data.cassandra.config=" + configLocation).run((context) -> { - DriverExecutionProfile actual = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); + DriverExecutionProfile actual = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); assertThat(actual.getString(DefaultDriverOption.SESSION_NAME)).isEqualTo("advanced session"); assertThat(actual.getDuration(DefaultDriverOption.REQUEST_TIMEOUT)).isEqualTo(Duration.ofSeconds(2)); assertThat(actual.getStringList(DefaultDriverOption.CONTACT_POINTS)) - .isEqualTo(Collections.singletonList("1.2.3.4:5678")); + .isEqualTo(Collections.singletonList("1.2.3.4:5678")); assertThat(actual.getBoolean(DefaultDriverOption.RESOLVE_CONTACT_POINTS)).isFalse(); assertThat(actual.getInt(DefaultDriverOption.REQUEST_PAGE_SIZE)).isEqualTo(11); assertThat(actual.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)).isEqualTo("datacenter1"); @@ -263,7 +295,7 @@ class CassandraAutoConfigurationTests { assertThat(actual.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_REQUESTS_PER_SECOND)).isEqualTo(33); assertThat(actual.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_QUEUE_SIZE)).isEqualTo(44); assertThat(actual.getDuration(DefaultDriverOption.CONTROL_CONNECTION_TIMEOUT)) - .isEqualTo(Duration.ofMillis(5555)); + .isEqualTo(Duration.ofMillis(5555)); assertThat(actual.getString(DefaultDriverOption.PROTOCOL_COMPRESSION)).isEqualTo("SNAPPY"); }); } @@ -276,7 +308,7 @@ class CassandraAutoConfigurationTests { DriverConfig driverConfig = context.getBean(DriverConfigLoader.class).getInitialConfig(); assertThat(driverConfig.getProfiles()).containsOnlyKeys("default", "first", "second"); assertThat(driverConfig.getProfile("first").getDuration(DefaultDriverOption.REQUEST_TIMEOUT)) - .isEqualTo(Duration.ofMillis(100)); + .isEqualTo(Duration.ofMillis(100)); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationWithPasswordAuthenticationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationWithPasswordAuthenticationIntegrationTests.java index 84baa16093..ac8bb932ba 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationWithPasswordAuthenticationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationWithPasswordAuthenticationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,34 +52,35 @@ class CassandraAutoConfigurationWithPasswordAuthenticationIntegrationTests { @Container static final CassandraContainer cassandra = new PasswordAuthenticatorCassandraContainer().withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(10)).waitingFor(new CassandraWaitStrategy()); + .withStartupTimeout(Duration.ofMinutes(10)) + .waitingFor(new CassandraWaitStrategy()); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CassandraAutoConfiguration.class)).withPropertyValues( - "spring.data.cassandra.contact-points:" + cassandra.getHost() + ":" - + cassandra.getFirstMappedPort(), - "spring.data.cassandra.local-datacenter=datacenter1", - "spring.data.cassandra.connection.connect-timeout=60s", - "spring.data.cassandra.connection.init-query-timeout=60s", - "spring.data.cassandra.request.timeout=60s"); + .withConfiguration(AutoConfigurations.of(CassandraAutoConfiguration.class)) + .withPropertyValues( + "spring.data.cassandra.contact-points:" + cassandra.getHost() + ":" + cassandra.getFirstMappedPort(), + "spring.data.cassandra.local-datacenter=datacenter1", + "spring.data.cassandra.connection.connect-timeout=60s", + "spring.data.cassandra.connection.init-query-timeout=60s", "spring.data.cassandra.request.timeout=60s"); @Test void authenticationWithValidUsernameAndPassword() { - this.contextRunner.withPropertyValues("spring.data.cassandra.username=cassandra", - "spring.data.cassandra.password=cassandra").run((context) -> { - SimpleStatement select = SimpleStatement.newInstance("SELECT release_version FROM system.local") - .setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); - assertThat(context.getBean(CqlSession.class).execute(select).one()).isNotNull(); - }); + this.contextRunner + .withPropertyValues("spring.data.cassandra.username=cassandra", "spring.data.cassandra.password=cassandra") + .run((context) -> { + SimpleStatement select = SimpleStatement.newInstance("SELECT release_version FROM system.local") + .setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); + assertThat(context.getBean(CqlSession.class).execute(select).one()).isNotNull(); + }); } @Test void authenticationWithInvalidCredentials() { this.contextRunner - .withPropertyValues("spring.data.cassandra.username=not-a-user", - "spring.data.cassandra.password=invalid-password") - .run((context) -> assertThatThrownBy(() -> context.getBean(CqlSession.class)) - .hasMessageContaining("Authentication error")); + .withPropertyValues("spring.data.cassandra.username=not-a-user", + "spring.data.cassandra.password=invalid-password") + .run((context) -> assertThatThrownBy(() -> context.getBean(CqlSession.class)) + .hasMessageContaining("Authentication error")); } static final class PasswordAuthenticatorCassandraContainer extends CassandraContainer { @@ -114,9 +115,10 @@ class CassandraAutoConfigurationWithPasswordAuthenticationIntegrationTests { private CqlSessionBuilder cqlSessionBuilder() { return CqlSession.builder() - .addContactPoint(new InetSocketAddress(this.waitStrategyTarget.getHost(), - this.waitStrategyTarget.getFirstMappedPort())) - .withLocalDatacenter("datacenter1").withAuthCredentials("cassandra", "cassandra"); + .addContactPoint(new InetSocketAddress(this.waitStrategyTarget.getHost(), + this.waitStrategyTarget.getFirstMappedPort())) + .withLocalDatacenter("datacenter1") + .withAuthCredentials("cassandra", "cassandra"); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraPropertiesTests.java index abb2e6fb9e..c544c0d803 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,14 +44,14 @@ class CassandraPropertiesTests { assertThat(driverDefaults.get(TypedDriverOption.CONNECTION_CONNECT_TIMEOUT)).isEqualTo(Duration.ofSeconds(5)); // spring.data.cassandra.connection.init-query-timeout assertThat(driverDefaults.get(TypedDriverOption.CONNECTION_INIT_QUERY_TIMEOUT)) - .isEqualTo(Duration.ofSeconds(5)); + .isEqualTo(Duration.ofSeconds(5)); // spring.data.cassandra.request.timeout assertThat(driverDefaults.get(TypedDriverOption.REQUEST_TIMEOUT)).isEqualTo(Duration.ofSeconds(2)); // spring.data.cassandra.request.page-size assertThat(driverDefaults.get(TypedDriverOption.REQUEST_PAGE_SIZE)).isEqualTo(5000); // spring.data.cassandra.request.throttler.type assertThat(driverDefaults.get(TypedDriverOption.REQUEST_THROTTLER_CLASS)) - .isEqualTo("PassThroughRequestThrottler"); // "none" + .isEqualTo("PassThroughRequestThrottler"); // "none" // spring.data.cassandra.pool.heartbeat-interval assertThat(driverDefaults.get(TypedDriverOption.HEARTBEAT_INTERVAL)).isEqualTo(Duration.ofSeconds(30)); // spring.data.cassandra.pool.idle-timeout diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AbstractNestedConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AbstractNestedConditionTests.java index 830af0c1e4..6a723472bf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AbstractNestedConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AbstractNestedConditionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ class AbstractNestedConditionTests { @Test void validPhase() { this.contextRunner.withUserConfiguration(ValidConfig.class) - .run((context) -> assertThat(context).hasBean("myBean")); + .run((context) -> assertThat(context).hasBean("myBean")); } @Test @@ -45,9 +45,9 @@ class AbstractNestedConditionTests { this.contextRunner.withUserConfiguration(InvalidConfig.class).run((context) -> { assertThat(context).hasFailed(); assertThat(context.getStartupFailure().getCause()).isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Nested condition " + InvalidNestedCondition.class.getName() - + " uses a configuration phase that is inappropriate for class " - + OnBeanCondition.class.getName()); + .hasMessageContaining("Nested condition " + InvalidNestedCondition.class.getName() + + " uses a configuration phase that is inappropriate for class " + + OnBeanCondition.class.getName()); }); } @@ -56,9 +56,9 @@ class AbstractNestedConditionTests { this.contextRunner.withUserConfiguration(DoubleNestedConfig.class).run((context) -> { assertThat(context).hasFailed(); assertThat(context.getStartupFailure().getCause()).isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Nested condition " + DoubleNestedCondition.class.getName() - + " uses a configuration phase that is inappropriate for class " - + ValidNestedCondition.class.getName()); + .hasMessageContaining("Nested condition " + DoubleNestedCondition.class.getName() + + " uses a configuration phase that is inappropriate for class " + + ValidNestedCondition.class.getName()); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java index e090fc0225..0e0ad4eb34 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,9 +53,9 @@ class ConditionEvaluationReportAutoConfigurationImportListenerTests { @Test void shouldBeInSpringFactories() { List factories = SpringFactoriesLoader - .loadFactories(AutoConfigurationImportListener.class, null); + .loadFactories(AutoConfigurationImportListener.class, null); assertThat(factories) - .hasAtLeastOneElementOfType(ConditionEvaluationReportAutoConfigurationImportListener.class); + .hasAtLeastOneElementOfType(ConditionEvaluationReportAutoConfigurationImportListener.class); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java index 2a627c33c9..6c390912e1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -98,7 +98,7 @@ class ConditionEvaluationReportTests { ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory.getParentBeanFactory()); assertThat(this.report).isSameAs(ConditionEvaluationReport.get(this.beanFactory)); assertThat(this.report.getParent()).isSameAs(ConditionEvaluationReport - .get((ConfigurableListableBeanFactory) this.beanFactory.getParentBeanFactory())); + .get((ConfigurableListableBeanFactory) this.beanFactory.getParentBeanFactory())); } @Test @@ -163,7 +163,7 @@ class ConditionEvaluationReportTests { @SuppressWarnings("resource") void springBootConditionPopulatesReport() { ConditionEvaluationReport report = ConditionEvaluationReport - .get(new AnnotationConfigApplicationContext(Config.class).getBeanFactory()); + .get(new AnnotationConfigApplicationContext(Config.class).getBeanFactory()); assertThat(report.getConditionAndOutcomesBySource().size()).isNotEqualTo(0); } @@ -246,7 +246,7 @@ class ConditionEvaluationReportTests { "org.springframework.boot.autoconfigure.condition.config.first.SampleAutoConfiguration", "org.springframework.boot.autoconfigure.condition.config.second.SampleAutoConfiguration"); assertThat(reportMessage) - .doesNotContain("org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration"); + .doesNotContain("org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration"); context.close(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java index d8c47ecccc..f941a375b4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -146,15 +146,17 @@ class ConditionMessageTests { @Test void foundWhenMultipleElementsShouldUsePlural() { - ConditionMessage message = ConditionMessage.forCondition(Test.class).found("bean", "beans").items("a", "b", - "c"); + ConditionMessage message = ConditionMessage.forCondition(Test.class) + .found("bean", "beans") + .items("a", "b", "c"); assertThat(message.toString()).isEqualTo("@Test found beans a, b, c"); } @Test void foundWhenQuoteStyleShouldQuote() { - ConditionMessage message = ConditionMessage.forCondition(Test.class).found("bean", "beans").items(Style.QUOTE, - "a", "b", "c"); + ConditionMessage message = ConditionMessage.forCondition(Test.class) + .found("bean", "beans") + .items(Style.QUOTE, "a", "b", "c"); assertThat(message.toString()).isEqualTo("@Test found beans 'a', 'b', 'c'"); } @@ -166,8 +168,9 @@ class ConditionMessageTests { @Test void didNotFindWhenMultipleElementsShouldUsePlural() { - ConditionMessage message = ConditionMessage.forCondition(Test.class).didNotFind("class", "classes").items("a", - "b", "c"); + ConditionMessage message = ConditionMessage.forCondition(Test.class) + .didNotFind("class", "classes") + .items("a", "b", "c"); assertThat(message.toString()).isEqualTo("@Test did not find classes a, b, c"); } @@ -199,8 +202,9 @@ class ConditionMessageTests { @Test void quotedItemsTolerateNullInput() { Collection items = null; - ConditionMessage message = ConditionMessage.forCondition(Test.class).didNotFind("item").items(Style.QUOTE, - items); + ConditionMessage message = ConditionMessage.forCondition(Test.class) + .didNotFind("item") + .items(Style.QUOTE, items); assertThat(message.toString()).isEqualTo("@Test did not find item"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java index 5bfb79e00d..b00658cbe1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,76 +59,76 @@ class ConditionalOnBeanTests { @Test void testNameOnBeanCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanNameConfiguration.class) - .run(this::hasBarBean); + .run(this::hasBarBean); } @Test void testNameAndTypeOnBeanCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanNameAndTypeConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("bar")); + .run((context) -> assertThat(context).doesNotHaveBean("bar")); } @Test void testNameOnBeanConditionReverseOrder() { // Ideally this should be true this.contextRunner.withUserConfiguration(OnBeanNameConfiguration.class, FooConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("bar")); + .run((context) -> assertThat(context).doesNotHaveBean("bar")); } @Test void testClassOnBeanCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanClassConfiguration.class) - .run(this::hasBarBean); + .run(this::hasBarBean); } @Test void testClassOnBeanClassNameCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanClassNameConfiguration.class) - .run(this::hasBarBean); + .run(this::hasBarBean); } @Test void testOnBeanConditionWithXml() { this.contextRunner.withUserConfiguration(XmlConfiguration.class, OnBeanNameConfiguration.class) - .run(this::hasBarBean); + .run(this::hasBarBean); } @Test void testOnBeanConditionWithCombinedXml() { // Ideally this should be true this.contextRunner.withUserConfiguration(CombinedXmlConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("bar")); + .run((context) -> assertThat(context).doesNotHaveBean("bar")); } @Test void testAnnotationOnBeanCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnAnnotationConfiguration.class) - .run(this::hasBarBean); + .run(this::hasBarBean); } @Test void testOnMissingBeanType() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanMissingClassConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("bar")); + .run((context) -> assertThat(context).doesNotHaveBean("bar")); } @Test void withPropertyPlaceholderClassName() { this.contextRunner - .withUserConfiguration(PropertySourcesPlaceholderConfigurer.class, - WithPropertyPlaceholderClassName.class, OnBeanClassConfiguration.class) - .withPropertyValues("mybeanclass=java.lang.String") - .run((context) -> assertThat(context).hasNotFailed()); + .withUserConfiguration(PropertySourcesPlaceholderConfigurer.class, WithPropertyPlaceholderClassName.class, + OnBeanClassConfiguration.class) + .withPropertyValues("mybeanclass=java.lang.String") + .run((context) -> assertThat(context).hasNotFailed()); } @Test void beanProducedByFactoryBeanIsConsideredWhenMatchingOnAnnotation() { this.contextRunner - .withUserConfiguration(FactoryBeanConfiguration.class, OnAnnotationWithFactoryBeanConfiguration.class) - .run((context) -> { - assertThat(context).hasBean("bar"); - assertThat(context).hasSingleBean(ExampleBean.class); - }); + .withUserConfiguration(FactoryBeanConfiguration.class, OnAnnotationWithFactoryBeanConfiguration.class) + .run((context) -> { + assertThat(context).hasBean("bar"); + assertThat(context).hasSingleBean(ExampleBean.class); + }); } private void hasBarBean(AssertableApplicationContext context) { @@ -140,8 +140,9 @@ class ConditionalOnBeanTests { void onBeanConditionOutputShouldNotContainConditionalOnMissingBeanClassInMessage() { this.contextRunner.withUserConfiguration(OnBeanNameConfiguration.class).run((context) -> { Collection conditionAndOutcomes = ConditionEvaluationReport - .get(context.getSourceApplicationContext().getBeanFactory()).getConditionAndOutcomesBySource() - .values(); + .get(context.getSourceApplicationContext().getBeanFactory()) + .getConditionAndOutcomesBySource() + .values(); String message = conditionAndOutcomes.iterator().next().iterator().next().getOutcome().getMessage(); assertThat(message).doesNotContain("@ConditionalOnMissingBean"); }); @@ -149,81 +150,81 @@ class ConditionalOnBeanTests { @Test void conditionEvaluationConsidersChangeInTypeWhenBeanIsOverridden() { - this.contextRunner.withAllowBeanDefinitionOverriding(true).withUserConfiguration(OriginalDefinition.class, - OverridingDefinition.class, ConsumingConfiguration.class).run((context) -> { - assertThat(context).hasBean("testBean"); - assertThat(context).hasSingleBean(Integer.class); - assertThat(context).doesNotHaveBean(ConsumingConfiguration.class); - }); + this.contextRunner.withAllowBeanDefinitionOverriding(true) + .withUserConfiguration(OriginalDefinition.class, OverridingDefinition.class, ConsumingConfiguration.class) + .run((context) -> { + assertThat(context).hasBean("testBean"); + assertThat(context).hasSingleBean(Integer.class); + assertThat(context).doesNotHaveBean(ConsumingConfiguration.class); + }); } @Test void parameterizedContainerWhenValueIsOfMissingBeanDoesNotMatch() { this.contextRunner - .withUserConfiguration(ParameterizedWithoutCustomConfig.class, - ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("otherExampleBean"))); + .withUserConfiguration(ParameterizedWithoutCustomConfig.class, ParameterizedConditionWithValueConfig.class) + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("otherExampleBean"))); } @Test void parameterizedContainerWhenValueIsOfExistingBeanMatches() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithValueConfig.class) + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); } @Test void parameterizedContainerWhenValueIsOfMissingBeanRegistrationDoesNotMatch() { this.contextRunner - .withUserConfiguration(ParameterizedWithoutCustomContainerConfig.class, - ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("otherExampleBean"))); + .withUserConfiguration(ParameterizedWithoutCustomContainerConfig.class, + ParameterizedConditionWithValueConfig.class) + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("otherExampleBean"))); } @Test void parameterizedContainerWhenValueIsOfExistingBeanRegistrationMatches() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, - ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, + ParameterizedConditionWithValueConfig.class) + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); } @Test void parameterizedContainerWhenReturnTypeIsOfExistingBeanMatches() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomConfig.class, - ParameterizedConditionWithReturnTypeConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomConfig.class, + ParameterizedConditionWithReturnTypeConfig.class) + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); } @Test void parameterizedContainerWhenReturnTypeIsOfExistingBeanRegistrationMatches() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, - ParameterizedConditionWithReturnTypeConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, + ParameterizedConditionWithReturnTypeConfig.class) + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); } @Test void parameterizedContainerWhenReturnRegistrationTypeIsOfExistingBeanMatches() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomConfig.class, - ParameterizedConditionWithReturnRegistrationTypeConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomConfig.class, + ParameterizedConditionWithReturnRegistrationTypeConfig.class) + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); } @Test void parameterizedContainerWhenReturnRegistrationTypeIsOfExistingBeanRegistrationMatches() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, - ParameterizedConditionWithReturnRegistrationTypeConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, + ParameterizedConditionWithReturnRegistrationTypeConfig.class) + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); } private Consumer exampleBeanRequirement(String... names) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java index 3bd18519c1..ceb4cd2bdb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class ConditionalOnClassTests { @Test void testVanillaOnClassCondition() { this.contextRunner.withUserConfiguration(BasicConfiguration.class, FooConfiguration.class) - .run(this::hasBarBean); + .run(this::hasBarBean); } @Test @@ -57,7 +57,7 @@ class ConditionalOnClassTests { @Test void testOnClassConditionWithXml() { this.contextRunner.withUserConfiguration(BasicConfiguration.class, XmlConfiguration.class) - .run(this::hasBarBean); + .run(this::hasBarBean); } @Test @@ -69,8 +69,9 @@ class ConditionalOnClassTests { void onClassConditionOutputShouldNotContainConditionalOnMissingClassInMessage() { this.contextRunner.withUserConfiguration(BasicConfiguration.class).run((context) -> { Collection conditionAndOutcomes = ConditionEvaluationReport - .get(context.getSourceApplicationContext().getBeanFactory()).getConditionAndOutcomesBySource() - .values(); + .get(context.getSourceApplicationContext().getBeanFactory()) + .getConditionAndOutcomesBySource() + .values(); String message = conditionAndOutcomes.iterator().next().iterator().next().getOutcome().getMessage(); assertThat(message).doesNotContain("@ConditionalOnMissingClass did not find unwanted class"); }); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java index 8cdeafcefd..76c3f3feb7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,19 +35,21 @@ class ConditionalOnCloudPlatformTests { @Test void outcomeWhenCloudfoundryPlatformNotPresentShouldNotMatch() { this.contextRunner.withUserConfiguration(CloudFoundryPlatformConfig.class) - .run((context) -> assertThat(context).doesNotHaveBean("foo")); + .run((context) -> assertThat(context).doesNotHaveBean("foo")); } @Test void outcomeWhenCloudfoundryPlatformPresentShouldMatch() { this.contextRunner.withUserConfiguration(CloudFoundryPlatformConfig.class) - .withPropertyValues("VCAP_APPLICATION:---").run((context) -> assertThat(context).hasBean("foo")); + .withPropertyValues("VCAP_APPLICATION:---") + .run((context) -> assertThat(context).hasBean("foo")); } @Test void outcomeWhenCloudfoundryPlatformPresentAndMethodTargetShouldMatch() { this.contextRunner.withUserConfiguration(CloudFoundryPlatformOnMethodConfig.class) - .withPropertyValues("VCAP_APPLICATION:---").run((context) -> assertThat(context).hasBean("foo")); + .withPropertyValues("VCAP_APPLICATION:---") + .run((context) -> assertThat(context).hasBean("foo")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java index 9316faba01..36cb94382c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,19 +44,19 @@ class ConditionalOnExpressionTests { @Test void expressionIsTrue() { this.contextRunner.withUserConfiguration(BasicConfiguration.class) - .run((context) -> assertThat(context.getBean("foo")).isEqualTo("foo")); + .run((context) -> assertThat(context.getBean("foo")).isEqualTo("foo")); } @Test void expressionEvaluatesToTrueRegistersBean() { this.contextRunner.withUserConfiguration(MissingConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("foo")); + .run((context) -> assertThat(context).doesNotHaveBean("foo")); } @Test void expressionEvaluatesToFalseDoesNotRegisterBean() { this.contextRunner.withUserConfiguration(NullConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("foo")); + .run((context) -> assertThat(context).doesNotHaveBean("foo")); } @Test @@ -73,7 +73,7 @@ class ConditionalOnExpressionTests { private AnnotatedTypeMetadata mockMetaData(String value) { AnnotatedTypeMetadata metadata = mock(AnnotatedTypeMetadata.class); given(metadata.getAnnotationAttributes(ConditionalOnExpression.class.getName())) - .willReturn(Collections.singletonMap("value", value)); + .willReturn(Collections.singletonMap("value", value)); return metadata; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java index f9ef8ab066..f5ed4acbd7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,19 +51,19 @@ class ConditionalOnJavaTests { @EnabledOnJre(JRE.JAVA_8) void doesNotMatchIfBetterVersionIsRequired() { this.contextRunner.withUserConfiguration(Java9Required.class) - .run((context) -> assertThat(context).doesNotHaveBean(String.class)); + .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test void doesNotMatchIfLowerIsRequired() { this.contextRunner.withUserConfiguration(Java7Required.class) - .run((context) -> assertThat(context).doesNotHaveBean(String.class)); + .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test void matchesIfVersionIsInRange() { this.contextRunner.withUserConfiguration(Java8Required.class) - .run((context) -> assertThat(context).hasSingleBean(String.class)); + .run((context) -> assertThat(context).hasSingleBean(String.class)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java index 4e470ab631..3a6195b918 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,21 +74,21 @@ class ConditionalOnJndiTests { @Test void jndiNotAvailable() { this.contextRunner.withUserConfiguration(JndiAvailableConfiguration.class, JndiConditionConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(String.class)); + .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test void jndiAvailable() { setupJndi(); this.contextRunner.withUserConfiguration(JndiAvailableConfiguration.class, JndiConditionConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(String.class)); + .run((context) -> assertThat(context).hasSingleBean(String.class)); } @Test void jndiLocationNotBound() { setupJndi(); this.contextRunner.withUserConfiguration(JndiConditionConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(String.class)); + .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test @@ -96,7 +96,7 @@ class ConditionalOnJndiTests { setupJndi(); TestableInitialContextFactory.bind("java:/FooManager", new Object()); this.contextRunner.withUserConfiguration(JndiConditionConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(String.class)); + .run((context) -> assertThat(context).hasSingleBean(String.class)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java index f7087dd233..b06ab09f2f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,21 +68,21 @@ class ConditionalOnMissingBeanTests { @Test void testNameOnMissingBeanCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanNameConfiguration.class) - .run((context) -> { - assertThat(context).doesNotHaveBean("bar"); - assertThat(context.getBean("foo")).isEqualTo("foo"); - }); + .run((context) -> { + assertThat(context).doesNotHaveBean("bar"); + assertThat(context.getBean("foo")).isEqualTo("foo"); + }); } @Test void testNameOnMissingBeanConditionReverseOrder() { this.contextRunner.withUserConfiguration(OnBeanNameConfiguration.class, FooConfiguration.class) - .run((context) -> { - // Ideally this would be doesNotHaveBean, but the ordering is a - // problem - assertThat(context).hasBean("bar"); - assertThat(context.getBean("foo")).isEqualTo("foo"); - }); + .run((context) -> { + // Ideally this would be doesNotHaveBean, but the ordering is a + // problem + assertThat(context).hasBean("bar"); + assertThat(context.getBean("foo")).isEqualTo("foo"); + }); } @Test @@ -91,59 +91,60 @@ class ConditionalOnMissingBeanTests { // specified in the different attributes of @ConditionalOnBean are combined with // logical OR (not AND) so if any of them match the condition is true. this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanNameAndTypeConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("bar")); + .run((context) -> assertThat(context).doesNotHaveBean("bar")); } @Test void hierarchyConsidered() { this.contextRunner.withUserConfiguration(FooConfiguration.class) - .run((parent) -> new ApplicationContextRunner().withParent(parent) - .withUserConfiguration(HierarchyConsidered.class) - .run((context) -> assertThat(context.containsLocalBean("bar")).isFalse())); + .run((parent) -> new ApplicationContextRunner().withParent(parent) + .withUserConfiguration(HierarchyConsidered.class) + .run((context) -> assertThat(context.containsLocalBean("bar")).isFalse())); } @Test void hierarchyNotConsidered() { this.contextRunner.withUserConfiguration(FooConfiguration.class) - .run((parent) -> new ApplicationContextRunner().withParent(parent) - .withUserConfiguration(HierarchyNotConsidered.class) - .run((context) -> assertThat(context.containsLocalBean("bar")).isTrue())); + .run((parent) -> new ApplicationContextRunner().withParent(parent) + .withUserConfiguration(HierarchyNotConsidered.class) + .run((context) -> assertThat(context.containsLocalBean("bar")).isTrue())); } @Test void impliedOnBeanMethod() { this.contextRunner.withUserConfiguration(ExampleBeanConfiguration.class, ImpliedOnBeanMethod.class) - .run((context) -> assertThat(context).hasSingleBean(ExampleBean.class)); + .run((context) -> assertThat(context).hasSingleBean(ExampleBean.class)); } @Test void testAnnotationOnMissingBeanCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnAnnotationConfiguration.class) - .run((context) -> { - assertThat(context).doesNotHaveBean("bar"); - assertThat(context.getBean("foo")).isEqualTo("foo"); - }); + .run((context) -> { + assertThat(context).doesNotHaveBean("bar"); + assertThat(context.getBean("foo")).isEqualTo("foo"); + }); } @Test void testAnnotationOnMissingBeanConditionWithEagerFactoryBean() { // Rigorous test for SPR-11069 this.contextRunner - .withUserConfiguration(FooConfiguration.class, OnAnnotationConfiguration.class, - FactoryBeanXmlConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .run((context) -> { - assertThat(context).doesNotHaveBean("bar"); - assertThat(context).hasBean("example"); - assertThat(context.getBean("foo")).isEqualTo("foo"); - }); + .withUserConfiguration(FooConfiguration.class, OnAnnotationConfiguration.class, + FactoryBeanXmlConfiguration.class, PropertyPlaceholderAutoConfiguration.class) + .run((context) -> { + assertThat(context).doesNotHaveBean("bar"); + assertThat(context).hasBean("example"); + assertThat(context.getBean("foo")).isEqualTo("foo"); + }); } @Test void testOnMissingBeanConditionOutputShouldNotContainConditionalOnBeanClassInMessage() { this.contextRunner.withUserConfiguration(OnBeanNameConfiguration.class).run((context) -> { Collection conditionAndOutcomes = ConditionEvaluationReport - .get(context.getSourceApplicationContext().getBeanFactory()).getConditionAndOutcomesBySource() - .values(); + .get(context.getSourceApplicationContext().getBeanFactory()) + .getConditionAndOutcomesBySource() + .values(); String message = conditionAndOutcomes.iterator().next().iterator().next().getOutcome().getMessage(); assertThat(message).doesNotContain("@ConditionalOnBean"); }); @@ -152,192 +153,196 @@ class ConditionalOnMissingBeanTests { @Test void testOnMissingBeanConditionWithFactoryBean() { this.contextRunner - .withUserConfiguration(FactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, - PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); + .withUserConfiguration(FactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, + PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test void testOnMissingBeanConditionWithComponentScannedFactoryBean() { this.contextRunner - .withUserConfiguration(ComponentScannedFactoryBeanBeanMethodConfiguration.class, - ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context.getBean(ScanBean.class).toString()).isEqualTo("fromFactory")); + .withUserConfiguration(ComponentScannedFactoryBeanBeanMethodConfiguration.class, + ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ScanBean.class).toString()).isEqualTo("fromFactory")); } @Test void testOnMissingBeanConditionWithComponentScannedFactoryBeanWithBeanMethodArguments() { this.contextRunner - .withUserConfiguration(ComponentScannedFactoryBeanBeanMethodWithArgumentsConfiguration.class, - ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context.getBean(ScanBean.class).toString()).isEqualTo("fromFactory")); + .withUserConfiguration(ComponentScannedFactoryBeanBeanMethodWithArgumentsConfiguration.class, + ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ScanBean.class).toString()).isEqualTo("fromFactory")); } @Test void testOnMissingBeanConditionWithFactoryBeanWithBeanMethodArguments() { this.contextRunner - .withUserConfiguration(FactoryBeanWithBeanMethodArgumentsConfiguration.class, - ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) - .withPropertyValues("theValue=foo") - .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); + .withUserConfiguration(FactoryBeanWithBeanMethodArgumentsConfiguration.class, + ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) + .withPropertyValues("theValue=foo") + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test void testOnMissingBeanConditionWithConcreteFactoryBean() { this.contextRunner - .withUserConfiguration(ConcreteFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, - PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); + .withUserConfiguration(ConcreteFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, + PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test void testOnMissingBeanConditionWithUnhelpfulFactoryBean() { // We could not tell that the FactoryBean would ultimately create an ExampleBean this.contextRunner - .withUserConfiguration(UnhelpfulFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, - PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context).getBeans(ExampleBean.class).hasSize(2)); + .withUserConfiguration(UnhelpfulFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, + PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context).getBeans(ExampleBean.class).hasSize(2)); } @Test void testOnMissingBeanConditionWithRegisteredFactoryBean() { this.contextRunner - .withUserConfiguration(RegisteredFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, - PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); + .withUserConfiguration(RegisteredFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, + PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test void testOnMissingBeanConditionWithNonspecificFactoryBeanWithClassAttribute() { this.contextRunner - .withUserConfiguration(NonspecificFactoryBeanClassAttributeConfiguration.class, - ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); + .withUserConfiguration(NonspecificFactoryBeanClassAttributeConfiguration.class, + ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test void testOnMissingBeanConditionWithNonspecificFactoryBeanWithStringAttribute() { this.contextRunner - .withUserConfiguration(NonspecificFactoryBeanStringAttributeConfiguration.class, - ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); + .withUserConfiguration(NonspecificFactoryBeanStringAttributeConfiguration.class, + ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test void testOnMissingBeanConditionWithFactoryBeanInXml() { this.contextRunner - .withUserConfiguration(FactoryBeanXmlConfiguration.class, ConditionalOnFactoryBean.class, - PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); + .withUserConfiguration(FactoryBeanXmlConfiguration.class, ConditionalOnFactoryBean.class, + PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test void testOnMissingBeanConditionWithIgnoredSubclass() { - this.contextRunner.withUserConfiguration(CustomExampleBeanConfiguration.class, - ConditionalOnIgnoredSubclass.class, PropertyPlaceholderAutoConfiguration.class).run((context) -> { - assertThat(context).getBeans(ExampleBean.class).hasSize(2); - assertThat(context).getBeans(CustomExampleBean.class).hasSize(1); - }); + this.contextRunner + .withUserConfiguration(CustomExampleBeanConfiguration.class, ConditionalOnIgnoredSubclass.class, + PropertyPlaceholderAutoConfiguration.class) + .run((context) -> { + assertThat(context).getBeans(ExampleBean.class).hasSize(2); + assertThat(context).getBeans(CustomExampleBean.class).hasSize(1); + }); } @Test void testOnMissingBeanConditionWithIgnoredSubclassByName() { - this.contextRunner.withUserConfiguration(CustomExampleBeanConfiguration.class, - ConditionalOnIgnoredSubclassByName.class, PropertyPlaceholderAutoConfiguration.class).run((context) -> { - assertThat(context).getBeans(ExampleBean.class).hasSize(2); - assertThat(context).getBeans(CustomExampleBean.class).hasSize(1); - }); + this.contextRunner + .withUserConfiguration(CustomExampleBeanConfiguration.class, ConditionalOnIgnoredSubclassByName.class, + PropertyPlaceholderAutoConfiguration.class) + .run((context) -> { + assertThat(context).getBeans(ExampleBean.class).hasSize(2); + assertThat(context).getBeans(CustomExampleBean.class).hasSize(1); + }); } @Test void grandparentIsConsideredWhenUsingAncestorsStrategy() { this.contextRunner.withUserConfiguration(ExampleBeanConfiguration.class) - .run((grandparent) -> new ApplicationContextRunner().withParent(grandparent) - .run((parent) -> new ApplicationContextRunner().withParent(parent) - .withUserConfiguration(ExampleBeanConfiguration.class, - OnBeanInAncestorsConfiguration.class) - .run((context) -> assertThat(context).getBeans(ExampleBean.class).hasSize(1)))); + .run((grandparent) -> new ApplicationContextRunner().withParent(grandparent) + .run((parent) -> new ApplicationContextRunner().withParent(parent) + .withUserConfiguration(ExampleBeanConfiguration.class, OnBeanInAncestorsConfiguration.class) + .run((context) -> assertThat(context).getBeans(ExampleBean.class).hasSize(1)))); } @Test void currentContextIsIgnoredWhenUsingAncestorsStrategy() { this.contextRunner.run((parent) -> new ApplicationContextRunner().withParent(parent) - .withUserConfiguration(ExampleBeanConfiguration.class, OnBeanInAncestorsConfiguration.class) - .run((context) -> assertThat(context).getBeans(ExampleBean.class).hasSize(2))); + .withUserConfiguration(ExampleBeanConfiguration.class, OnBeanInAncestorsConfiguration.class) + .run((context) -> assertThat(context).getBeans(ExampleBean.class).hasSize(2))); } @Test void beanProducedByFactoryBeanIsConsideredWhenMatchingOnAnnotation() { - this.contextRunner.withUserConfiguration(ConcreteFactoryBeanConfiguration.class, - OnAnnotationWithFactoryBeanConfiguration.class).run((context) -> { - assertThat(context).doesNotHaveBean("bar"); - assertThat(context).hasSingleBean(ExampleBean.class); - }); + this.contextRunner + .withUserConfiguration(ConcreteFactoryBeanConfiguration.class, + OnAnnotationWithFactoryBeanConfiguration.class) + .run((context) -> { + assertThat(context).doesNotHaveBean("bar"); + assertThat(context).hasSingleBean(ExampleBean.class); + }); } @Test void parameterizedContainerWhenValueIsOfMissingBeanMatches() { this.contextRunner - .withUserConfiguration(ParameterizedWithoutCustomConfig.class, - ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("otherExampleBean", "conditionalCustomExampleBean"))); + .withUserConfiguration(ParameterizedWithoutCustomConfig.class, ParameterizedConditionWithValueConfig.class) + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("otherExampleBean", "conditionalCustomExampleBean"))); } @Test void parameterizedContainerWhenValueIsOfExistingBeanDoesNotMatch() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithValueConfig.class) + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } @Test void parameterizedContainerWhenValueIsOfMissingBeanRegistrationMatches() { this.contextRunner - .withUserConfiguration(ParameterizedWithoutCustomContainerConfig.class, - ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("otherExampleBean", "conditionalCustomExampleBean"))); + .withUserConfiguration(ParameterizedWithoutCustomContainerConfig.class, + ParameterizedConditionWithValueConfig.class) + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("otherExampleBean", "conditionalCustomExampleBean"))); } @Test void parameterizedContainerWhenValueIsOfExistingBeanRegistrationDoesNotMatch() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, - ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, + ParameterizedConditionWithValueConfig.class) + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } @Test void parameterizedContainerWhenReturnTypeIsOfExistingBeanDoesNotMatch() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomConfig.class, - ParameterizedConditionWithReturnTypeConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomConfig.class, + ParameterizedConditionWithReturnTypeConfig.class) + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } @Test void parameterizedContainerWhenReturnTypeIsOfExistingBeanRegistrationDoesNotMatch() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, - ParameterizedConditionWithReturnTypeConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, + ParameterizedConditionWithReturnTypeConfig.class) + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } @Test void parameterizedContainerWhenReturnRegistrationTypeIsOfExistingBeanDoesNotMatch() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomConfig.class, - ParameterizedConditionWithReturnRegistrationTypeConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomConfig.class, + ParameterizedConditionWithReturnRegistrationTypeConfig.class) + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } @Test void parameterizedContainerWhenReturnRegistrationTypeIsOfExistingBeanRegistrationDoesNotMatch() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, - ParameterizedConditionWithReturnRegistrationTypeConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, + ParameterizedConditionWithReturnRegistrationTypeConfig.class) + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } private Consumer exampleBeanRequirement(String... names) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanWithFilteredClasspathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanWithFilteredClasspathTests.java index 8477400909..b71644c56a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanWithFilteredClasspathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanWithFilteredClasspathTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ConditionalOnMissingBeanWithFilteredClasspathTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(OnBeanTypeConfiguration.class); + .withUserConfiguration(OnBeanTypeConfiguration.class); @Test void testNameOnMissingBeanTypeWithMissingImport() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java index c428c218ca..2c92ac5ee1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,20 +42,20 @@ class ConditionalOnNotWebApplicationTests { @Test void testNotWebApplicationWithServletContext() { new WebApplicationContextRunner().withUserConfiguration(NotWebApplicationConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(String.class)); + .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test void testNotWebApplicationWithReactiveContext() { new ReactiveWebApplicationContextRunner() - .withUserConfiguration(ReactiveApplicationConfig.class, NotWebApplicationConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(String.class)); + .withUserConfiguration(ReactiveApplicationConfig.class, NotWebApplicationConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test void testNotWebApplication() { new ApplicationContextRunner().withUserConfiguration(NotWebApplicationConfiguration.class) - .run((context) -> assertThat(context).getBeans(String.class).containsExactly(entry("none", "none"))); + .run((context) -> assertThat(context).getBeans(String.class).containsExactly(entry("none", "none"))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java index 4bd89c1b5a..24fbcf20ad 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -196,15 +196,14 @@ class ConditionalOnPropertyTests { @Test void nameOrValueMustBeSpecified() { assertThatIllegalStateException().isThrownBy(() -> load(NoNameOrValueAttribute.class, "some.property")) - .satisfies(causeMessageContaining( - "The name or value attribute of @ConditionalOnProperty must be specified")); + .satisfies( + causeMessageContaining("The name or value attribute of @ConditionalOnProperty must be specified")); } @Test void nameAndValueMustNotBeSpecified() { assertThatIllegalStateException().isThrownBy(() -> load(NameAndValueAttribute.class, "some.property")) - .satisfies(causeMessageContaining( - "The name and value attributes of @ConditionalOnProperty are exclusive")); + .satisfies(causeMessageContaining("The name and value attributes of @ConditionalOnProperty are exclusive")); } private Consumer causeMessageContaining(String message) { @@ -274,8 +273,9 @@ class ConditionalOnPropertyTests { private void load(Class config, String... environment) { TestPropertyValues.of(environment).applyTo(this.environment); - this.context = new SpringApplicationBuilder(config).environment(this.environment).web(WebApplicationType.NONE) - .run(); + this.context = new SpringApplicationBuilder(config).environment(this.environment) + .web(WebApplicationType.NONE) + .run(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java index 1cd9cb7f19..2f0f61bd90 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,89 +40,95 @@ class ConditionalOnSingleCandidateTests { @Test void singleCandidateNoCandidate() { this.contextRunner.withUserConfiguration(OnBeanSingleCandidateConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("consumer")); + .run((context) -> assertThat(context).doesNotHaveBean("consumer")); } @Test void singleCandidateOneCandidate() { this.contextRunner.withUserConfiguration(AlphaConfiguration.class, OnBeanSingleCandidateConfiguration.class) - .run((context) -> { - assertThat(context).hasBean("consumer"); - assertThat(context.getBean("consumer")).isEqualTo("alpha"); - }); + .run((context) -> { + assertThat(context).hasBean("consumer"); + assertThat(context.getBean("consumer")).isEqualTo("alpha"); + }); } @Test void singleCandidateOneScopedProxyCandidate() { this.contextRunner - .withUserConfiguration(AlphaScopedProxyConfiguration.class, OnBeanSingleCandidateConfiguration.class) - .run((context) -> { - assertThat(context).hasBean("consumer"); - assertThat(context.getBean("consumer").toString()).isEqualTo("alpha"); - }); + .withUserConfiguration(AlphaScopedProxyConfiguration.class, OnBeanSingleCandidateConfiguration.class) + .run((context) -> { + assertThat(context).hasBean("consumer"); + assertThat(context.getBean("consumer").toString()).isEqualTo("alpha"); + }); } @Test void singleCandidateInAncestorsOneCandidateInCurrent() { this.contextRunner.run((parent) -> this.contextRunner - .withUserConfiguration(AlphaConfiguration.class, OnBeanSingleCandidateInAncestorsConfiguration.class) - .withParent(parent).run((child) -> assertThat(child).doesNotHaveBean("consumer"))); + .withUserConfiguration(AlphaConfiguration.class, OnBeanSingleCandidateInAncestorsConfiguration.class) + .withParent(parent) + .run((child) -> assertThat(child).doesNotHaveBean("consumer"))); } @Test void singleCandidateInAncestorsOneCandidateInParent() { this.contextRunner.withUserConfiguration(AlphaConfiguration.class) - .run((parent) -> this.contextRunner - .withUserConfiguration(OnBeanSingleCandidateInAncestorsConfiguration.class).withParent(parent) - .run((child) -> { - assertThat(child).hasBean("consumer"); - assertThat(child.getBean("consumer")).isEqualTo("alpha"); - })); + .run((parent) -> this.contextRunner + .withUserConfiguration(OnBeanSingleCandidateInAncestorsConfiguration.class) + .withParent(parent) + .run((child) -> { + assertThat(child).hasBean("consumer"); + assertThat(child.getBean("consumer")).isEqualTo("alpha"); + })); } @Test void singleCandidateInAncestorsOneCandidateInGrandparent() { this.contextRunner.withUserConfiguration(AlphaConfiguration.class) - .run((grandparent) -> this.contextRunner.withParent(grandparent) - .run((parent) -> this.contextRunner - .withUserConfiguration(OnBeanSingleCandidateInAncestorsConfiguration.class) - .withParent(parent).run((child) -> { - assertThat(child).hasBean("consumer"); - assertThat(child.getBean("consumer")).isEqualTo("alpha"); - }))); + .run((grandparent) -> this.contextRunner.withParent(grandparent) + .run((parent) -> this.contextRunner + .withUserConfiguration(OnBeanSingleCandidateInAncestorsConfiguration.class) + .withParent(parent) + .run((child) -> { + assertThat(child).hasBean("consumer"); + assertThat(child.getBean("consumer")).isEqualTo("alpha"); + }))); } @Test void singleCandidateMultipleCandidates() { this.contextRunner - .withUserConfiguration(AlphaConfiguration.class, BravoConfiguration.class, - OnBeanSingleCandidateConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("consumer")); + .withUserConfiguration(AlphaConfiguration.class, BravoConfiguration.class, + OnBeanSingleCandidateConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean("consumer")); } @Test void singleCandidateMultipleCandidatesOnePrimary() { - this.contextRunner.withUserConfiguration(AlphaPrimaryConfiguration.class, BravoConfiguration.class, - OnBeanSingleCandidateConfiguration.class).run((context) -> { - assertThat(context).hasBean("consumer"); - assertThat(context.getBean("consumer")).isEqualTo("alpha"); - }); + this.contextRunner + .withUserConfiguration(AlphaPrimaryConfiguration.class, BravoConfiguration.class, + OnBeanSingleCandidateConfiguration.class) + .run((context) -> { + assertThat(context).hasBean("consumer"); + assertThat(context.getBean("consumer")).isEqualTo("alpha"); + }); } @Test void singleCandidateMultipleCandidatesMultiplePrimary() { this.contextRunner - .withUserConfiguration(AlphaPrimaryConfiguration.class, BravoPrimaryConfiguration.class, - OnBeanSingleCandidateConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("consumer")); + .withUserConfiguration(AlphaPrimaryConfiguration.class, BravoPrimaryConfiguration.class, + OnBeanSingleCandidateConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean("consumer")); } @Test void invalidAnnotationTwoTypes() { this.contextRunner.withUserConfiguration(OnBeanSingleCandidateTwoTypesConfiguration.class).run((context) -> { assertThat(context).hasFailed(); - assertThat(context).getFailure().hasCauseInstanceOf(IllegalArgumentException.class) - .hasMessageContaining(OnBeanSingleCandidateTwoTypesConfiguration.class.getName()); + assertThat(context).getFailure() + .hasCauseInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(OnBeanSingleCandidateTwoTypesConfiguration.class.getName()); }); } @@ -130,19 +136,21 @@ class ConditionalOnSingleCandidateTests { void invalidAnnotationNoType() { this.contextRunner.withUserConfiguration(OnBeanSingleCandidateNoTypeConfiguration.class).run((context) -> { assertThat(context).hasFailed(); - assertThat(context).getFailure().hasCauseInstanceOf(IllegalArgumentException.class) - .hasMessageContaining(OnBeanSingleCandidateNoTypeConfiguration.class.getName()); + assertThat(context).getFailure() + .hasCauseInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(OnBeanSingleCandidateNoTypeConfiguration.class.getName()); }); } @Test void singleCandidateMultipleCandidatesInContextHierarchy() { this.contextRunner.withUserConfiguration(AlphaPrimaryConfiguration.class, BravoConfiguration.class) - .run((parent) -> this.contextRunner.withUserConfiguration(OnBeanSingleCandidateConfiguration.class) - .withParent(parent).run((child) -> { - assertThat(child).hasBean("consumer"); - assertThat(child.getBean("consumer")).isEqualTo("alpha"); - })); + .run((parent) -> this.contextRunner.withUserConfiguration(OnBeanSingleCandidateConfiguration.class) + .withParent(parent) + .run((child) -> { + assertThat(child).hasBean("consumer"); + assertThat(child.getBean("consumer")).isEqualTo("alpha"); + })); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWarDeploymentTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWarDeploymentTests.java index 91eaea7734..c3507f9bcf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWarDeploymentTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWarDeploymentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,14 +38,14 @@ class ConditionalOnWarDeploymentTests { void nonWebApplicationShouldNotMatch() { ApplicationContextRunner contextRunner = new ApplicationContextRunner(); contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("forWar")); + .run((context) -> assertThat(context).doesNotHaveBean("forWar")); } @Test void reactiveWebApplicationShouldNotMatch() { ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner(); contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("forWar")); + .run((context) -> assertThat(context).doesNotHaveBean("forWar")); } @Test @@ -53,7 +53,7 @@ class ConditionalOnWarDeploymentTests { WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( AnnotationConfigServletWebApplicationContext::new); contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("forWar")); + .run((context) -> assertThat(context).doesNotHaveBean("forWar")); } @Test @@ -62,7 +62,7 @@ class ConditionalOnWarDeploymentTests { // SpringBootServletInitializer does for WAR deployments. WebApplicationContextRunner contextRunner = new WebApplicationContextRunner(); contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).hasBean("forWar")); + .run((context) -> assertThat(context).hasBean("forWar")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java index 608a2160cd..e023523508 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,14 +42,14 @@ class OnBeanConditionTypeDeductionFailureTests { @Test void conditionalOnMissingBeanWithDeducedTypeThatIsPartiallyMissingFromClassPath() { assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> new AnnotationConfigApplicationContext(ImportingConfiguration.class).close()) - .satisfies((ex) -> { - Throwable beanTypeDeductionException = findNestedCause(ex, BeanTypeDeductionException.class); - assertThat(beanTypeDeductionException).hasMessage("Failed to deduce bean type for " - + OnMissingBeanConfiguration.class.getName() + ".objectMapper"); - assertThat(findNestedCause(beanTypeDeductionException, NoClassDefFoundError.class)).isNotNull(); - - }); + .isThrownBy(() -> new AnnotationConfigApplicationContext(ImportingConfiguration.class).close()) + .satisfies((ex) -> { + Throwable beanTypeDeductionException = findNestedCause(ex, BeanTypeDeductionException.class); + assertThat(beanTypeDeductionException).hasMessage("Failed to deduce bean type for " + + OnMissingBeanConfiguration.class.getName() + ".objectMapper"); + assertThat(findNestedCause(beanTypeDeductionException, NoClassDefFoundError.class)).isNotNull(); + + }); } private Throwable findNestedCause(Throwable ex, Class target) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java index b195632c88..fc3113f2fd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ class OnClassConditionAutoConfigurationImportFilterTests { @Test void shouldBeRegistered() { assertThat(SpringFactoriesLoader.loadFactories(AutoConfigurationImportFilter.class, null)) - .hasAtLeastOneElementOfType(OnClassCondition.class); + .hasAtLeastOneElementOfType(OnClassCondition.class); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnPropertyListConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnPropertyListConditionTests.java index 9185e2137a..507ec4c3ff 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnPropertyListConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnPropertyListConditionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; class OnPropertyListConditionTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(TestConfig.class); + .withUserConfiguration(TestConfig.class); @Test void propertyNotDefined() { @@ -43,25 +43,25 @@ class OnPropertyListConditionTests { @Test void propertyDefinedAsCommaSeparated() { this.contextRunner.withPropertyValues("spring.test.my-list=value1") - .run((context) -> assertThat(context).hasBean("foo")); + .run((context) -> assertThat(context).hasBean("foo")); } @Test void propertyDefinedAsList() { this.contextRunner.withPropertyValues("spring.test.my-list[0]=value1") - .run((context) -> assertThat(context).hasBean("foo")); + .run((context) -> assertThat(context).hasBean("foo")); } @Test void propertyDefinedAsCommaSeparatedRelaxed() { this.contextRunner.withPropertyValues("spring.test.myList=value1") - .run((context) -> assertThat(context).hasBean("foo")); + .run((context) -> assertThat(context).hasBean("foo")); } @Test void propertyDefinedAsListRelaxed() { this.contextRunner.withPropertyValues("spring.test.myList[0]=value1") - .run((context) -> assertThat(context).hasBean("foo")); + .run((context) -> assertThat(context).hasBean("foo")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java index 7be194374f..845f6d0b34 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,13 +38,13 @@ class SpringBootConditionTests { @Test void sensibleClassException() { assertThatIllegalStateException().isThrownBy(() -> new AnnotationConfigApplicationContext(ErrorOnClass.class)) - .withMessageContaining("Error processing condition on " + ErrorOnClass.class.getName()); + .withMessageContaining("Error processing condition on " + ErrorOnClass.class.getName()); } @Test void sensibleMethodException() { assertThatIllegalStateException().isThrownBy(() -> new AnnotationConfigApplicationContext(ErrorOnMethod.class)) - .withMessageContaining("Error processing condition on " + ErrorOnMethod.class.getName() + ".myBean"); + .withMessageContaining("Error processing condition on " + ErrorOnMethod.class.getName() + ".myBean"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/LifecycleAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/LifecycleAutoConfigurationTests.java index c252a31fdd..ea6ee78b08 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/LifecycleAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/LifecycleAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; class LifecycleAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(LifecycleAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(LifecycleAutoConfiguration.class)); @Test void lifecycleProcessorIsConfiguredWithDefaultTimeout() { @@ -58,12 +58,13 @@ class LifecycleAutoConfigurationTests { @Test void lifecycleProcessorIsConfiguredWithCustomTimeoutInAChildContext() { new ApplicationContextRunner().run((parent) -> { - this.contextRunner.withParent(parent).withPropertyValues("spring.lifecycle.timeout-per-shutdown-phase=15s") - .run((child) -> { - assertThat(child).hasBean(AbstractApplicationContext.LIFECYCLE_PROCESSOR_BEAN_NAME); - Object processor = child.getBean(AbstractApplicationContext.LIFECYCLE_PROCESSOR_BEAN_NAME); - assertThat(processor).extracting("timeoutPerShutdownPhase").isEqualTo(15000L); - }); + this.contextRunner.withParent(parent) + .withPropertyValues("spring.lifecycle.timeout-per-shutdown-phase=15s") + .run((child) -> { + assertThat(child).hasBean(AbstractApplicationContext.LIFECYCLE_PROCESSOR_BEAN_NAME); + Object processor = child.getBean(AbstractApplicationContext.LIFECYCLE_PROCESSOR_BEAN_NAME); + assertThat(processor).extracting("timeoutPerShutdownPhase").isEqualTo(15000L); + }); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java index eea8ea84c4..313624d877 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,12 +44,12 @@ import static org.assertj.core.api.Assertions.assertThat; class MessageSourceAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MessageSourceAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MessageSourceAutoConfiguration.class)); @Test void testDefaultMessageSource() { this.contextRunner.run((context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("Foo message")); + .isEqualTo("Foo message")); } @Test @@ -71,22 +71,22 @@ class MessageSourceAutoConfigurationTests { @Test void testEncodingWorks() { this.contextRunner.withPropertyValues("spring.messages.basename:test/swedish") - .run((context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("Some text with some swedish öäå!")); + .run((context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)) + .isEqualTo("Some text with some swedish öäå!")); } @Test void testCacheDurationNoUnit() { this.contextRunner - .withPropertyValues("spring.messages.basename:test/messages", "spring.messages.cache-duration=10") - .run(assertCache(10 * 1000)); + .withPropertyValues("spring.messages.basename:test/messages", "spring.messages.cache-duration=10") + .run(assertCache(10 * 1000)); } @Test void testCacheDurationWithUnit() { this.contextRunner - .withPropertyValues("spring.messages.basename:test/messages", "spring.messages.cache-duration=1m") - .run(assertCache(60 * 1000)); + .withPropertyValues("spring.messages.basename:test/messages", "spring.messages.cache-duration=1m") + .run(assertCache(60 * 1000)); } private ContextConsumer assertCache(long expected) { @@ -99,86 +99,85 @@ class MessageSourceAutoConfigurationTests { @Test void testMultipleMessageSourceCreated() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages,test/messages2") - .run((context) -> { - assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); - assertThat(context.getMessage("foo-foo", null, "Foo-Foo message", Locale.UK)).isEqualTo("bar-bar"); - }); + .run((context) -> { + assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); + assertThat(context.getMessage("foo-foo", null, "Foo-Foo message", Locale.UK)).isEqualTo("bar-bar"); + }); } @Test @Disabled("Expected to fail per gh-1075") void testMessageSourceFromPropertySourceAnnotation() { - this.contextRunner.withUserConfiguration(Config.class).run( - (context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar")); + this.contextRunner.withUserConfiguration(Config.class) + .run((context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar")); } @Test void testFallbackDefault() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages") - .run((context) -> assertThat(context.getBean(MessageSource.class)) - .hasFieldOrPropertyWithValue("fallbackToSystemLocale", true)); + .run((context) -> assertThat(context.getBean(MessageSource.class)) + .hasFieldOrPropertyWithValue("fallbackToSystemLocale", true)); } @Test void testFallbackTurnOff() { this.contextRunner - .withPropertyValues("spring.messages.basename:test/messages", - "spring.messages.fallback-to-system-locale:false") - .run((context) -> assertThat(context.getBean(MessageSource.class)) - .hasFieldOrPropertyWithValue("fallbackToSystemLocale", false)); + .withPropertyValues("spring.messages.basename:test/messages", + "spring.messages.fallback-to-system-locale:false") + .run((context) -> assertThat(context.getBean(MessageSource.class)) + .hasFieldOrPropertyWithValue("fallbackToSystemLocale", false)); } @Test void testFormatMessageDefault() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages") - .run((context) -> assertThat(context.getBean(MessageSource.class)) - .hasFieldOrPropertyWithValue("alwaysUseMessageFormat", false)); + .run((context) -> assertThat(context.getBean(MessageSource.class)) + .hasFieldOrPropertyWithValue("alwaysUseMessageFormat", false)); } @Test void testFormatMessageOn() { this.contextRunner - .withPropertyValues("spring.messages.basename:test/messages", - "spring.messages.always-use-message-format:true") - .run((context) -> assertThat(context.getBean(MessageSource.class)) - .hasFieldOrPropertyWithValue("alwaysUseMessageFormat", true)); + .withPropertyValues("spring.messages.basename:test/messages", + "spring.messages.always-use-message-format:true") + .run((context) -> assertThat(context.getBean(MessageSource.class)) + .hasFieldOrPropertyWithValue("alwaysUseMessageFormat", true)); } @Test void testUseCodeAsDefaultMessageDefault() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages") - .run((context) -> assertThat(context.getBean(MessageSource.class)) - .hasFieldOrPropertyWithValue("useCodeAsDefaultMessage", false)); + .run((context) -> assertThat(context.getBean(MessageSource.class)) + .hasFieldOrPropertyWithValue("useCodeAsDefaultMessage", false)); } @Test void testUseCodeAsDefaultMessageOn() { this.contextRunner - .withPropertyValues("spring.messages.basename:test/messages", - "spring.messages.use-code-as-default-message:true") - .run((context) -> assertThat(context.getBean(MessageSource.class)) - .hasFieldOrPropertyWithValue("useCodeAsDefaultMessage", true)); + .withPropertyValues("spring.messages.basename:test/messages", + "spring.messages.use-code-as-default-message:true") + .run((context) -> assertThat(context.getBean(MessageSource.class)) + .hasFieldOrPropertyWithValue("useCodeAsDefaultMessage", true)); } @Test void existingMessageSourceIsPreferred() { this.contextRunner.withUserConfiguration(CustomMessageSourceConfiguration.class) - .run((context) -> assertThat(context.getMessage("foo", null, null, null)).isEqualTo("foo")); + .run((context) -> assertThat(context.getMessage("foo", null, null, null)).isEqualTo("foo")); } @Test void existingMessageSourceInParentIsIgnored() { this.contextRunner.run((parent) -> this.contextRunner.withParent(parent) - .withPropertyValues("spring.messages.basename:test/messages") - .run((context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("bar"))); + .withPropertyValues("spring.messages.basename:test/messages") + .run((context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"))); } @Test void messageSourceWithNonStandardBeanNameIsIgnored() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages") - .withUserConfiguration(CustomBeanNameMessageSourceConfiguration.class) - .run((context) -> assertThat(context.getMessage("foo", null, Locale.US)).isEqualTo("bar")); + .withUserConfiguration(CustomBeanNameMessageSourceConfiguration.class) + .run((context) -> assertThat(context.getMessage("foo", null, Locale.US)).isEqualTo("bar")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java index 139a14fd3e..a8a7122f48 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,51 +43,56 @@ class PropertyPlaceholderAutoConfigurationTests { @Test void whenTheAutoConfigurationIsNotUsedThenBeanDefinitionPlaceholdersAreNotResolved() { - this.contextRunner.withPropertyValues("fruit:banana").withInitializer(this::definePlaceholderBean) - .run((context) -> assertThat(context.getBean(PlaceholderBean.class).fruit).isEqualTo("${fruit:apple}")); + this.contextRunner.withPropertyValues("fruit:banana") + .withInitializer(this::definePlaceholderBean) + .run((context) -> assertThat(context.getBean(PlaceholderBean.class).fruit).isEqualTo("${fruit:apple}")); } @Test void whenTheAutoConfigurationIsUsedThenBeanDefinitionPlaceholdersAreResolved() { - this.contextRunner.withPropertyValues("fruit:banana").withInitializer(this::definePlaceholderBean) - .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class)) - .run((context) -> assertThat(context.getBean(PlaceholderBean.class).fruit).isEqualTo("banana")); + this.contextRunner.withPropertyValues("fruit:banana") + .withInitializer(this::definePlaceholderBean) + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class)) + .run((context) -> assertThat(context.getBean(PlaceholderBean.class).fruit).isEqualTo("banana")); } @Test void whenTheAutoConfigurationIsNotUsedThenValuePlaceholdersAreResolved() { - this.contextRunner.withPropertyValues("fruit:banana").withUserConfiguration(PlaceholderConfig.class) - .run((context) -> assertThat(context.getBean(PlaceholderConfig.class).fruit).isEqualTo("banana")); + this.contextRunner.withPropertyValues("fruit:banana") + .withUserConfiguration(PlaceholderConfig.class) + .run((context) -> assertThat(context.getBean(PlaceholderConfig.class).fruit).isEqualTo("banana")); } @Test void whenTheAutoConfigurationIsUsedThenValuePlaceholdersAreResolved() { this.contextRunner.withPropertyValues("fruit:banana") - .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class)) - .withUserConfiguration(PlaceholderConfig.class) - .run((context) -> assertThat(context.getBean(PlaceholderConfig.class).fruit).isEqualTo("banana")); + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class)) + .withUserConfiguration(PlaceholderConfig.class) + .run((context) -> assertThat(context.getBean(PlaceholderConfig.class).fruit).isEqualTo("banana")); } @Test void whenThereIsAUserDefinedPropertySourcesPlaceholderConfigurerThenItIsUsedForBeanDefinitionPlaceholderResolution() { - this.contextRunner.withPropertyValues("fruit:banana").withInitializer(this::definePlaceholderBean) - .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class)) - .withUserConfiguration(PlaceholdersOverride.class) - .run((context) -> assertThat(context.getBean(PlaceholderBean.class).fruit).isEqualTo("orange")); + this.contextRunner.withPropertyValues("fruit:banana") + .withInitializer(this::definePlaceholderBean) + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class)) + .withUserConfiguration(PlaceholdersOverride.class) + .run((context) -> assertThat(context.getBean(PlaceholderBean.class).fruit).isEqualTo("orange")); } @Test void whenThereIsAUserDefinedPropertySourcesPlaceholderConfigurerThenItIsUsedForValuePlaceholderResolution() { this.contextRunner.withPropertyValues("fruit:banana") - .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class)) - .withUserConfiguration(PlaceholderConfig.class, PlaceholdersOverride.class) - .run((context) -> assertThat(context.getBean(PlaceholderConfig.class).fruit).isEqualTo("orange")); + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class)) + .withUserConfiguration(PlaceholderConfig.class, PlaceholdersOverride.class) + .run((context) -> assertThat(context.getBean(PlaceholderConfig.class).fruit).isEqualTo("orange")); } private void definePlaceholderBean(ConfigurableApplicationContext context) { ((BeanDefinitionRegistry) context.getBeanFactory()).registerBeanDefinition("placeholderBean", - BeanDefinitionBuilder.rootBeanDefinition(PlaceholderBean.class).addConstructorArgValue("${fruit:apple}") - .getBeanDefinition()); + BeanDefinitionBuilder.rootBeanDefinition(PlaceholderBean.class) + .addConstructorArgValue("${fruit:apple}") + .getBeanDefinition()); } @Configuration(proxyBeanMethods = false) @@ -115,7 +120,7 @@ class PropertyPlaceholderAutoConfigurationTests { static PropertySourcesPlaceholderConfigurer morePlaceholders() { PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); configurer - .setProperties(StringUtils.splitArrayElementsIntoProperties(new String[] { "fruit=orange" }, "=")); + .setProperties(StringUtils.splitArrayElementsIntoProperties(new String[] { "fruit=orange" }, "=")); configurer.setLocalOverride(true); configurer.setOrder(0); return configurer; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java index 9fc637c2d4..82ef9350db 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,14 +51,16 @@ class CouchbaseAutoConfigurationIntegrationTests { @Container static final CouchbaseContainer couchbase = new CouchbaseContainer(DockerImageNames.couchbase()) - .withCredentials("spring", "password").withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)) - .withBucket(new BucketDefinition(BUCKET_NAME).withPrimaryIndex(false)); + .withCredentials("spring", "password") + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)) + .withBucket(new BucketDefinition(BUCKET_NAME).withPrimaryIndex(false)); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CouchbaseAutoConfiguration.class)) - .withPropertyValues("spring.couchbase.connection-string: " + couchbase.getConnectionString(), - "spring.couchbase.username:spring", "spring.couchbase.password:password", - "spring.couchbase.bucket.name:" + BUCKET_NAME); + .withConfiguration(AutoConfigurations.of(CouchbaseAutoConfiguration.class)) + .withPropertyValues("spring.couchbase.connection-string: " + couchbase.getConnectionString(), + "spring.couchbase.username:spring", "spring.couchbase.password:password", + "spring.couchbase.bucket.name:" + BUCKET_NAME); @Test void defaultConfiguration() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java index 5a420e604c..2edf5a8341 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,52 +52,57 @@ import static org.mockito.Mockito.mock; class CouchbaseAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CouchbaseAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(CouchbaseAutoConfiguration.class)); @Test void connectionStringIsRequired() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ClusterEnvironment.class) - .doesNotHaveBean(Cluster.class)); + .doesNotHaveBean(Cluster.class)); } @Test void connectionStringCreateEnvironmentAndCluster() { this.contextRunner.withUserConfiguration(CouchbaseTestConfiguration.class) - .withPropertyValues("spring.couchbase.connection-string=localhost").run((context) -> { - assertThat(context).hasSingleBean(ClusterEnvironment.class).hasSingleBean(Cluster.class); - assertThat(context.getBean(Cluster.class)) - .isSameAs(context.getBean(CouchbaseTestConfiguration.class).couchbaseCluster()); - }); + .withPropertyValues("spring.couchbase.connection-string=localhost") + .run((context) -> { + assertThat(context).hasSingleBean(ClusterEnvironment.class).hasSingleBean(Cluster.class); + assertThat(context.getBean(Cluster.class)) + .isSameAs(context.getBean(CouchbaseTestConfiguration.class).couchbaseCluster()); + }); } @Test void whenObjectMapperBeanIsDefinedThenClusterEnvironmentObjectMapperIsDerivedFromIt() { this.contextRunner.withUserConfiguration(CouchbaseTestConfiguration.class) - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) - .withPropertyValues("spring.couchbase.connection-string=localhost").run((context) -> { - ClusterEnvironment env = context.getBean(ClusterEnvironment.class); - Set expectedModuleIds = new HashSet<>( - context.getBean(ObjectMapper.class).getRegisteredModuleIds()); - expectedModuleIds.add(new JsonValueModule().getTypeId()); - JsonSerializer serializer = env.jsonSerializer(); - assertThat(serializer).extracting("wrapped").isInstanceOf(JacksonJsonSerializer.class) - .extracting("mapper", as(InstanceOfAssertFactories.type(ObjectMapper.class))) - .extracting(ObjectMapper::getRegisteredModuleIds).isEqualTo(expectedModuleIds); - }); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) + .withPropertyValues("spring.couchbase.connection-string=localhost") + .run((context) -> { + ClusterEnvironment env = context.getBean(ClusterEnvironment.class); + Set expectedModuleIds = new HashSet<>( + context.getBean(ObjectMapper.class).getRegisteredModuleIds()); + expectedModuleIds.add(new JsonValueModule().getTypeId()); + JsonSerializer serializer = env.jsonSerializer(); + assertThat(serializer).extracting("wrapped") + .isInstanceOf(JacksonJsonSerializer.class) + .extracting("mapper", as(InstanceOfAssertFactories.type(ObjectMapper.class))) + .extracting(ObjectMapper::getRegisteredModuleIds) + .isEqualTo(expectedModuleIds); + }); } @Test void customizeJsonSerializer() { JsonSerializer customJsonSerializer = mock(JsonSerializer.class); this.contextRunner.withUserConfiguration(CouchbaseTestConfiguration.class) - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) - .withBean(ClusterEnvironmentBuilderCustomizer.class, - () -> (builder) -> builder.jsonSerializer(customJsonSerializer)) - .withPropertyValues("spring.couchbase.connection-string=localhost").run((context) -> { - ClusterEnvironment env = context.getBean(ClusterEnvironment.class); - JsonSerializer serializer = env.jsonSerializer(); - assertThat(serializer).extracting("wrapped").isSameAs(customJsonSerializer); - }); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) + .withBean(ClusterEnvironmentBuilderCustomizer.class, + () -> (builder) -> builder.jsonSerializer(customJsonSerializer)) + .withPropertyValues("spring.couchbase.connection-string=localhost") + .run((context) -> { + ClusterEnvironment env = context.getBean(ClusterEnvironment.class); + JsonSerializer serializer = env.jsonSerializer(); + assertThat(serializer).extracting("wrapped").isSameAs(customJsonSerializer); + }); } @Test @@ -152,23 +157,23 @@ class CouchbaseAutoConfigurationTests { private void testClusterEnvironment(Consumer environmentConsumer, String... environment) { this.contextRunner.withUserConfiguration(CouchbaseTestConfiguration.class) - .withPropertyValues("spring.couchbase.connection-string=localhost").withPropertyValues(environment) - .run((context) -> environmentConsumer.accept(context.getBean(ClusterEnvironment.class))); + .withPropertyValues("spring.couchbase.connection-string=localhost") + .withPropertyValues(environment) + .run((context) -> environmentConsumer.accept(context.getBean(ClusterEnvironment.class))); } @Test void customizeEnvWithCustomCouchbaseConfiguration() { this.contextRunner - .withUserConfiguration(CouchbaseTestConfiguration.class, - ClusterEnvironmentCustomizerConfiguration.class) - .withPropertyValues("spring.couchbase.connection-string=localhost", - "spring.couchbase.env.timeouts.connect=100") - .run((context) -> { - assertThat(context).hasSingleBean(ClusterEnvironment.class); - ClusterEnvironment env = context.getBean(ClusterEnvironment.class); - assertThat(env.timeoutConfig().kvTimeout()).isEqualTo(Duration.ofSeconds(5)); - assertThat(env.timeoutConfig().connectTimeout()).isEqualTo(Duration.ofSeconds(2)); - }); + .withUserConfiguration(CouchbaseTestConfiguration.class, ClusterEnvironmentCustomizerConfiguration.class) + .withPropertyValues("spring.couchbase.connection-string=localhost", + "spring.couchbase.env.timeouts.connect=100") + .run((context) -> { + assertThat(context).hasSingleBean(ClusterEnvironment.class); + ClusterEnvironment env = context.getBean(ClusterEnvironment.class); + assertThat(env.timeoutConfig().kvTimeout()).isEqualTo(Duration.ofSeconds(5)); + assertThat(env.timeoutConfig().connectTimeout()).isEqualTo(Duration.ofSeconds(2)); + }); } @Configuration(proxyBeanMethods = false) @@ -176,8 +181,9 @@ class CouchbaseAutoConfigurationTests { @Bean ClusterEnvironmentBuilderCustomizer clusterEnvironmentBuilderCustomizer() { - return (builder) -> builder.timeoutConfig().kvTimeout(Duration.ofSeconds(5)) - .connectTimeout(Duration.ofSeconds(2)); + return (builder) -> builder.timeoutConfig() + .kvTimeout(Duration.ofSeconds(5)) + .connectTimeout(Duration.ofSeconds(2)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java index c3ef53ba17..c87fdd863c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,7 +59,7 @@ class PersistenceExceptionTranslationAutoConfigurationTests { void exceptionTranslationPostProcessorUsesCglibByDefault() { this.context = new AnnotationConfigApplicationContext(PersistenceExceptionTranslationAutoConfiguration.class); Map beans = this.context - .getBeansOfType(PersistenceExceptionTranslationPostProcessor.class); + .getBeansOfType(PersistenceExceptionTranslationPostProcessor.class); assertThat(beans).hasSize(1); assertThat(beans.values().iterator().next().isProxyTargetClass()).isTrue(); } @@ -71,7 +71,7 @@ class PersistenceExceptionTranslationAutoConfigurationTests { this.context.register(PersistenceExceptionTranslationAutoConfiguration.class); this.context.refresh(); Map beans = this.context - .getBeansOfType(PersistenceExceptionTranslationPostProcessor.class); + .getBeansOfType(PersistenceExceptionTranslationPostProcessor.class); assertThat(beans).hasSize(1); assertThat(beans.values().iterator().next().isProxyTargetClass()).isFalse(); } @@ -83,7 +83,7 @@ class PersistenceExceptionTranslationAutoConfigurationTests { this.context.register(PersistenceExceptionTranslationAutoConfiguration.class); this.context.refresh(); Map beans = this.context - .getBeansOfType(PersistenceExceptionTranslationPostProcessor.class); + .getBeansOfType(PersistenceExceptionTranslationPostProcessor.class); assertThat(beans).isEmpty(); } @@ -100,7 +100,7 @@ class PersistenceExceptionTranslationAutoConfigurationTests { HibernateJpaAutoConfiguration.class, TestConfiguration.class, PersistenceExceptionTranslationAutoConfiguration.class); assertThatExceptionOfType(InvalidDataAccessApiUsageException.class) - .isThrownBy(() -> this.context.getBean(TestRepository.class).doSomething()); + .isThrownBy(() -> this.context.getBean(TestRepository.class).doSomething()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ConditionalOnRepositoryTypeTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ConditionalOnRepositoryTypeTests.java index 5f6c4b5c65..3de73b9cd9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ConditionalOnRepositoryTypeTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ConditionalOnRepositoryTypeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,76 +35,76 @@ class ConditionalOnRepositoryTypeTests { @Test void imperativeRepositoryMatchesWithNoConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) - .run((context) -> assertThat(context).hasSingleBean(ImperativeRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(ImperativeRepository.class)); } @Test void reactiveRepositoryMatchesWithNoConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) - .run((context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); } @Test void imperativeRepositoryMatchesWithAutoConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) - .withPropertyValues("spring.data.test.repositories.type:auto") - .run((context) -> assertThat(context).hasSingleBean(ImperativeRepository.class)); + .withPropertyValues("spring.data.test.repositories.type:auto") + .run((context) -> assertThat(context).hasSingleBean(ImperativeRepository.class)); } @Test void reactiveRepositoryMatchesWithAutoConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) - .withPropertyValues("spring.data.test.repositories.type:auto") - .run((context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); + .withPropertyValues("spring.data.test.repositories.type:auto") + .run((context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); } @Test void imperativeRepositoryMatchesWithImperativeConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) - .withPropertyValues("spring.data.test.repositories.type:imperative") - .run((context) -> assertThat(context).hasSingleBean(ImperativeRepository.class)); + .withPropertyValues("spring.data.test.repositories.type:imperative") + .run((context) -> assertThat(context).hasSingleBean(ImperativeRepository.class)); } @Test void reactiveRepositoryMatchesWithReactiveConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) - .withPropertyValues("spring.data.test.repositories.type:reactive") - .run((context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); + .withPropertyValues("spring.data.test.repositories.type:reactive") + .run((context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); } @Test void imperativeRepositoryDoesNotMatchWithReactiveConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) - .withPropertyValues("spring.data.test.repositories.type:reactive") - .run((context) -> assertThat(context).doesNotHaveBean(ImperativeRepository.class)); + .withPropertyValues("spring.data.test.repositories.type:reactive") + .run((context) -> assertThat(context).doesNotHaveBean(ImperativeRepository.class)); } @Test void reactiveRepositoryDoesNotMatchWithImperativeConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) - .withPropertyValues("spring.data.test.repositories.type:imperative") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveRepository.class)); + .withPropertyValues("spring.data.test.repositories.type:imperative") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveRepository.class)); } @Test void imperativeRepositoryDoesNotMatchWithNoneConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) - .withPropertyValues("spring.data.test.repositories.type:none") - .run((context) -> assertThat(context).doesNotHaveBean(ImperativeRepository.class)); + .withPropertyValues("spring.data.test.repositories.type:none") + .run((context) -> assertThat(context).doesNotHaveBean(ImperativeRepository.class)); } @Test void reactiveRepositoryDoesNotMatchWithNoneConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) - .withPropertyValues("spring.data.test.repositories.type:none") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveRepository.class)); + .withPropertyValues("spring.data.test.repositories.type:none") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveRepository.class)); } @Test void failsFastWhenConfiguredTypeIsUnknown() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) - .withPropertyValues("spring.data.test.repositories.type:abcde") - .run((context) -> assertThat(context).hasFailed()); + .withPropertyValues("spring.data.test.repositories.type:abcde") + .run((context) -> assertThat(context).hasFailed()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java index 80392014d1..3353ea89fa 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,30 +49,28 @@ class CassandraDataAutoConfigurationIntegrationTests { static final CassandraContainer cassandra = new CassandraContainer(); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class)) - .withPropertyValues( - "spring.data.cassandra.contact-points:" + cassandra.getHost() + ":" - + cassandra.getFirstMappedPort(), - "spring.data.cassandra.local-datacenter=datacenter1", - "spring.data.cassandra.connection.connect-timeout=60s", - "spring.data.cassandra.connection.init-query-timeout=60s", - "spring.data.cassandra.request.timeout=60s") - .withInitializer((context) -> AutoConfigurationPackages.register((BeanDefinitionRegistry) context, - City.class.getPackage().getName())); + .withConfiguration( + AutoConfigurations.of(CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class)) + .withPropertyValues( + "spring.data.cassandra.contact-points:" + cassandra.getHost() + ":" + cassandra.getFirstMappedPort(), + "spring.data.cassandra.local-datacenter=datacenter1", + "spring.data.cassandra.connection.connect-timeout=60s", + "spring.data.cassandra.connection.init-query-timeout=60s", "spring.data.cassandra.request.timeout=60s") + .withInitializer((context) -> AutoConfigurationPackages.register((BeanDefinitionRegistry) context, + City.class.getPackage().getName())); @Test void hasDefaultSchemaActionSet() { this.contextRunner.run((context) -> assertThat(context.getBean(SessionFactoryFactoryBean.class)) - .hasFieldOrPropertyWithValue("schemaAction", SchemaAction.NONE)); + .hasFieldOrPropertyWithValue("schemaAction", SchemaAction.NONE)); } @Test void hasRecreateSchemaActionSet() { this.contextRunner.withUserConfiguration(KeyspaceTestConfiguration.class) - .withPropertyValues("spring.data.cassandra.schemaAction=recreate_drop_unused") - .run((context) -> assertThat(context.getBean(SessionFactoryFactoryBean.class)) - .hasFieldOrPropertyWithValue("schemaAction", SchemaAction.RECREATE_DROP_UNUSED)); + .withPropertyValues("spring.data.cassandra.schemaAction=recreate_drop_unused") + .run((context) -> assertThat(context.getBean(SessionFactoryFactoryBean.class)) + .hasFieldOrPropertyWithValue("schemaAction", SchemaAction.RECREATE_DROP_UNUSED)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java index c9d6ef7434..3fd96a6ead 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,7 +87,7 @@ class CassandraDataAutoConfigurationTests { load(); CassandraConverter cassandraConverter = this.context.getBean(CassandraConverter.class); assertThat(cassandraConverter.getCodecRegistry()) - .isSameAs(this.context.getBean(CassandraMockConfiguration.class).codecRegistry); + .isSameAs(this.context.getBean(CassandraMockConfiguration.class).codecRegistry); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigurationTests.java index 3f2b3b23f4..275ebaf9f9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -82,15 +82,15 @@ class CassandraReactiveRepositoriesAutoConfigurationTests { @Test void enablingImperativeRepositoriesDisablesReactiveRepositories() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .withPropertyValues("spring.data.cassandra.repositories.type=imperative") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); + .withPropertyValues("spring.data.cassandra.repositories.type=imperative") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Test void enablingNoRepositoriesDisablesReactiveRepositories() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .withPropertyValues("spring.data.cassandra.repositories.type=none") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); + .withPropertyValues("spring.data.cassandra.repositories.type=none") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @SuppressWarnings("unchecked") diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java index 017d1c1018..0fd76f63b1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -80,15 +80,15 @@ class CassandraRepositoriesAutoConfigurationTests { @Test void enablingReactiveRepositoriesDisablesImperativeRepositories() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .withPropertyValues("spring.data.cassandra.repositories.type=reactive") - .run((context) -> assertThat(context).doesNotHaveBean(CityCassandraRepository.class)); + .withPropertyValues("spring.data.cassandra.repositories.type=reactive") + .run((context) -> assertThat(context).doesNotHaveBean(CityCassandraRepository.class)); } @Test void enablingNoRepositoriesDisablesImperativeRepositories() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .withPropertyValues("spring.data.cassandra.repositories.type=none") - .run((context) -> assertThat(context).doesNotHaveBean(CityCassandraRepository.class)); + .withPropertyValues("spring.data.cassandra.repositories.type=none") + .run((context) -> assertThat(context).doesNotHaveBean(CityCassandraRepository.class)); } @SuppressWarnings("unchecked") diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java index 6cb4e0698f..7ee576be8b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,8 @@ import static org.assertj.core.api.Assertions.assertThat; class CouchbaseDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class, - CouchbaseAutoConfiguration.class, CouchbaseDataAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class, CouchbaseAutoConfiguration.class, + CouchbaseDataAutoConfiguration.class)); @Test void disabledIfCouchbaseIsNotConfigured() { @@ -78,16 +78,16 @@ class CouchbaseDataAutoConfigurationTests { @Test void typeKeyDefault() { this.contextRunner.withUserConfiguration(CouchbaseMockConfiguration.class) - .run((context) -> assertThat(context.getBean(MappingCouchbaseConverter.class).getTypeKey()) - .isEqualTo(DefaultCouchbaseTypeMapper.DEFAULT_TYPE_KEY)); + .run((context) -> assertThat(context.getBean(MappingCouchbaseConverter.class).getTypeKey()) + .isEqualTo(DefaultCouchbaseTypeMapper.DEFAULT_TYPE_KEY)); } @Test void typeKeyCanBeCustomized() { this.contextRunner.withUserConfiguration(CouchbaseMockConfiguration.class) - .withPropertyValues("spring.data.couchbase.type-key=_custom") - .run((context) -> assertThat(context.getBean(MappingCouchbaseConverter.class).getTypeKey()) - .isEqualTo("_custom")); + .withPropertyValues("spring.data.couchbase.type-key=_custom") + .run((context) -> assertThat(context.getBean(MappingCouchbaseConverter.class).getTypeKey()) + .isEqualTo("_custom")); } @Test @@ -96,7 +96,7 @@ class CouchbaseDataAutoConfigurationTests { CouchbaseTemplate template = context.getBean(CouchbaseTemplate.class); assertThat( template.getConverter().getConversionService().canConvert(CouchbaseProperties.class, Boolean.class)) - .isTrue(); + .isTrue(); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests.java index 2fbbac6c22..23fa8b4c2e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,9 +47,9 @@ class CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests { @Test void shouldCreateInstancesForReactiveAndImperativeRepositories() { new ApplicationContextRunner() - .withUserConfiguration(ImperativeAndReactiveConfiguration.class, BaseConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(CityRepository.class) - .hasSingleBean(ReactiveCityRepository.class)); + .withUserConfiguration(ImperativeAndReactiveConfiguration.class, BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(CityRepository.class) + .hasSingleBean(ReactiveCityRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveDataAutoConfigurationTests.java index a949f14aa1..080d7b0cc9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,9 +49,9 @@ import static org.assertj.core.api.Assertions.assertThat; */ class CouchbaseReactiveDataAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( - AutoConfigurations.of(ValidationAutoConfiguration.class, CouchbaseAutoConfiguration.class, - CouchbaseDataAutoConfiguration.class, CouchbaseReactiveDataAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class, CouchbaseAutoConfiguration.class, + CouchbaseDataAutoConfiguration.class, CouchbaseReactiveDataAutoConfiguration.class)); @Test void disabledIfCouchbaseIsNotConfigured() { @@ -80,7 +80,7 @@ class CouchbaseReactiveDataAutoConfigurationTests { ReactiveCouchbaseTemplate template = context.getBean(ReactiveCouchbaseTemplate.class); assertThat( template.getConverter().getConversionService().canConvert(CouchbaseProperties.class, Boolean.class)) - .isTrue(); + .isTrue(); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesAutoConfigurationTests.java index 060ea7f0d9..b5a13de1bb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,10 +41,10 @@ import static org.assertj.core.api.Assertions.assertThat; */ class CouchbaseReactiveRepositoriesAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( - AutoConfigurations.of(CouchbaseAutoConfiguration.class, CouchbaseDataAutoConfiguration.class, - CouchbaseRepositoriesAutoConfiguration.class, CouchbaseReactiveDataAutoConfiguration.class, - CouchbaseReactiveRepositoriesAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(CouchbaseAutoConfiguration.class, CouchbaseDataAutoConfiguration.class, + CouchbaseRepositoriesAutoConfiguration.class, CouchbaseReactiveDataAutoConfiguration.class, + CouchbaseReactiveRepositoriesAutoConfiguration.class)); @Test void couchbaseNotAvailable() { @@ -54,33 +54,33 @@ class CouchbaseReactiveRepositoriesAutoConfigurationTests { @Test void defaultRepository() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ReactiveCityRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveCityRepository.class)); } @Test void imperativeRepositories() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .withPropertyValues("spring.data.couchbase.repositories.type=imperative") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); + .withPropertyValues("spring.data.couchbase.repositories.type=imperative") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Test void disabledRepositories() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .withPropertyValues("spring.data.couchbase.repositories.type=none") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); + .withPropertyValues("spring.data.couchbase.repositories.type=none") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Test void noRepositoryAvailable() { this.contextRunner.withUserConfiguration(NoRepositoryConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Test void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(CustomizedConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityCouchbaseRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityCouchbaseRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java index ac628cc4fa..a5ec5c152d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,8 @@ import static org.assertj.core.api.Assertions.assertThat; class CouchbaseRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CouchbaseAutoConfiguration.class, - CouchbaseDataAutoConfiguration.class, CouchbaseRepositoriesAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(CouchbaseAutoConfiguration.class, CouchbaseDataAutoConfiguration.class, + CouchbaseRepositoriesAutoConfiguration.class)); @Test void couchbaseNotAvailable() { @@ -50,27 +50,27 @@ class CouchbaseRepositoriesAutoConfigurationTests { @Test void defaultRepository() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(CityRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(CityRepository.class)); } @Test void reactiveRepositories() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .withPropertyValues("spring.data.couchbase.repositories.type=reactive") - .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); + .withPropertyValues("spring.data.couchbase.repositories.type=reactive") + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Test void disabledRepositories() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .withPropertyValues("spring.data.couchbase.repositories.type=none") - .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); + .withPropertyValues("spring.data.couchbase.repositories.type=none") + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Test void noRepositoryAvailable() { this.contextRunner.withUserConfiguration(NoRepositoryConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java index cea52a6064..1e120a24d9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,8 +55,8 @@ import static org.mockito.Mockito.mock; class ElasticsearchDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class, - ReactiveElasticsearchRestClientAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class, + ReactiveElasticsearchRestClientAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class)); @BeforeEach void setUp() { @@ -71,8 +71,10 @@ class ElasticsearchDataAutoConfigurationTests { @Test void defaultRestBeansRegistered() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ElasticsearchRestTemplate.class) - .hasSingleBean(ReactiveElasticsearchTemplate.class).hasSingleBean(ElasticsearchConverter.class) - .hasSingleBean(ElasticsearchConverter.class).hasSingleBean(ElasticsearchCustomConversions.class)); + .hasSingleBean(ReactiveElasticsearchTemplate.class) + .hasSingleBean(ElasticsearchConverter.class) + .hasSingleBean(ElasticsearchConverter.class) + .hasSingleBean(ElasticsearchCustomConversions.class)); } @Test @@ -80,8 +82,8 @@ class ElasticsearchDataAutoConfigurationTests { this.contextRunner.run((context) -> { SimpleElasticsearchMappingContext mappingContext = context.getBean(SimpleElasticsearchMappingContext.class); assertThat(mappingContext) - .extracting("simpleTypeHolder", InstanceOfAssertFactories.type(SimpleTypeHolder.class)).satisfies( - (simpleTypeHolder) -> assertThat(simpleTypeHolder.isSimpleType(BigDecimal.class)).isTrue()); + .extracting("simpleTypeHolder", InstanceOfAssertFactories.type(SimpleTypeHolder.class)) + .satisfies((simpleTypeHolder) -> assertThat(simpleTypeHolder.isSimpleType(BigDecimal.class)).isTrue()); }); } @@ -89,22 +91,26 @@ class ElasticsearchDataAutoConfigurationTests { void customConversionsShouldBeUsed() { this.contextRunner.withUserConfiguration(CustomElasticsearchCustomConversions.class).run((context) -> { assertThat(context).hasSingleBean(ElasticsearchCustomConversions.class).hasBean("testCustomConversions"); - assertThat(context.getBean(ElasticsearchConverter.class).getConversionService() - .canConvert(ElasticsearchRestTemplate.class, Boolean.class)).isTrue(); + assertThat(context.getBean(ElasticsearchConverter.class) + .getConversionService() + .canConvert(ElasticsearchRestTemplate.class, Boolean.class)).isTrue(); }); } @Test void customRestTemplateShouldBeUsed() { - this.contextRunner.withUserConfiguration(CustomRestTemplate.class).run((context) -> assertThat(context) - .getBeanNames(ElasticsearchRestTemplate.class).hasSize(1).contains("elasticsearchTemplate")); + this.contextRunner.withUserConfiguration(CustomRestTemplate.class) + .run((context) -> assertThat(context).getBeanNames(ElasticsearchRestTemplate.class) + .hasSize(1) + .contains("elasticsearchTemplate")); } @Test void customReactiveRestTemplateShouldBeUsed() { this.contextRunner.withUserConfiguration(CustomReactiveRestTemplate.class) - .run((context) -> assertThat(context).getBeanNames(ReactiveElasticsearchTemplate.class).hasSize(1) - .contains("reactiveElasticsearchTemplate")); + .run((context) -> assertThat(context).getBeanNames(ReactiveElasticsearchTemplate.class) + .hasSize(1) + .contains("reactiveElasticsearchTemplate")); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java index 21a4af23f5..ba6922202c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,29 +50,31 @@ class ElasticsearchRepositoriesAutoConfigurationTests { @Container static final ElasticsearchContainer elasticsearch = new ElasticsearchContainer(DockerImageNames.elasticsearch()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class, - ElasticsearchRepositoriesAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class)) - .withPropertyValues("spring.elasticsearch.uris=" + elasticsearch.getHttpHostAddress()); + .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class, + ElasticsearchRepositoriesAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class)) + .withPropertyValues("spring.elasticsearch.uris=" + elasticsearch.getHttpHostAddress()); @Test void testDefaultRepositoryConfiguration() { - this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(CityRepository.class).hasSingleBean(ElasticsearchRestTemplate.class)); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(CityRepository.class) + .hasSingleBean(ElasticsearchRestTemplate.class)); } @Test void testNoRepositoryConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ElasticsearchRestTemplate.class)); + .run((context) -> assertThat(context).hasSingleBean(ElasticsearchRestTemplate.class)); } @Test void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(CustomizedConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(CityElasticsearchDbRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(CityElasticsearchDbRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfigurationTests.java index 06b7379dda..d85166aeb1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,31 +49,33 @@ class ReactiveElasticsearchRepositoriesAutoConfigurationTests { @Container static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(DockerImageNames.elasticsearch()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveElasticsearchRestClientAutoConfiguration.class, - ReactiveElasticsearchRepositoriesAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class)) - .withPropertyValues( - "spring.elasticsearch.uris=" + elasticsearch.getHost() + ":" + elasticsearch.getFirstMappedPort(), - "spring.elasticsearch.socket-timeout=30s"); + .withConfiguration(AutoConfigurations.of(ReactiveElasticsearchRestClientAutoConfiguration.class, + ReactiveElasticsearchRepositoriesAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class)) + .withPropertyValues( + "spring.elasticsearch.uris=" + elasticsearch.getHost() + ":" + elasticsearch.getFirstMappedPort(), + "spring.elasticsearch.socket-timeout=30s"); @Test void testDefaultRepositoryConfiguration() { - this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(ReactiveCityRepository.class).hasSingleBean(ReactiveElasticsearchTemplate.class)); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(ReactiveCityRepository.class) + .hasSingleBean(ReactiveElasticsearchTemplate.class)); } @Test void testNoRepositoryConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ReactiveElasticsearchTemplate.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveElasticsearchTemplate.class)); } @Test void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(CustomizedConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(CityReactiveElasticsearchDbRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(CityReactiveElasticsearchDbRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRestClientAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRestClientAutoConfigurationIntegrationTests.java index eed064d708..c78e1eb487 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRestClientAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRestClientAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,27 +45,28 @@ class ReactiveElasticsearchRestClientAutoConfigurationIntegrationTests { @Container static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(DockerImageNames.elasticsearch()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveElasticsearchRestClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveElasticsearchRestClientAutoConfiguration.class)); @Test void restClientCanQueryElasticsearchNode() { this.contextRunner - .withPropertyValues("spring.elasticsearch.uris=" + elasticsearch.getHttpHostAddress(), - "spring.elasticsearch.connection-timeout=120s", "spring.elasticsearch.socket-timeout=120s") - .run((context) -> { - ReactiveElasticsearchClient client = context.getBean(ReactiveElasticsearchClient.class); - Map source = new HashMap<>(); - source.put("a", "alpha"); - source.put("b", "bravo"); - IndexRequest indexRequest = new IndexRequest("foo").id("1").source(source); - GetRequest getRequest = new GetRequest("foo").id("1"); - GetResult getResult = client.index(indexRequest).then(client.get(getRequest)).block(); - assertThat(getResult).isNotNull(); - assertThat(getResult.isExists()).isTrue(); - }); + .withPropertyValues("spring.elasticsearch.uris=" + elasticsearch.getHttpHostAddress(), + "spring.elasticsearch.connection-timeout=120s", "spring.elasticsearch.socket-timeout=120s") + .run((context) -> { + ReactiveElasticsearchClient client = context.getBean(ReactiveElasticsearchClient.class); + Map source = new HashMap<>(); + source.put("a", "alpha"); + source.put("b", "bravo"); + IndexRequest indexRequest = new IndexRequest("foo").id("1").source(source); + GetRequest getRequest = new GetRequest("foo").id("1"); + GetResult getResult = client.index(indexRequest).then(client.get(getRequest)).block(); + assertThat(getResult).isNotNull(); + assertThat(getResult.isExists()).isTrue(); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRestClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRestClientAutoConfigurationTests.java index 31463dc37f..5dd5e7f099 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRestClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRestClientAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,13 +54,13 @@ import static org.mockito.Mockito.mock; class ReactiveElasticsearchRestClientAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveElasticsearchRestClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveElasticsearchRestClientAutoConfiguration.class)); @Test void configureShouldCreateDefaultBeans() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(ClientConfiguration.class) - .hasSingleBean(ReactiveElasticsearchClient.class); + .hasSingleBean(ReactiveElasticsearchClient.class); List endpoints = context.getBean(ClientConfiguration.class).getEndpoints(); assertThat(endpoints).hasSize(1); assertThat(endpoints.get(0).getHostString()).isEqualTo("localhost"); @@ -70,42 +70,44 @@ class ReactiveElasticsearchRestClientAutoConfigurationTests { @Test void configureWhenCustomClientShouldBackOff() { - this.contextRunner.withUserConfiguration(CustomClientConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(ReactiveElasticsearchClient.class).hasBean("customClient")); + this.contextRunner.withUserConfiguration(CustomClientConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(ReactiveElasticsearchClient.class) + .hasBean("customClient")); } @Test void configureWhenCustomClientConfig() { this.contextRunner.withUserConfiguration(CustomClientConfigConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ReactiveElasticsearchClient.class) - .hasSingleBean(ClientConfiguration.class).hasBean("customClientConfiguration")); + .run((context) -> assertThat(context).hasSingleBean(ReactiveElasticsearchClient.class) + .hasSingleBean(ClientConfiguration.class) + .hasBean("customClientConfiguration")); } @Test @Deprecated void whenEndpointIsCustomizedThenClientConfigurationHasCustomEndpoint() { this.contextRunner.withPropertyValues("spring.data.elasticsearch.client.reactive.endpoints=localhost:9876") - .run((context) -> { - List endpoints = context.getBean(ClientConfiguration.class).getEndpoints(); - assertThat(endpoints).hasSize(1); - assertThat(endpoints.get(0).getHostString()).isEqualTo("localhost"); - assertThat(endpoints.get(0).getPort()).isEqualTo(9876); - }); + .run((context) -> { + List endpoints = context.getBean(ClientConfiguration.class).getEndpoints(); + assertThat(endpoints).hasSize(1); + assertThat(endpoints.get(0).getHostString()).isEqualTo("localhost"); + assertThat(endpoints.get(0).getPort()).isEqualTo(9876); + }); } @Test @Deprecated void whenMultipleEndpointsAreConfiguredThenClientConfigurationHasMultipleEndpoints() { this.contextRunner - .withPropertyValues("spring.data.elasticsearch.client.reactive.endpoints=localhost:9876,localhost:8765") - .run((context) -> { - List endpoints = context.getBean(ClientConfiguration.class).getEndpoints(); - assertThat(endpoints).hasSize(2); - assertThat(endpoints.get(0).getHostString()).isEqualTo("localhost"); - assertThat(endpoints.get(0).getPort()).isEqualTo(9876); - assertThat(endpoints.get(1).getHostString()).isEqualTo("localhost"); - assertThat(endpoints.get(1).getPort()).isEqualTo(8765); - }); + .withPropertyValues("spring.data.elasticsearch.client.reactive.endpoints=localhost:9876,localhost:8765") + .run((context) -> { + List endpoints = context.getBean(ClientConfiguration.class).getEndpoints(); + assertThat(endpoints).hasSize(2); + assertThat(endpoints.get(0).getHostString()).isEqualTo("localhost"); + assertThat(endpoints.get(0).getPort()).isEqualTo(9876); + assertThat(endpoints.get(1).getHostString()).isEqualTo("localhost"); + assertThat(endpoints.get(1).getPort()).isEqualTo(8765); + }); } @Test @@ -133,39 +135,40 @@ class ReactiveElasticsearchRestClientAutoConfigurationTests { @Test void whenMultipleUrisAreConfiguredThenClientConfigurationHasMultipleEndpoints() { this.contextRunner.withPropertyValues("spring.elasticsearch.uris=http://localhost:9876,http://localhost:8765") - .run((context) -> { - List endpoints = context.getBean(ClientConfiguration.class).getEndpoints(); - assertThat(endpoints).hasSize(2); - assertThat(endpoints.get(0).getHostString()).isEqualTo("localhost"); - assertThat(endpoints.get(0).getPort()).isEqualTo(9876); - assertThat(endpoints.get(1).getHostString()).isEqualTo("localhost"); - assertThat(endpoints.get(1).getPort()).isEqualTo(8765); - }); + .run((context) -> { + List endpoints = context.getBean(ClientConfiguration.class).getEndpoints(); + assertThat(endpoints).hasSize(2); + assertThat(endpoints.get(0).getHostString()).isEqualTo("localhost"); + assertThat(endpoints.get(0).getPort()).isEqualTo(9876); + assertThat(endpoints.get(1).getHostString()).isEqualTo("localhost"); + assertThat(endpoints.get(1).getPort()).isEqualTo(8765); + }); } @Test void whenMultipleUrisHaveHttpsSchemeThenClientConfigurationUsesSsl() { this.contextRunner.withPropertyValues("spring.elasticsearch.uris=https://localhost:9876,https://localhost:8765") - .run((context) -> { - ClientConfiguration clientConfiguration = context.getBean(ClientConfiguration.class); - List endpoints = clientConfiguration.getEndpoints(); - assertThat(endpoints).hasSize(2); - assertThat(endpoints.get(0).getHostString()).isEqualTo("localhost"); - assertThat(endpoints.get(0).getPort()).isEqualTo(9876); - assertThat(endpoints.get(1).getHostString()).isEqualTo("localhost"); - assertThat(endpoints.get(1).getPort()).isEqualTo(8765); - assertThat(clientConfiguration.useSsl()).isTrue(); - }); + .run((context) -> { + ClientConfiguration clientConfiguration = context.getBean(ClientConfiguration.class); + List endpoints = clientConfiguration.getEndpoints(); + assertThat(endpoints).hasSize(2); + assertThat(endpoints.get(0).getHostString()).isEqualTo("localhost"); + assertThat(endpoints.get(0).getPort()).isEqualTo(9876); + assertThat(endpoints.get(1).getHostString()).isEqualTo("localhost"); + assertThat(endpoints.get(1).getPort()).isEqualTo(8765); + assertThat(clientConfiguration.useSsl()).isTrue(); + }); } @Test void whenMultipleUrisHaveVaryingSchemesThenRunFails() { this.contextRunner.withPropertyValues("spring.elasticsearch.uris=https://localhost:9876,http://localhost:8765") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasRootCauseInstanceOf(IllegalArgumentException.class) - .hasRootCauseMessage("Configured Elasticsearch URIs have varying schemes"); - }); + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure() + .hasRootCauseInstanceOf(IllegalArgumentException.class) + .hasRootCauseMessage("Configured Elasticsearch URIs have varying schemes"); + }); } @Test @@ -180,95 +183,97 @@ class ReactiveElasticsearchRestClientAutoConfigurationTests { @Test void whenUriHasUsernameAndPasswordThenDefaultAuthorizationHeaderHasUsernameAndPassword() { this.contextRunner.withPropertyValues("spring.elasticsearch.uris=http://user:secret@localhost:9200") - .run((context) -> { - ClientConfiguration clientConfiguration = context.getBean(ClientConfiguration.class); - assertThat(clientConfiguration.getDefaultHeaders().get(HttpHeaders.AUTHORIZATION)) - .containsExactly("Basic " + Base64.getEncoder() - .encodeToString("user:secret".getBytes(StandardCharsets.UTF_8))); - }); + .run((context) -> { + ClientConfiguration clientConfiguration = context.getBean(ClientConfiguration.class); + assertThat(clientConfiguration.getDefaultHeaders().get(HttpHeaders.AUTHORIZATION)).containsExactly( + "Basic " + Base64.getEncoder().encodeToString("user:secret".getBytes(StandardCharsets.UTF_8))); + }); } @Test void whenMultipleUrisHaveVaryingUserInfosThenRunFails() { this.contextRunner - .withPropertyValues("spring.elasticsearch.uris=http://user:secret@localhost:9876,http://localhost:8765") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasRootCauseInstanceOf(IllegalArgumentException.class) - .hasRootCauseMessage("Configured Elasticsearch URIs have varying user infos"); - }); + .withPropertyValues("spring.elasticsearch.uris=http://user:secret@localhost:9876,http://localhost:8765") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure() + .hasRootCauseInstanceOf(IllegalArgumentException.class) + .hasRootCauseMessage("Configured Elasticsearch URIs have varying user infos"); + }); } @Test void whenUriUserInfoMatchesUsernameAndPasswordPropertiesThenDefaultAuthorizationHeaderIsConfigured() { - this.contextRunner.withPropertyValues("spring.elasticsearch.uris=http://user:secret@localhost:9876", - "spring.elasticsearch.username=user", "spring.elasticsearch.password=secret").run((context) -> { - ClientConfiguration clientConfiguration = context.getBean(ClientConfiguration.class); - assertThat(clientConfiguration.getDefaultHeaders().get(HttpHeaders.AUTHORIZATION)) - .containsExactly("Basic " + Base64.getEncoder() - .encodeToString("user:secret".getBytes(StandardCharsets.UTF_8))); - }); + this.contextRunner + .withPropertyValues("spring.elasticsearch.uris=http://user:secret@localhost:9876", + "spring.elasticsearch.username=user", "spring.elasticsearch.password=secret") + .run((context) -> { + ClientConfiguration clientConfiguration = context.getBean(ClientConfiguration.class); + assertThat(clientConfiguration.getDefaultHeaders().get(HttpHeaders.AUTHORIZATION)).containsExactly( + "Basic " + Base64.getEncoder().encodeToString("user:secret".getBytes(StandardCharsets.UTF_8))); + }); } @Test void whenUriUserInfoAndUsernameAndPasswordPropertiesDoNotMatchThenRunFails() { this.contextRunner - .withPropertyValues("spring.elasticsearch.uris=http://user:secret@localhost:9876", - "spring.elasticsearch.username=alice", "spring.elasticsearch.password=confidential") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasRootCauseInstanceOf(IllegalArgumentException.class) - .hasRootCauseMessage("Credentials from URI user info do not match those from " - + "spring.elasticsearch.username and spring.elasticsearch.password"); - }); + .withPropertyValues("spring.elasticsearch.uris=http://user:secret@localhost:9876", + "spring.elasticsearch.username=alice", "spring.elasticsearch.password=confidential") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure() + .hasRootCauseInstanceOf(IllegalArgumentException.class) + .hasRootCauseMessage("Credentials from URI user info do not match those from " + + "spring.elasticsearch.username and spring.elasticsearch.password"); + }); } @Test @Deprecated void whenConfiguredToUseSslThenClientConfigurationUsesSsl() { this.contextRunner.withPropertyValues("spring.data.elasticsearch.client.reactive.use-ssl=true") - .run((context) -> assertThat(context.getBean(ClientConfiguration.class).useSsl()).isTrue()); + .run((context) -> assertThat(context.getBean(ClientConfiguration.class).useSsl()).isTrue()); } @Test void whenSocketTimeoutIsNotConfiguredThenClientConfigurationUsesDefault() { this.contextRunner.run((context) -> assertThat(context.getBean(ClientConfiguration.class).getSocketTimeout()) - .isEqualTo(Duration.ofSeconds(30))); + .isEqualTo(Duration.ofSeconds(30))); } @Test void whenConnectionTimeoutIsNotConfiguredThenClientConfigurationUsesDefault() { this.contextRunner.run((context) -> assertThat(context.getBean(ClientConfiguration.class).getConnectTimeout()) - .isEqualTo(Duration.ofSeconds(1))); + .isEqualTo(Duration.ofSeconds(1))); } @ParameterizedPropertyPrefixTest void whenSocketTimeoutIsConfiguredThenClientConfigurationHasCustomSocketTimeout(String prefix) { this.contextRunner.withPropertyValues(prefix + "socket-timeout=2s") - .run((context) -> assertThat(context.getBean(ClientConfiguration.class).getSocketTimeout()) - .isEqualTo(Duration.ofSeconds(2))); + .run((context) -> assertThat(context.getBean(ClientConfiguration.class).getSocketTimeout()) + .isEqualTo(Duration.ofSeconds(2))); } @ParameterizedPropertyPrefixTest void whenConnectionTimeoutIsConfiguredThenClientConfigurationHasCustomConnectTimeout(String prefix) { this.contextRunner.withPropertyValues(prefix + "connection-timeout=2s") - .run((context) -> assertThat(context.getBean(ClientConfiguration.class).getConnectTimeout()) - .isEqualTo(Duration.ofSeconds(2))); + .run((context) -> assertThat(context.getBean(ClientConfiguration.class).getConnectTimeout()) + .isEqualTo(Duration.ofSeconds(2))); } @Test void whenPathPrefixIsConfiguredThenClientConfigurationHasPathPrefix() { this.contextRunner.withPropertyValues("spring.elasticsearch.path-prefix=/some/prefix") - .run((context) -> assertThat(context.getBean(ClientConfiguration.class).getPathPrefix()) - .isEqualTo("/some/prefix")); + .run((context) -> assertThat(context.getBean(ClientConfiguration.class).getPathPrefix()) + .isEqualTo("/some/prefix")); } @ParameterizedPropertyPrefixTest void whenCredentialsAreConfiguredThenClientConfigurationHasDefaultAuthorizationHeader(String prefix) { this.contextRunner.withPropertyValues(prefix + "username=alice", prefix + "password=secret") - .run((context) -> assertThat( - context.getBean(ClientConfiguration.class).getDefaultHeaders().get(HttpHeaders.AUTHORIZATION)) - .containsExactly("Basic YWxpY2U6c2VjcmV0")); + .run((context) -> assertThat( + context.getBean(ClientConfiguration.class).getDefaultHeaders().get(HttpHeaders.AUTHORIZATION)) + .containsExactly("Basic YWxpY2U6c2VjcmV0")); } @ParameterizedTest @@ -277,8 +282,9 @@ class ReactiveElasticsearchRestClientAutoConfigurationTests { this.contextRunner.withPropertyValues(prefix + "max-in-memory-size=1MB").run((context) -> { WebClient client = configureWebClient(context.getBean(ClientConfiguration.class).getClientConfigurers()); assertThat(client).extracting("exchangeFunction.strategies.codecConfigurer.defaultCodecs") - .asInstanceOf(InstanceOfAssertFactories.type(DefaultCodecConfig.class)) - .extracting(DefaultCodecConfig::maxInMemorySize).isEqualTo(1024 * 1024); + .asInstanceOf(InstanceOfAssertFactories.type(DefaultCodecConfig.class)) + .extracting(DefaultCodecConfig::maxInMemorySize) + .isEqualTo(1024 * 1024); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfigurationTests.java index ffc40727b2..5b1b1788a3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,12 +49,12 @@ import static org.assertj.core.api.Assertions.assertThat; class JdbcRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JdbcRepositoriesAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JdbcRepositoriesAutoConfiguration.class)); @Test void backsOffWithNoDataSource() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(AbstractJdbcConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(AbstractJdbcConfiguration.class)); } @Test @@ -68,56 +68,59 @@ class JdbcRepositoriesAutoConfigurationTests { @Test void backsOffWithNoTransactionManager() { this.contextRunner.with(database()) - .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class)) - .withUserConfiguration(TestConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(DataSource.class); - assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); - assertThat(context).doesNotHaveBean(AbstractJdbcConfiguration.class); - }); + .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class)) + .withUserConfiguration(TestConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(DataSource.class); + assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); + assertThat(context).doesNotHaveBean(AbstractJdbcConfiguration.class); + }); } @Test void basicAutoConfiguration() { this.contextRunner.with(database()) - .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withUserConfiguration(TestConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(AbstractJdbcConfiguration.class); - assertThat(context).hasSingleBean(CityRepository.class); - assertThat(context.getBean(CityRepository.class).findById(2000L)).isPresent(); - }); + .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withUserConfiguration(TestConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(AbstractJdbcConfiguration.class); + assertThat(context).hasSingleBean(CityRepository.class); + assertThat(context.getBean(CityRepository.class).findById(2000L)).isPresent(); + }); } @Test void autoConfigurationWithNoRepositories() { this.contextRunner.with(database()) - .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withUserConfiguration(EmptyConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(AbstractJdbcConfiguration.class); - assertThat(context).doesNotHaveBean(Repository.class); - }); + .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withUserConfiguration(EmptyConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(AbstractJdbcConfiguration.class); + assertThat(context).doesNotHaveBean(Repository.class); + }); } @Test void honoursUsersEnableJdbcRepositoriesConfiguration() { this.contextRunner.with(database()) - .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withUserConfiguration(EnableRepositoriesConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(AbstractJdbcConfiguration.class); - assertThat(context).hasSingleBean(CityRepository.class); - assertThat(context.getBean(CityRepository.class).findById(2000L)).isPresent(); - }); + .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withUserConfiguration(EnableRepositoriesConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(AbstractJdbcConfiguration.class); + assertThat(context).hasSingleBean(CityRepository.class); + assertThat(context.getBean(CityRepository.class).findById(2000L)).isPresent(); + }); } private Function database() { return (runner) -> runner - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - SqlInitializationAutoConfiguration.class)) - .withPropertyValues("spring.sql.init.schema-locations=classpath:data-city-schema.sql", - "spring.sql.init.data-locations=classpath:city.sql", - "spring.datasource.generate-unique-name:true"); + .withConfiguration( + AutoConfigurations.of(DataSourceAutoConfiguration.class, SqlInitializationAutoConfiguration.class)) + .withPropertyValues("spring.sql.init.schema-locations=classpath:data-city-schema.sql", + "spring.sql.init.data-locations=classpath:city.sql", "spring.datasource.generate-unique-name:true"); } @TestAutoConfigurationPackage(City.class) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/AbstractJpaRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/AbstractJpaRepositoriesAutoConfigurationTests.java index 8c529abea5..f70147809c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/AbstractJpaRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/AbstractJpaRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,9 +58,9 @@ import static org.assertj.core.api.Assertions.assertThat; abstract class AbstractJpaRepositoriesAutoConfigurationTests { final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HibernateJpaAutoConfiguration.class, - JpaRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)) - .withUserConfiguration(EmbeddedDataSourceConfiguration.class); + .withConfiguration(AutoConfigurations.of(HibernateJpaAutoConfiguration.class, + JpaRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)) + .withUserConfiguration(EmbeddedDataSourceConfiguration.class); @Test void testDefaultRepositoryConfiguration() { @@ -84,56 +84,59 @@ abstract class AbstractJpaRepositoriesAutoConfigurationTests { @Test void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Test void whenBootstrapModeIsLazyWithMultipleAsyncExecutorBootstrapExecutorIsConfigured() { this.contextRunner.withUserConfiguration(MultipleAsyncTaskExecutorConfiguration.class) - .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class, - TaskSchedulingAutoConfiguration.class)) - .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=lazy") - .run((context) -> assertThat( - context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) - .isEqualTo(context.getBean("applicationTaskExecutor"))); + .withConfiguration( + AutoConfigurations.of(TaskExecutionAutoConfiguration.class, TaskSchedulingAutoConfiguration.class)) + .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=lazy") + .run((context) -> assertThat( + context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) + .isEqualTo(context.getBean("applicationTaskExecutor"))); } @Test void whenBootstrapModeIsLazyWithSingleAsyncExecutorBootstrapExecutorIsConfigured() { this.contextRunner.withUserConfiguration(SingleAsyncTaskExecutorConfiguration.class) - .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=lazy") - .run((context) -> assertThat( - context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) - .isEqualTo(context.getBean("testAsyncTaskExecutor"))); + .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=lazy") + .run((context) -> assertThat( + context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) + .isEqualTo(context.getBean("testAsyncTaskExecutor"))); } @Test void whenBootstrapModeIsDeferredBootstrapExecutorIsConfigured() { this.contextRunner.withUserConfiguration(MultipleAsyncTaskExecutorConfiguration.class) - .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class, - TaskSchedulingAutoConfiguration.class)) - .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=deferred") - .run((context) -> assertThat( - context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) - .isEqualTo(context.getBean("applicationTaskExecutor"))); + .withConfiguration( + AutoConfigurations.of(TaskExecutionAutoConfiguration.class, TaskSchedulingAutoConfiguration.class)) + .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=deferred") + .run((context) -> assertThat( + context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) + .isEqualTo(context.getBean("applicationTaskExecutor"))); } @Test void whenBootstrapModeIsDefaultBootstrapExecutorIsNotConfigured() { this.contextRunner.withUserConfiguration(MultipleAsyncTaskExecutorConfiguration.class) - .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class, - TaskSchedulingAutoConfiguration.class)) - .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=default").run((context) -> assertThat( - context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()).isNull()); + .withConfiguration( + AutoConfigurations.of(TaskExecutionAutoConfiguration.class, TaskSchedulingAutoConfiguration.class)) + .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=default") + .run((context) -> assertThat( + context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) + .isNull()); } @Test void bootstrapModeIsDefaultByDefault() { this.contextRunner.withUserConfiguration(MultipleAsyncTaskExecutorConfiguration.class) - .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class, - TaskSchedulingAutoConfiguration.class)) - .run((context) -> assertThat( - context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()).isNull()); + .withConfiguration( + AutoConfigurations.of(TaskExecutionAutoConfiguration.class, TaskSchedulingAutoConfiguration.class)) + .run((context) -> assertThat( + context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) + .isNull()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/EnversRevisionRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/EnversRevisionRepositoriesAutoConfigurationTests.java index 9e965bcac0..e49594c6a3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/EnversRevisionRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/EnversRevisionRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ class EnversRevisionRepositoriesAutoConfigurationTests extends AbstractJpaReposi @Test void autoConfigurationShouldSucceedWithRevisionRepository() { this.contextRunner.withUserConfiguration(RevisionRepositoryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(CountryRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(CountryRepository.class)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java index 4efde42ec5..b84ea525a0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ class JpaRepositoriesAutoConfigurationTests extends AbstractJpaRepositoriesAutoC @Test void autoConfigurationShouldFailWithRevisionRepository() { this.contextRunner.withUserConfiguration(RevisionRepositoryConfiguration.class) - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java index 8aa4b6e8a6..cc5acd7c24 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,10 +45,9 @@ import static org.assertj.core.api.Assertions.assertThat; class JpaWebAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, - JpaRepositoriesAutoConfiguration.class, SpringDataWebAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true"); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, + JpaRepositoriesAutoConfiguration.class, SpringDataWebAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test void springDataWebIsConfiguredWithJpaRepositories() { @@ -57,7 +56,7 @@ class JpaWebAutoConfigurationTests { assertThat(context).hasSingleBean(PageableHandlerMethodArgumentResolver.class); assertThat(context).hasSingleBean(SortHandlerMethodArgumentResolver.class); assertThat(context.getBean(FormattingConversionService.class).canConvert(String.class, Distance.class)) - .isTrue(); + .isTrue(); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java index a7bf893dad..628a2171d8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,8 +61,8 @@ import static org.assertj.core.api.Assertions.assertThat; class MongoDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - MongoAutoConfiguration.class, MongoDataAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + MongoAutoConfiguration.class, MongoDataAutoConfiguration.class)); @Test void templateExists() { @@ -93,7 +93,7 @@ class MongoDataAutoConfigurationTests { this.contextRunner.withUserConfiguration(CustomConversionsConfig.class).run((context) -> { MongoTemplate template = context.getBean(MongoTemplate.class); assertThat(template.getConverter().getConversionService().canConvert(MongoClient.class, Boolean.class)) - .isTrue(); + .isTrue(); }); } @@ -124,15 +124,15 @@ class MongoDataAutoConfigurationTests { @Test void customFieldNamingStrategy() { - this.contextRunner.withPropertyValues( - "spring.data.mongodb.field-naming-strategy:" + CamelCaseAbbreviatingFieldNamingStrategy.class.getName()) - .run((context) -> { - MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); - FieldNamingStrategy fieldNamingStrategy = (FieldNamingStrategy) ReflectionTestUtils - .getField(mappingContext, "fieldNamingStrategy"); - assertThat(fieldNamingStrategy.getClass()) - .isEqualTo(CamelCaseAbbreviatingFieldNamingStrategy.class); - }); + this.contextRunner + .withPropertyValues("spring.data.mongodb.field-naming-strategy:" + + CamelCaseAbbreviatingFieldNamingStrategy.class.getName()) + .run((context) -> { + MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); + FieldNamingStrategy fieldNamingStrategy = (FieldNamingStrategy) ReflectionTestUtils + .getField(mappingContext, "fieldNamingStrategy"); + assertThat(fieldNamingStrategy.getClass()).isEqualTo(CamelCaseAbbreviatingFieldNamingStrategy.class); + }); } @Test @@ -154,8 +154,8 @@ class MongoDataAutoConfigurationTests { @Test void interfaceFieldNamingStrategy() { this.contextRunner - .withPropertyValues("spring.data.mongodb.field-naming-strategy:" + FieldNamingStrategy.class.getName()) - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); + .withPropertyValues("spring.data.mongodb.field-naming-strategy:" + FieldNamingStrategy.class.getName()) + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); } @Test @@ -184,7 +184,7 @@ class MongoDataAutoConfigurationTests { @Test void backsOffIfMongoClientBeanIsNotPresent() { ApplicationContextRunner runner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoDataAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoDataAutoConfiguration.class)); runner.run((context) -> assertThat(context).doesNotHaveBean(MongoTemplate.class)); } @@ -207,7 +207,7 @@ class MongoDataAutoConfigurationTests { @Test void autoConfiguresIfUserProvidesMongoDatabaseFactoryButNoClient() { this.contextRunner.withUserConfiguration(MongoDatabaseFactoryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(MongoTemplate.class)); + .run((context) -> assertThat(context).hasSingleBean(MongoTemplate.class)); } @SuppressWarnings({ "unchecked", "rawtypes" }) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfigurationTests.java index 3f7e29890e..993aa22ac0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,8 @@ import static org.assertj.core.api.Assertions.assertThat; class MongoReactiveDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)); @Test void templateExists() { @@ -55,7 +55,7 @@ class MongoReactiveDataAutoConfigurationTests { @Test void whenGridFsDatabaseIsConfiguredThenGridFsTemplateUsesIt() { this.contextRunner.withPropertyValues("spring.data.mongodb.gridfs.database:grid") - .run((context) -> assertThat(grisFsTemplateDatabaseName(context)).isEqualTo("grid")); + .run((context) -> assertThat(grisFsTemplateDatabaseName(context)).isEqualTo("grid")); } @Test @@ -70,7 +70,7 @@ class MongoReactiveDataAutoConfigurationTests { @Test void backsOffIfMongoClientBeanIsNotPresent() { ApplicationContextRunner runner = new ApplicationContextRunner().withConfiguration(AutoConfigurations - .of(PropertyPlaceholderAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)); + .of(PropertyPlaceholderAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)); runner.run((context) -> assertThat(context).doesNotHaveBean(MongoReactiveDataAutoConfiguration.class)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigurationTests.java index e028059f36..62b59e70fd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,9 +49,9 @@ import static org.assertj.core.api.Assertions.assertThat; class MongoReactiveRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, - MongoReactiveRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, + MongoReactiveRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); @Test void testDefaultRepositoryConfiguration() { @@ -69,33 +69,33 @@ class MongoReactiveRepositoriesAutoConfigurationTests { @Test void testNoRepositoryConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); + .run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); } @Test void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(CustomizedConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityMongoDbRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityMongoDbRepository.class)); } @Test void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Test void enablingImperativeRepositoriesDisablesReactiveRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.data.mongodb.repositories.type=imperative") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); + .withPropertyValues("spring.data.mongodb.repositories.type=imperative") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Test void enablingNoRepositoriesDisablesReactiveRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.data.mongodb.repositories.type=none") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); + .withPropertyValues("spring.data.mongodb.repositories.type=none") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java index 6510680504..cad63dfde3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,8 +46,8 @@ import static org.assertj.core.api.Assertions.assertThat; class MongoRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - MongoRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); @Test void testDefaultRepositoryConfiguration() { @@ -65,33 +65,33 @@ class MongoRepositoriesAutoConfigurationTests { @Test void testNoRepositoryConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); + .run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); } @Test void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(CustomizedConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(CityMongoDbRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(CityMongoDbRepository.class)); } @Test void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Test void enablingReactiveRepositoriesDisablesImperativeRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.data.mongodb.repositories.type=reactive") - .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); + .withPropertyValues("spring.data.mongodb.repositories.type=reactive") + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Test void enablingNoRepositoriesDisablesImperativeRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.data.mongodb.repositories.type=none") - .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); + .withPropertyValues("spring.data.mongodb.repositories.type=none") + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java index c5b46119ea..15e1f12c6f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,8 +56,8 @@ import static org.mockito.Mockito.mock; class Neo4jDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(MockedDriverConfiguration.class) - .withConfiguration(AutoConfigurations.of(Neo4jAutoConfiguration.class, Neo4jDataAutoConfiguration.class)); + .withUserConfiguration(MockedDriverConfiguration.class) + .withConfiguration(AutoConfigurations.of(Neo4jAutoConfiguration.class, Neo4jDataAutoConfiguration.class)); @Test void shouldProvideConversions() { @@ -69,7 +69,7 @@ class Neo4jDataAutoConfigurationTests { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(DatabaseSelectionProvider.class); assertThat(context.getBean(DatabaseSelectionProvider.class)) - .isSameAs(DatabaseSelectionProvider.getDefaultSelectionProvider()); + .isSameAs(DatabaseSelectionProvider.getDefaultSelectionProvider()); }); } @@ -78,18 +78,19 @@ class Neo4jDataAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.data.neo4j.database=test").run((context) -> { assertThat(context).hasSingleBean(DatabaseSelectionProvider.class); assertThat(context.getBean(DatabaseSelectionProvider.class).getDatabaseSelection()) - .isEqualTo(DatabaseSelection.byName("test")); + .isEqualTo(DatabaseSelection.byName("test")); }); } @Test void shouldReuseExistingDatabaseNameProvider() { this.contextRunner.withPropertyValues("spring.data.neo4j.database=ignored") - .withUserConfiguration(CustomDatabaseSelectionProviderConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(DatabaseSelectionProvider.class); - assertThat(context.getBean(DatabaseSelectionProvider.class).getDatabaseSelection()) - .isEqualTo(DatabaseSelection.byName("custom")); - }); + .withUserConfiguration(CustomDatabaseSelectionProviderConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(DatabaseSelectionProvider.class); + assertThat(context.getBean(DatabaseSelectionProvider.class).getDatabaseSelection()) + .isEqualTo(DatabaseSelection.byName("custom")); + }); } @Test @@ -102,26 +103,26 @@ class Neo4jDataAutoConfigurationTests { this.contextRunner.withUserConfiguration(CustomDatabaseSelectionProviderConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(Neo4jClient.class); assertThat(context.getBean(Neo4jClient.class)).extracting("databaseSelectionProvider") - .isSameAs(context.getBean(DatabaseSelectionProvider.class)); + .isSameAs(context.getBean(DatabaseSelectionProvider.class)); }); } @Test void shouldReuseExistingNeo4jClient() { this.contextRunner.withBean("myCustomClient", Neo4jClient.class, () -> mock(Neo4jClient.class)) - .run((context) -> assertThat(context).hasSingleBean(Neo4jClient.class).hasBean("myCustomClient")); + .run((context) -> assertThat(context).hasSingleBean(Neo4jClient.class).hasBean("myCustomClient")); } @Test void shouldProvideNeo4jTemplate() { this.contextRunner.withUserConfiguration(CustomDatabaseSelectionProviderConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(Neo4jTemplate.class)); + .run((context) -> assertThat(context).hasSingleBean(Neo4jTemplate.class)); } @Test void shouldReuseExistingNeo4jTemplate() { - this.contextRunner.withBean("myCustomOperations", Neo4jOperations.class, () -> mock(Neo4jOperations.class)).run( - (context) -> assertThat(context).hasSingleBean(Neo4jOperations.class).hasBean("myCustomOperations")); + this.contextRunner.withBean("myCustomOperations", Neo4jOperations.class, () -> mock(Neo4jOperations.class)) + .run((context) -> assertThat(context).hasSingleBean(Neo4jOperations.class).hasBean("myCustomOperations")); } @Test @@ -129,24 +130,24 @@ class Neo4jDataAutoConfigurationTests { this.contextRunner.withUserConfiguration(CustomDatabaseSelectionProviderConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(Neo4jTransactionManager.class); assertThat(context.getBean(Neo4jTransactionManager.class)).extracting("databaseSelectionProvider") - .isSameAs(context.getBean(DatabaseSelectionProvider.class)); + .isSameAs(context.getBean(DatabaseSelectionProvider.class)); }); } @Test void shouldBackoffIfReactiveTransactionManagerIsSet() { this.contextRunner.withBean(ReactiveTransactionManager.class, () -> mock(ReactiveTransactionManager.class)) - .run((context) -> assertThat(context).doesNotHaveBean(Neo4jTransactionManager.class) - .hasSingleBean(TransactionManager.class)); + .run((context) -> assertThat(context).doesNotHaveBean(Neo4jTransactionManager.class) + .hasSingleBean(TransactionManager.class)); } @Test void shouldReuseExistingTransactionManager() { this.contextRunner - .withBean("myCustomTransactionManager", PlatformTransactionManager.class, - () -> mock(PlatformTransactionManager.class)) - .run((context) -> assertThat(context).hasSingleBean(PlatformTransactionManager.class) - .hasBean("myCustomTransactionManager")); + .withBean("myCustomTransactionManager", PlatformTransactionManager.class, + () -> mock(PlatformTransactionManager.class)) + .run((context) -> assertThat(context).hasSingleBean(PlatformTransactionManager.class) + .hasBean("myCustomTransactionManager")); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jReactiveDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jReactiveDataAutoConfigurationTests.java index e04690355f..2c01517290 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jReactiveDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jReactiveDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,16 +51,16 @@ import static org.mockito.Mockito.mock; class Neo4jReactiveDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(MockedDriverConfiguration.class) - .withConfiguration(AutoConfigurations.of(Neo4jAutoConfiguration.class, Neo4jDataAutoConfiguration.class, - Neo4jReactiveDataAutoConfiguration.class)); + .withUserConfiguration(MockedDriverConfiguration.class) + .withConfiguration(AutoConfigurations.of(Neo4jAutoConfiguration.class, Neo4jDataAutoConfiguration.class, + Neo4jReactiveDataAutoConfiguration.class)); @Test void shouldProvideDefaultDatabaseNameProvider() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(ReactiveDatabaseSelectionProvider.class); assertThat(context.getBean(ReactiveDatabaseSelectionProvider.class)) - .isSameAs(ReactiveDatabaseSelectionProvider.getDefaultSelectionProvider()); + .isSameAs(ReactiveDatabaseSelectionProvider.getDefaultSelectionProvider()); }); } @@ -69,21 +69,22 @@ class Neo4jReactiveDataAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.data.neo4j.database=test").run((context) -> { assertThat(context).hasSingleBean(ReactiveDatabaseSelectionProvider.class); StepVerifier.create(context.getBean(ReactiveDatabaseSelectionProvider.class).getDatabaseSelection()) - .consumeNextWith((databaseSelection) -> assertThat(databaseSelection.getValue()).isEqualTo("test")) - .expectComplete(); + .consumeNextWith((databaseSelection) -> assertThat(databaseSelection.getValue()).isEqualTo("test")) + .expectComplete(); }); } @Test void shouldReuseExistingDatabaseNameProvider() { this.contextRunner.withPropertyValues("spring.data.neo4j.database=ignored") - .withUserConfiguration(CustomReactiveDatabaseSelectionProviderConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(ReactiveDatabaseSelectionProvider.class); - StepVerifier.create(context.getBean(ReactiveDatabaseSelectionProvider.class).getDatabaseSelection()) - .consumeNextWith( - (databaseSelection) -> assertThat(databaseSelection.getValue()).isEqualTo("custom")) - .expectComplete(); - }); + .withUserConfiguration(CustomReactiveDatabaseSelectionProviderConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveDatabaseSelectionProvider.class); + StepVerifier.create(context.getBean(ReactiveDatabaseSelectionProvider.class).getDatabaseSelection()) + .consumeNextWith( + (databaseSelection) -> assertThat(databaseSelection.getValue()).isEqualTo("custom")) + .expectComplete(); + }); } @Test @@ -94,43 +95,43 @@ class Neo4jReactiveDataAutoConfigurationTests { @Test void shouldProvideReactiveNeo4jClientWithCustomDatabaseSelectionProvider() { this.contextRunner.withUserConfiguration(CustomReactiveDatabaseSelectionProviderConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveNeo4jClient.class); - assertThat(context.getBean(ReactiveNeo4jClient.class)).extracting("databaseSelectionProvider") - .isSameAs(context.getBean(ReactiveDatabaseSelectionProvider.class)); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveNeo4jClient.class); + assertThat(context.getBean(ReactiveNeo4jClient.class)).extracting("databaseSelectionProvider") + .isSameAs(context.getBean(ReactiveDatabaseSelectionProvider.class)); + }); } @Test void shouldReuseExistingReactiveNeo4jClient() { this.contextRunner - .withBean("myCustomReactiveClient", ReactiveNeo4jClient.class, () -> mock(ReactiveNeo4jClient.class)) - .run((context) -> assertThat(context).hasSingleBean(ReactiveNeo4jClient.class) - .hasBean("myCustomReactiveClient")); + .withBean("myCustomReactiveClient", ReactiveNeo4jClient.class, () -> mock(ReactiveNeo4jClient.class)) + .run((context) -> assertThat(context).hasSingleBean(ReactiveNeo4jClient.class) + .hasBean("myCustomReactiveClient")); } @Test void shouldProvideReactiveNeo4jTemplate() { this.contextRunner.withUserConfiguration(CustomReactiveDatabaseSelectionProviderConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ReactiveNeo4jTemplate.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveNeo4jTemplate.class)); } @Test void shouldReuseExistingReactiveNeo4jTemplate() { this.contextRunner - .withBean("myCustomReactiveOperations", ReactiveNeo4jOperations.class, - () -> mock(ReactiveNeo4jOperations.class)) - .run((context) -> assertThat(context).hasSingleBean(ReactiveNeo4jOperations.class) - .hasBean("myCustomReactiveOperations")); + .withBean("myCustomReactiveOperations", ReactiveNeo4jOperations.class, + () -> mock(ReactiveNeo4jOperations.class)) + .run((context) -> assertThat(context).hasSingleBean(ReactiveNeo4jOperations.class) + .hasBean("myCustomReactiveOperations")); } @Test void shouldUseExistingReactiveTransactionManager() { this.contextRunner - .withBean("myCustomReactiveTransactionManager", ReactiveTransactionManager.class, - () -> mock(ReactiveTransactionManager.class)) - .run((context) -> assertThat(context).hasSingleBean(ReactiveTransactionManager.class) - .hasSingleBean(TransactionManager.class)); + .withBean("myCustomReactiveTransactionManager", ReactiveTransactionManager.class, + () -> mock(ReactiveTransactionManager.class)) + .run((context) -> assertThat(context).hasSingleBean(ReactiveTransactionManager.class) + .hasSingleBean(TransactionManager.class)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jReactiveRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jReactiveRepositoriesAutoConfigurationTests.java index c78b4a1426..3946180313 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jReactiveRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jReactiveRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,45 +43,47 @@ import static org.assertj.core.api.Assertions.assertThat; class Neo4jReactiveRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(MockedDriverConfiguration.class) - .withConfiguration(AutoConfigurations.of(Neo4jDataAutoConfiguration.class, - Neo4jReactiveDataAutoConfiguration.class, Neo4jRepositoriesAutoConfiguration.class, - Neo4jReactiveRepositoriesAutoConfiguration.class)); + .withUserConfiguration(MockedDriverConfiguration.class) + .withConfiguration( + AutoConfigurations.of(Neo4jDataAutoConfiguration.class, Neo4jReactiveDataAutoConfiguration.class, + Neo4jRepositoriesAutoConfiguration.class, Neo4jReactiveRepositoriesAutoConfiguration.class)); @Test void configurationWithDefaultRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ReactiveCityRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveCityRepository.class)); } @Test void configurationWithNoRepositories() { - this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(ReactiveNeo4jTemplate.class).doesNotHaveBean(ReactiveNeo4jRepository.class)); + this.contextRunner.withUserConfiguration(EmptyConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(ReactiveNeo4jTemplate.class) + .doesNotHaveBean(ReactiveNeo4jRepository.class)); } @Test void configurationWithDisabledRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.data.neo4j.repositories.type=none") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveNeo4jRepository.class)); + .withPropertyValues("spring.data.neo4j.repositories.type=none") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveNeo4jRepository.class)); } @Test void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ReactiveNeo4jTemplate.class) - .doesNotHaveBean(ReactiveNeo4jRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveNeo4jTemplate.class) + .doesNotHaveBean(ReactiveNeo4jRepository.class)); } @Test void shouldRespectAtEnableReactiveNeo4jRepositories() { this.contextRunner - .withUserConfiguration(SortOfInvalidCustomConfiguration.class, WithCustomReactiveRepositoryScan.class) - .withPropertyValues("spring.data.neo4j.repositories.type=reactive") - .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class) - .doesNotHaveBean(ReactiveCityRepository.class).doesNotHaveBean(CountryRepository.class) - .hasSingleBean(ReactiveCountryRepository.class)); + .withUserConfiguration(SortOfInvalidCustomConfiguration.class, WithCustomReactiveRepositoryScan.class) + .withPropertyValues("spring.data.neo4j.repositories.type=reactive") + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class) + .doesNotHaveBean(ReactiveCityRepository.class) + .doesNotHaveBean(CountryRepository.class) + .hasSingleBean(ReactiveCountryRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationIntegrationTests.java index 41b4c72487..b32f0dddcc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,8 @@ class Neo4jRepositoriesAutoConfigurationIntegrationTests { @Container private static final Neo4jContainer neo4jServer = new Neo4jContainer<>(DockerImageNames.neo4j()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void neo4jProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java index 708b4372be..2f1badf71f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,41 +50,44 @@ import static org.assertj.core.api.Assertions.assertThat; class Neo4jRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(MockedDriverConfiguration.class).withConfiguration( - AutoConfigurations.of(Neo4jDataAutoConfiguration.class, Neo4jRepositoriesAutoConfiguration.class)); + .withUserConfiguration(MockedDriverConfiguration.class) + .withConfiguration( + AutoConfigurations.of(Neo4jDataAutoConfiguration.class, Neo4jRepositoriesAutoConfiguration.class)); @Test void configurationWithDefaultRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(CityRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(CityRepository.class)); } @Test void configurationWithNoRepositories() { - this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(Neo4jTransactionManager.class).doesNotHaveBean(Neo4jRepository.class)); + this.contextRunner.withUserConfiguration(EmptyConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(Neo4jTransactionManager.class) + .doesNotHaveBean(Neo4jRepository.class)); } @Test void configurationWithDisabledRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.data.neo4j.repositories.type=none") - .run((context) -> assertThat(context).doesNotHaveBean(Neo4jRepository.class)); + .withPropertyValues("spring.data.neo4j.repositories.type=none") + .run((context) -> assertThat(context).doesNotHaveBean(Neo4jRepository.class)); } @Test void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(Neo4jTransactionManager.class) - .doesNotHaveBean(Neo4jRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(Neo4jTransactionManager.class) + .doesNotHaveBean(Neo4jRepository.class)); } @Test void shouldRespectAtEnableNeo4jRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class, WithCustomRepositoryScan.class) - .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class) - .doesNotHaveBean(ReactiveCityRepository.class).hasSingleBean(CountryRepository.class) - .doesNotHaveBean(ReactiveCountryRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class) + .doesNotHaveBean(ReactiveCityRepository.class) + .hasSingleBean(CountryRepository.class) + .doesNotHaveBean(ReactiveCountryRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/r2dbc/R2dbcDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/r2dbc/R2dbcDataAutoConfigurationTests.java index 8a3b8d6733..ed990549fd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/r2dbc/R2dbcDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/r2dbc/R2dbcDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; class R2dbcDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class, R2dbcDataAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class, R2dbcDataAutoConfiguration.class)); @Test void r2dbcEntityTemplateIsConfigured() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/r2dbc/R2dbcRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/r2dbc/R2dbcRepositoriesAutoConfigurationTests.java index 99e372dc80..05e25361de 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/r2dbc/R2dbcRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/r2dbc/R2dbcRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,55 +49,62 @@ import static org.assertj.core.api.Assertions.assertThat; class R2dbcRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(R2dbcRepositoriesAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(R2dbcRepositoriesAutoConfiguration.class)); @Test void backsOffWithNoConnectionFactory() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(R2dbcRepositoryConfigurationExtension.class)); + .run((context) -> assertThat(context).doesNotHaveBean(R2dbcRepositoryConfigurationExtension.class)); } @Test void backsOffWithNoDatabaseClientOperations() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader("org.springframework.r2dbc")) - .withUserConfiguration(TestConfiguration.class).run((context) -> { - assertThat(context).doesNotHaveBean(DatabaseClient.class); - assertThat(context).doesNotHaveBean(R2dbcRepositoryConfigurationExtension.class); - }); + .withClassLoader(new FilteredClassLoader("org.springframework.r2dbc")) + .withUserConfiguration(TestConfiguration.class) + .run((context) -> { + assertThat(context).doesNotHaveBean(DatabaseClient.class); + assertThat(context).doesNotHaveBean(R2dbcRepositoryConfigurationExtension.class); + }); } @Test void basicAutoConfiguration() { this.contextRunner - .withConfiguration( - AutoConfigurations.of(R2dbcAutoConfiguration.class, R2dbcDataAutoConfiguration.class)) - .withUserConfiguration(DatabaseInitializationConfiguration.class, TestConfiguration.class) - .withPropertyValues("spring.r2dbc.generate-unique-name:true").run((context) -> { - assertThat(context).hasSingleBean(CityRepository.class); - context.getBean(CityRepository.class).findById(2000L).as(StepVerifier::create).expectNextCount(1) - .verifyComplete(); - }); + .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class, R2dbcDataAutoConfiguration.class)) + .withUserConfiguration(DatabaseInitializationConfiguration.class, TestConfiguration.class) + .withPropertyValues("spring.r2dbc.generate-unique-name:true") + .run((context) -> { + assertThat(context).hasSingleBean(CityRepository.class); + context.getBean(CityRepository.class) + .findById(2000L) + .as(StepVerifier::create) + .expectNextCount(1) + .verifyComplete(); + }); } @Test void autoConfigurationWithNoRepositories() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .withUserConfiguration(EmptyConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(Repository.class)); + .withUserConfiguration(EmptyConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(Repository.class)); } @Test void honorsUsersEnableR2dbcRepositoriesConfiguration() { this.contextRunner - .withConfiguration( - AutoConfigurations.of(R2dbcAutoConfiguration.class, R2dbcDataAutoConfiguration.class)) - .withUserConfiguration(DatabaseInitializationConfiguration.class, EnableRepositoriesConfiguration.class) - .withPropertyValues("spring.r2dbc.generate-unique-name:true").run((context) -> { - assertThat(context).hasSingleBean(CityRepository.class); - context.getBean(CityRepository.class).findById(2000L).as(StepVerifier::create).expectNextCount(1) - .verifyComplete(); - }); + .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class, R2dbcDataAutoConfiguration.class)) + .withUserConfiguration(DatabaseInitializationConfiguration.class, EnableRepositoriesConfiguration.class) + .withPropertyValues("spring.r2dbc.generate-unique-name:true") + .run((context) -> { + assertThat(context).hasSingleBean(CityRepository.class); + context.getBean(CityRepository.class) + .findById(2000L) + .as(StepVerifier::create) + .expectNextCount(1) + .verifyComplete(); + }); } @Configuration(proxyBeanMethods = false) 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..1703575e2b 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,18 +44,18 @@ import static org.assertj.core.api.Assertions.assertThat; class RedisAutoConfigurationJedisTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)); @Test void connectionFactoryDefaultsToJedis() { this.contextRunner.run((context) -> assertThat(context.getBean("redisConnectionFactory")) - .isInstanceOf(JedisConnectionFactory.class)); + .isInstanceOf(JedisConnectionFactory.class)); } @Test void connectionFactoryIsNotCreatedWhenLettuceIsSelected() { this.contextRunner.withPropertyValues("spring.redis.client-type=lettuce") - .run((context) -> assertThat(context).doesNotHaveBean(RedisConnectionFactory.class)); + .run((context) -> assertThat(context).doesNotHaveBean(RedisConnectionFactory.class)); } @Test @@ -81,30 +81,30 @@ class RedisAutoConfigurationJedisTests { @Test void testRedisUrlConfiguration() { this.contextRunner - .withPropertyValues("spring.redis.host:foo", "spring.redis.url:redis://user:password@example:33") - .run((context) -> { - JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("example"); - assertThat(cf.getPort()).isEqualTo(33); - assertThat(getUserName(cf)).isEqualTo("user"); - assertThat(cf.getPassword()).isEqualTo("password"); - assertThat(cf.isUseSsl()).isFalse(); - }); + .withPropertyValues("spring.redis.host:foo", "spring.redis.url:redis://user:password@example:33") + .run((context) -> { + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("example"); + assertThat(cf.getPort()).isEqualTo(33); + assertThat(getUserName(cf)).isEqualTo("user"); + assertThat(cf.getPassword()).isEqualTo("password"); + assertThat(cf.isUseSsl()).isFalse(); + }); } @Test void testOverrideUrlRedisConfiguration() { this.contextRunner - .withPropertyValues("spring.redis.host:foo", "spring.redis.password:xyz", "spring.redis.port:1000", - "spring.redis.ssl:false", "spring.redis.url:rediss://user:password@example:33") - .run((context) -> { - JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("example"); - assertThat(cf.getPort()).isEqualTo(33); - assertThat(getUserName(cf)).isEqualTo("user"); - assertThat(cf.getPassword()).isEqualTo("password"); - assertThat(cf.isUseSsl()).isTrue(); - }); + .withPropertyValues("spring.redis.host:foo", "spring.redis.password:xyz", "spring.redis.port:1000", + "spring.redis.ssl:false", "spring.redis.url:rediss://user:password@example:33") + .run((context) -> { + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("example"); + assertThat(cf.getPort()).isEqualTo(33); + assertThat(getUserName(cf)).isEqualTo("user"); + assertThat(cf.getPassword()).isEqualTo("password"); + assertThat(cf.isUseSsl()).isTrue(); + }); } @Test @@ -131,39 +131,42 @@ class RedisAutoConfigurationJedisTests { @Test void testRedisConfigurationWithPool() { - this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.jedis.pool.min-idle:1", - "spring.redis.jedis.pool.max-idle:4", "spring.redis.jedis.pool.max-active:16", - "spring.redis.jedis.pool.max-wait:2000", "spring.redis.jedis.pool.time-between-eviction-runs:30000") - .run((context) -> { - JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getPoolConfig().getMinIdle()).isEqualTo(1); - assertThat(cf.getPoolConfig().getMaxIdle()).isEqualTo(4); - assertThat(cf.getPoolConfig().getMaxTotal()).isEqualTo(16); - assertThat(cf.getPoolConfig().getMaxWaitDuration()).isEqualTo(Duration.ofSeconds(2)); - assertThat(cf.getPoolConfig().getDurationBetweenEvictionRuns()).isEqualTo(Duration.ofSeconds(30)); - }); + this.contextRunner + .withPropertyValues("spring.redis.host:foo", "spring.redis.jedis.pool.min-idle:1", + "spring.redis.jedis.pool.max-idle:4", "spring.redis.jedis.pool.max-active:16", + "spring.redis.jedis.pool.max-wait:2000", "spring.redis.jedis.pool.time-between-eviction-runs:30000") + .run((context) -> { + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getPoolConfig().getMinIdle()).isEqualTo(1); + assertThat(cf.getPoolConfig().getMaxIdle()).isEqualTo(4); + assertThat(cf.getPoolConfig().getMaxTotal()).isEqualTo(16); + assertThat(cf.getPoolConfig().getMaxWaitDuration()).isEqualTo(Duration.ofSeconds(2)); + assertThat(cf.getPoolConfig().getDurationBetweenEvictionRuns()).isEqualTo(Duration.ofSeconds(30)); + }); } @Test void testRedisConfigurationDisabledPool() { this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.jedis.pool.enabled:false") - .run((context) -> { - JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getClientConfiguration().isUsePooling()).isEqualTo(false); - }); + .run((context) -> { + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getClientConfiguration().isUsePooling()).isEqualTo(false); + }); } @Test void testRedisConfigurationWithTimeoutAndConnectTimeout() { - this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.timeout:250", - "spring.redis.connect-timeout:1000").run((context) -> { - JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getTimeout()).isEqualTo(250); - assertThat(cf.getClientConfiguration().getConnectTimeout().toMillis()).isEqualTo(1000); - }); + this.contextRunner + .withPropertyValues("spring.redis.host:foo", "spring.redis.timeout:250", + "spring.redis.connect-timeout:1000") + .run((context) -> { + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getTimeout()).isEqualTo(250); + assertThat(cf.getClientConfiguration().getConnectTimeout().toMillis()).isEqualTo(1000); + }); } @Test @@ -179,41 +182,43 @@ class RedisAutoConfigurationJedisTests { @Test void testRedisConfigurationWithClientName() { this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.client-name:spring-boot") - .run((context) -> { - JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getClientName()).isEqualTo("spring-boot"); - }); + .run((context) -> { + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getClientName()).isEqualTo("spring-boot"); + }); } @Test void testRedisConfigurationWithSentinel() { this.contextRunner - .withPropertyValues("spring.redis.sentinel.master:mymaster", - "spring.redis.sentinel.nodes:127.0.0.1:26379,127.0.0.1:26380") - .withUserConfiguration(JedisConnectionFactoryCaptorConfiguration.class).run((context) -> { - assertThat(context).hasFailed(); - assertThat(JedisConnectionFactoryCaptor.connectionFactory.isRedisSentinelAware()).isTrue(); - }); + .withPropertyValues("spring.redis.sentinel.master:mymaster", + "spring.redis.sentinel.nodes:127.0.0.1:26379,127.0.0.1:26380") + .withUserConfiguration(JedisConnectionFactoryCaptorConfiguration.class) + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(JedisConnectionFactoryCaptor.connectionFactory.isRedisSentinelAware()).isTrue(); + }); } @Test void testRedisConfigurationWithSentinelAndAuthentication() { this.contextRunner.withPropertyValues("spring.redis.username=user", "spring.redis.password=password", "spring.redis.sentinel.master:mymaster", "spring.redis.sentinel.nodes:127.0.0.1:26379,127.0.0.1:26380") - .withUserConfiguration(JedisConnectionFactoryCaptorConfiguration.class).run((context) -> { - assertThat(context).hasFailed(); - assertThat(JedisConnectionFactoryCaptor.connectionFactory.isRedisSentinelAware()).isTrue(); - assertThat(getUserName(JedisConnectionFactoryCaptor.connectionFactory)).isEqualTo("user"); - assertThat(JedisConnectionFactoryCaptor.connectionFactory.getPassword()).isEqualTo("password"); - }); + .withUserConfiguration(JedisConnectionFactoryCaptorConfiguration.class) + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(JedisConnectionFactoryCaptor.connectionFactory.isRedisSentinelAware()).isTrue(); + assertThat(getUserName(JedisConnectionFactoryCaptor.connectionFactory)).isEqualTo("user"); + assertThat(JedisConnectionFactoryCaptor.connectionFactory.getPassword()).isEqualTo("password"); + }); } @Test void testRedisConfigurationWithCluster() { this.contextRunner.withPropertyValues("spring.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380") - .run((context) -> assertThat(context.getBean(JedisConnectionFactory.class).getClusterConnection()) - .isNotNull()); + .run((context) -> assertThat(context.getBean(JedisConnectionFactory.class).getClusterConnection()) + .isNotNull()); } private String getUserName(JedisConnectionFactory factory) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationLettuceWithoutCommonsPool2Tests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationLettuceWithoutCommonsPool2Tests.java index 0471a72dde..22d240b0d1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationLettuceWithoutCommonsPool2Tests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationLettuceWithoutCommonsPool2Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; class RedisAutoConfigurationLettuceWithoutCommonsPool2Tests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)); @Test void poolWithoutCommonsPool2IsDisabledByDefault() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java index 5eb1d38c75..c779d02b5e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,7 +76,7 @@ import static org.mockito.Mockito.mock; class RedisAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)); @Test void testDefaultRedisConfiguration() { @@ -90,26 +90,28 @@ class RedisAutoConfigurationTests { @Test void testOverrideRedisConfiguration() { - this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.database:1", - "spring.redis.lettuce.shutdown-timeout:500").run((context) -> { - LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getDatabase()).isEqualTo(1); - assertThat(getUserName(cf)).isNull(); - assertThat(cf.getPassword()).isNull(); - assertThat(cf.isUseSsl()).isFalse(); - assertThat(cf.getShutdownTimeout()).isEqualTo(500); - }); + this.contextRunner + .withPropertyValues("spring.redis.host:foo", "spring.redis.database:1", + "spring.redis.lettuce.shutdown-timeout:500") + .run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getDatabase()).isEqualTo(1); + assertThat(getUserName(cf)).isNull(); + assertThat(cf.getPassword()).isNull(); + assertThat(cf.isUseSsl()).isFalse(); + assertThat(cf.getShutdownTimeout()).isEqualTo(500); + }); } @Test void testCustomizeClientResources() { Tracing tracing = mock(Tracing.class); this.contextRunner.withBean(ClientResourcesBuilderCustomizer.class, () -> (builder) -> builder.tracing(tracing)) - .run((context) -> { - DefaultClientResources clientResources = context.getBean(DefaultClientResources.class); - assertThat(clientResources.tracing()).isEqualTo(tracing); - }); + .run((context) -> { + DefaultClientResources clientResources = context.getBean(DefaultClientResources.class); + assertThat(clientResources.tracing()).isEqualTo(tracing); + }); } @Test @@ -123,30 +125,30 @@ class RedisAutoConfigurationTests { @Test void testRedisUrlConfiguration() { this.contextRunner - .withPropertyValues("spring.redis.host:foo", "spring.redis.url:redis://user:password@example:33") - .run((context) -> { - LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("example"); - assertThat(cf.getPort()).isEqualTo(33); - assertThat(getUserName(cf)).isEqualTo("user"); - assertThat(cf.getPassword()).isEqualTo("password"); - assertThat(cf.isUseSsl()).isFalse(); - }); + .withPropertyValues("spring.redis.host:foo", "spring.redis.url:redis://user:password@example:33") + .run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("example"); + assertThat(cf.getPort()).isEqualTo(33); + assertThat(getUserName(cf)).isEqualTo("user"); + assertThat(cf.getPassword()).isEqualTo("password"); + assertThat(cf.isUseSsl()).isFalse(); + }); } @Test void testOverrideUrlRedisConfiguration() { this.contextRunner - .withPropertyValues("spring.redis.host:foo", "spring.redis.password:xyz", "spring.redis.port:1000", - "spring.redis.ssl:false", "spring.redis.url:rediss://user:password@example:33") - .run((context) -> { - LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("example"); - assertThat(cf.getPort()).isEqualTo(33); - assertThat(getUserName(cf)).isEqualTo("user"); - assertThat(cf.getPassword()).isEqualTo("password"); - assertThat(cf.isUseSsl()).isTrue(); - }); + .withPropertyValues("spring.redis.host:foo", "spring.redis.password:xyz", "spring.redis.port:1000", + "spring.redis.ssl:false", "spring.redis.url:rediss://user:password@example:33") + .run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("example"); + assertThat(cf.getPort()).isEqualTo(33); + assertThat(getUserName(cf)).isEqualTo("user"); + assertThat(cf.getPassword()).isEqualTo("password"); + assertThat(cf.isUseSsl()).isTrue(); + }); } @Test @@ -190,39 +192,46 @@ class RedisAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.lettuce.pool.min-idle:1", "spring.redis.lettuce.pool.max-idle:4", "spring.redis.lettuce.pool.max-active:16", "spring.redis.lettuce.pool.max-wait:2000", "spring.redis.lettuce.pool.time-between-eviction-runs:30000", - "spring.redis.lettuce.shutdown-timeout:1000").run((context) -> { - LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - GenericObjectPoolConfig poolConfig = getPoolingClientConfiguration(cf).getPoolConfig(); - assertThat(poolConfig.getMinIdle()).isEqualTo(1); - assertThat(poolConfig.getMaxIdle()).isEqualTo(4); - assertThat(poolConfig.getMaxTotal()).isEqualTo(16); - assertThat(poolConfig.getMaxWaitDuration()).isEqualTo(Duration.ofSeconds(2)); - assertThat(poolConfig.getDurationBetweenEvictionRuns()).isEqualTo(Duration.ofSeconds(30)); - assertThat(cf.getShutdownTimeout()).isEqualTo(1000); - }); + "spring.redis.lettuce.shutdown-timeout:1000") + .run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + GenericObjectPoolConfig poolConfig = getPoolingClientConfiguration(cf).getPoolConfig(); + assertThat(poolConfig.getMinIdle()).isEqualTo(1); + assertThat(poolConfig.getMaxIdle()).isEqualTo(4); + assertThat(poolConfig.getMaxTotal()).isEqualTo(16); + assertThat(poolConfig.getMaxWaitDuration()).isEqualTo(Duration.ofSeconds(2)); + assertThat(poolConfig.getDurationBetweenEvictionRuns()).isEqualTo(Duration.ofSeconds(30)); + assertThat(cf.getShutdownTimeout()).isEqualTo(1000); + }); } @Test void testRedisConfigurationDisabledPool() { this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.lettuce.pool.enabled:false") - .run((context) -> { - LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getClientConfiguration()).isNotInstanceOf(LettucePoolingClientConfiguration.class); - }); + .run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getClientConfiguration()).isNotInstanceOf(LettucePoolingClientConfiguration.class); + }); } @Test void testRedisConfigurationWithTimeoutAndConnectTimeout() { - this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.timeout:250", - "spring.redis.connect-timeout:1000").run((context) -> { - LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getTimeout()).isEqualTo(250); - assertThat(cf.getClientConfiguration().getClientOptions().get().getSocketOptions() - .getConnectTimeout().toMillis()).isEqualTo(1000); - }); + this.contextRunner + .withPropertyValues("spring.redis.host:foo", "spring.redis.timeout:250", + "spring.redis.connect-timeout:1000") + .run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getTimeout()).isEqualTo(250); + assertThat(cf.getClientConfiguration() + .getClientOptions() + .get() + .getSocketOptions() + .getConnectTimeout() + .toMillis()).isEqualTo(1000); + }); } @Test @@ -231,8 +240,12 @@ class RedisAutoConfigurationTests { LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); assertThat(cf.getHostName()).isEqualTo("foo"); assertThat(cf.getTimeout()).isEqualTo(60000); - assertThat(cf.getClientConfiguration().getClientOptions().get().getSocketOptions().getConnectTimeout() - .toMillis()).isEqualTo(10000); + assertThat(cf.getClientConfiguration() + .getClientOptions() + .get() + .getSocketOptions() + .getConnectTimeout() + .toMillis()).isEqualTo(10000); }); } @@ -247,11 +260,11 @@ class RedisAutoConfigurationTests { @Test void testRedisConfigurationWithClientName() { this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.client-name:spring-boot") - .run((context) -> { - LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getClientName()).isEqualTo("spring-boot"); - }); + .run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getClientName()).isEqualTo("spring-boot"); + }); } @Test @@ -274,75 +287,77 @@ class RedisAutoConfigurationTests { void testRedisConfigurationWithSentinel() { List sentinels = Arrays.asList("127.0.0.1:26379", "127.0.0.1:26380"); this.contextRunner - .withPropertyValues("spring.redis.sentinel.master:mymaster", - "spring.redis.sentinel.nodes:" + StringUtils.collectionToCommaDelimitedString(sentinels)) - .run((context) -> assertThat(context.getBean(LettuceConnectionFactory.class).isRedisSentinelAware()) - .isTrue()); + .withPropertyValues("spring.redis.sentinel.master:mymaster", + "spring.redis.sentinel.nodes:" + StringUtils.collectionToCommaDelimitedString(sentinels)) + .run((context) -> assertThat(context.getBean(LettuceConnectionFactory.class).isRedisSentinelAware()) + .isTrue()); } @Test void testRedisConfigurationWithIpv6Sentinel() { List sentinels = Arrays.asList("[0:0:0:0:0:0:0:1]:26379", "[0:0:0:0:0:0:0:1]:26380"); this.contextRunner - .withPropertyValues("spring.redis.sentinel.master:mymaster", - "spring.redis.sentinel.nodes:" + StringUtils.collectionToCommaDelimitedString(sentinels)) - .run((context) -> assertThat(context.getBean(LettuceConnectionFactory.class).isRedisSentinelAware()) - .isTrue()); + .withPropertyValues("spring.redis.sentinel.master:mymaster", + "spring.redis.sentinel.nodes:" + StringUtils.collectionToCommaDelimitedString(sentinels)) + .run((context) -> assertThat(context.getBean(LettuceConnectionFactory.class).isRedisSentinelAware()) + .isTrue()); } @Test void testRedisConfigurationWithSentinelAndDatabase() { - this.contextRunner.withPropertyValues("spring.redis.database:1", "spring.redis.sentinel.master:mymaster", - "spring.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380").run((context) -> { - LettuceConnectionFactory connectionFactory = context.getBean(LettuceConnectionFactory.class); - assertThat(connectionFactory.getDatabase()).isEqualTo(1); - assertThat(connectionFactory.isRedisSentinelAware()).isTrue(); - }); + this.contextRunner + .withPropertyValues("spring.redis.database:1", "spring.redis.sentinel.master:mymaster", + "spring.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380") + .run((context) -> { + LettuceConnectionFactory connectionFactory = context.getBean(LettuceConnectionFactory.class); + assertThat(connectionFactory.getDatabase()).isEqualTo(1); + assertThat(connectionFactory.isRedisSentinelAware()).isTrue(); + }); } @Test void testRedisConfigurationWithSentinelAndAuthentication() { this.contextRunner - .withPropertyValues("spring.redis.username=user", "spring.redis.password=password", - "spring.redis.sentinel.master:mymaster", - "spring.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380") - .run(assertSentinelConfiguration("user", "password", (sentinelConfiguration) -> { - assertThat(sentinelConfiguration.getSentinelPassword().isPresent()).isFalse(); - Set sentinels = sentinelConfiguration.getSentinels(); - assertThat(sentinels.stream().map(Object::toString).collect(Collectors.toSet())) - .contains("127.0.0.1:26379", "127.0.0.1:26380"); - })); + .withPropertyValues("spring.redis.username=user", "spring.redis.password=password", + "spring.redis.sentinel.master:mymaster", + "spring.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380") + .run(assertSentinelConfiguration("user", "password", (sentinelConfiguration) -> { + assertThat(sentinelConfiguration.getSentinelPassword().isPresent()).isFalse(); + Set sentinels = sentinelConfiguration.getSentinels(); + assertThat(sentinels.stream().map(Object::toString).collect(Collectors.toSet())) + .contains("127.0.0.1:26379", "127.0.0.1:26380"); + })); } @Test void testRedisConfigurationWithSentinelPasswordAndDataNodePassword() { this.contextRunner - .withPropertyValues("spring.redis.password=password", "spring.redis.sentinel.password=secret", - "spring.redis.sentinel.master:mymaster", - "spring.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380") - .run(assertSentinelConfiguration(null, "password", (sentinelConfiguration) -> { - assertThat(sentinelConfiguration.getSentinelUsername()).isNull(); - assertThat(new String(sentinelConfiguration.getSentinelPassword().get())).isEqualTo("secret"); - Set sentinels = sentinelConfiguration.getSentinels(); - assertThat(sentinels.stream().map(Object::toString).collect(Collectors.toSet())) - .contains("127.0.0.1:26379", "127.0.0.1:26380"); - })); + .withPropertyValues("spring.redis.password=password", "spring.redis.sentinel.password=secret", + "spring.redis.sentinel.master:mymaster", + "spring.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380") + .run(assertSentinelConfiguration(null, "password", (sentinelConfiguration) -> { + assertThat(sentinelConfiguration.getSentinelUsername()).isNull(); + assertThat(new String(sentinelConfiguration.getSentinelPassword().get())).isEqualTo("secret"); + Set sentinels = sentinelConfiguration.getSentinels(); + assertThat(sentinels.stream().map(Object::toString).collect(Collectors.toSet())) + .contains("127.0.0.1:26379", "127.0.0.1:26380"); + })); } @Test void testRedisConfigurationWithSentinelAuthenticationAndDataNodeAuthentication() { this.contextRunner - .withPropertyValues("spring.redis.username=username", "spring.redis.password=password", - "spring.redis.sentinel.username=sentinel", "spring.redis.sentinel.password=secret", - "spring.redis.sentinel.master:mymaster", - "spring.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380") - .run(assertSentinelConfiguration("username", "password", (sentinelConfiguration) -> { - assertThat(sentinelConfiguration.getSentinelUsername()).isEqualTo("sentinel"); - assertThat(new String(sentinelConfiguration.getSentinelPassword().get())).isEqualTo("secret"); - Set sentinels = sentinelConfiguration.getSentinels(); - assertThat(sentinels.stream().map(Object::toString).collect(Collectors.toSet())) - .contains("127.0.0.1:26379", "127.0.0.1:26380"); - })); + .withPropertyValues("spring.redis.username=username", "spring.redis.password=password", + "spring.redis.sentinel.username=sentinel", "spring.redis.sentinel.password=secret", + "spring.redis.sentinel.master:mymaster", + "spring.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380") + .run(assertSentinelConfiguration("username", "password", (sentinelConfiguration) -> { + assertThat(sentinelConfiguration.getSentinelUsername()).isEqualTo("sentinel"); + assertThat(new String(sentinelConfiguration.getSentinelPassword().get())).isEqualTo("secret"); + Set sentinels = sentinelConfiguration.getSentinels(); + assertThat(sentinels.stream().map(Object::toString).collect(Collectors.toSet())) + .contains("127.0.0.1:26379", "127.0.0.1:26380"); + })); } private ContextConsumer assertSentinelConfiguration(String userName, String password, @@ -358,41 +373,47 @@ class RedisAutoConfigurationTests { @Test void testRedisSentinelUrlConfiguration() { this.contextRunner - .withPropertyValues( - "spring.redis.url=redis-sentinel://username:password@127.0.0.1:26379,127.0.0.1:26380/mymaster") - .run((context) -> assertThatIllegalStateException() - .isThrownBy(() -> context.getBean(LettuceConnectionFactory.class)) - .withRootCauseInstanceOf(RedisUrlSyntaxException.class).havingRootCause().withMessageContaining( - "Invalid Redis URL 'redis-sentinel://username:password@127.0.0.1:26379,127.0.0.1:26380/mymaster'")); + .withPropertyValues( + "spring.redis.url=redis-sentinel://username:password@127.0.0.1:26379,127.0.0.1:26380/mymaster") + .run((context) -> assertThatIllegalStateException() + .isThrownBy(() -> context.getBean(LettuceConnectionFactory.class)) + .withRootCauseInstanceOf(RedisUrlSyntaxException.class) + .havingRootCause() + .withMessageContaining( + "Invalid Redis URL 'redis-sentinel://username:password@127.0.0.1:26379,127.0.0.1:26380/mymaster'")); } @Test void testRedisConfigurationWithCluster() { List clusterNodes = Arrays.asList("127.0.0.1:27379", "127.0.0.1:27380"); - this.contextRunner.withPropertyValues("spring.redis.cluster.nodes[0]:" + clusterNodes.get(0), - "spring.redis.cluster.nodes[1]:" + clusterNodes.get(1)).run((context) -> { - RedisClusterConfiguration clusterConfiguration = context.getBean(LettuceConnectionFactory.class) - .getClusterConfiguration(); - assertThat(clusterConfiguration.getClusterNodes()).hasSize(2); - assertThat(clusterConfiguration.getClusterNodes()) - .extracting((node) -> node.getHost() + ":" + node.getPort()) - .containsExactlyInAnyOrder("127.0.0.1:27379", "127.0.0.1:27380"); - }); + this.contextRunner + .withPropertyValues("spring.redis.cluster.nodes[0]:" + clusterNodes.get(0), + "spring.redis.cluster.nodes[1]:" + clusterNodes.get(1)) + .run((context) -> { + RedisClusterConfiguration clusterConfiguration = context.getBean(LettuceConnectionFactory.class) + .getClusterConfiguration(); + assertThat(clusterConfiguration.getClusterNodes()).hasSize(2); + assertThat(clusterConfiguration.getClusterNodes()) + .extracting((node) -> node.getHost() + ":" + node.getPort()) + .containsExactlyInAnyOrder("127.0.0.1:27379", "127.0.0.1:27380"); + }); } @Test void testRedisConfigurationWithClusterAndAuthentication() { List clusterNodes = Arrays.asList("127.0.0.1:27379", "127.0.0.1:27380"); - this.contextRunner.withPropertyValues("spring.redis.username=user", "spring.redis.password=password", - "spring.redis.cluster.nodes[0]:" + clusterNodes.get(0), - "spring.redis.cluster.nodes[1]:" + clusterNodes.get(1)).run((context) -> { - LettuceConnectionFactory connectionFactory = context.getBean(LettuceConnectionFactory.class); - assertThat(getUserName(connectionFactory)).isEqualTo("user"); - assertThat(connectionFactory.getPassword()).isEqualTo("password"); - } + this.contextRunner + .withPropertyValues("spring.redis.username=user", "spring.redis.password=password", + "spring.redis.cluster.nodes[0]:" + clusterNodes.get(0), + "spring.redis.cluster.nodes[1]:" + clusterNodes.get(1)) + .run((context) -> { + LettuceConnectionFactory connectionFactory = context.getBean(LettuceConnectionFactory.class); + assertThat(getUserName(connectionFactory)).isEqualTo("user"); + assertThat(connectionFactory.getPassword()).isEqualTo("password"); + } - ); + ); } @Test @@ -406,73 +427,71 @@ class RedisAutoConfigurationTests { @Test void testRedisConfigurationWithClusterCreateClusterClientOptions() { this.contextRunner.withPropertyValues("spring.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380") - .run(assertClientOptions(ClusterClientOptions.class, (options) -> { - assertThat(options.getTimeoutOptions().isApplyConnectionTimeout()).isTrue(); - assertThat(options.getTimeoutOptions().isTimeoutCommands()).isTrue(); - })); + .run(assertClientOptions(ClusterClientOptions.class, (options) -> { + assertThat(options.getTimeoutOptions().isApplyConnectionTimeout()).isTrue(); + assertThat(options.getTimeoutOptions().isTimeoutCommands()).isTrue(); + })); } @Test void testRedisConfigurationWithClusterRefreshPeriod() { this.contextRunner - .withPropertyValues("spring.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", - "spring.redis.lettuce.cluster.refresh.period=30s") - .run(assertClientOptions(ClusterClientOptions.class, - (options) -> assertThat(options.getTopologyRefreshOptions().getRefreshPeriod()) - .hasSeconds(30))); + .withPropertyValues("spring.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", + "spring.redis.lettuce.cluster.refresh.period=30s") + .run(assertClientOptions(ClusterClientOptions.class, + (options) -> assertThat(options.getTopologyRefreshOptions().getRefreshPeriod()).hasSeconds(30))); } @Test void testRedisConfigurationWithClusterAdaptiveRefresh() { this.contextRunner - .withPropertyValues("spring.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", - "spring.redis.lettuce.cluster.refresh.adaptive=true") - .run(assertClientOptions(ClusterClientOptions.class, - (options) -> assertThat(options.getTopologyRefreshOptions().getAdaptiveRefreshTriggers()) - .isEqualTo(EnumSet.allOf(RefreshTrigger.class)))); + .withPropertyValues("spring.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", + "spring.redis.lettuce.cluster.refresh.adaptive=true") + .run(assertClientOptions(ClusterClientOptions.class, + (options) -> assertThat(options.getTopologyRefreshOptions().getAdaptiveRefreshTriggers()) + .isEqualTo(EnumSet.allOf(RefreshTrigger.class)))); } @Test void testRedisConfigurationWithClusterRefreshPeriodHasNoEffectWithNonClusteredConfiguration() { - this.contextRunner.withPropertyValues("spring.redis.cluster.refresh.period=30s").run(assertClientOptions( - ClientOptions.class, (options) -> assertThat(options.getClass()).isEqualTo(ClientOptions.class))); + this.contextRunner.withPropertyValues("spring.redis.cluster.refresh.period=30s") + .run(assertClientOptions(ClientOptions.class, + (options) -> assertThat(options.getClass()).isEqualTo(ClientOptions.class))); } @Test void testRedisConfigurationWithClusterDynamicRefreshSourcesEnabled() { this.contextRunner - .withPropertyValues("spring.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", - "spring.redis.lettuce.cluster.refresh.dynamic-refresh-sources=true") - .run(assertClientOptions(ClusterClientOptions.class, - (options) -> assertThat(options.getTopologyRefreshOptions().useDynamicRefreshSources()) - .isTrue())); + .withPropertyValues("spring.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", + "spring.redis.lettuce.cluster.refresh.dynamic-refresh-sources=true") + .run(assertClientOptions(ClusterClientOptions.class, + (options) -> assertThat(options.getTopologyRefreshOptions().useDynamicRefreshSources()).isTrue())); } @Test void testRedisConfigurationWithClusterDynamicRefreshSourcesDisabled() { this.contextRunner - .withPropertyValues("spring.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", - "spring.redis.lettuce.cluster.refresh.dynamic-refresh-sources=false") - .run(assertClientOptions(ClusterClientOptions.class, - (options) -> assertThat(options.getTopologyRefreshOptions().useDynamicRefreshSources()) - .isFalse())); + .withPropertyValues("spring.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", + "spring.redis.lettuce.cluster.refresh.dynamic-refresh-sources=false") + .run(assertClientOptions(ClusterClientOptions.class, + (options) -> assertThat(options.getTopologyRefreshOptions().useDynamicRefreshSources()).isFalse())); } @Test void testRedisConfigurationWithClusterDynamicSourcesUnspecifiedUsesDefault() { this.contextRunner - .withPropertyValues("spring.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", - "spring.redis.lettuce.cluster.refresh.dynamic-sources=") - .run(assertClientOptions(ClusterClientOptions.class, - (options) -> assertThat(options.getTopologyRefreshOptions().useDynamicRefreshSources()) - .isEqualTo(ClusterTopologyRefreshOptions.DEFAULT_DYNAMIC_REFRESH_SOURCES))); + .withPropertyValues("spring.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", + "spring.redis.lettuce.cluster.refresh.dynamic-sources=") + .run(assertClientOptions(ClusterClientOptions.class, + (options) -> assertThat(options.getTopologyRefreshOptions().useDynamicRefreshSources()) + .isEqualTo(ClusterTopologyRefreshOptions.DEFAULT_DYNAMIC_REFRESH_SOURCES))); } private ContextConsumer assertClientOptions( Class expectedType, Consumer options) { return (context) -> { LettuceClientConfiguration clientConfiguration = context.getBean(LettuceConnectionFactory.class) - .getClientConfiguration(); + .getClientConfiguration(); assertThat(clientConfiguration.getClientOptions()).isPresent(); ClientOptions clientOptions = clientConfiguration.getClientOptions().get(); assertThat(clientOptions.getClass()).isEqualTo(expectedType); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisPropertiesTests.java index 0a42e51a73..5d2544bc44 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,9 +34,9 @@ class RedisPropertiesTests { void lettuceDefaultsAreConsistent() { Lettuce lettuce = new RedisProperties().getLettuce(); ClusterTopologyRefreshOptions defaultClusterTopologyRefreshOptions = ClusterTopologyRefreshOptions.builder() - .build(); + .build(); assertThat(lettuce.getCluster().getRefresh().isDynamicRefreshSources()) - .isEqualTo(defaultClusterTopologyRefreshOptions.useDynamicRefreshSources()); + .isEqualTo(defaultClusterTopologyRefreshOptions.useDynamicRefreshSources()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java index fb0a6abd14..545ace7385 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,8 @@ import static org.assertj.core.api.Assertions.assertThat; */ class RedisReactiveAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( - AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)); @Test void testDefaultRedisConfiguration() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java index fd9c4338e1..1394b4e284 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,14 +48,14 @@ class RedisRepositoriesAutoConfigurationTests { @Container public static RedisContainer redis = new RedisContainer().withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(10)); + .withStartupTimeout(Duration.ofMinutes(10)); private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @BeforeEach void setUp() { TestPropertyValues.of("spring.redis.host=" + redis.getHost(), "spring.redis.port=" + redis.getFirstMappedPort()) - .applyTo(this.context.getEnvironment()); + .applyTo(this.context.getEnvironment()); } @AfterEach diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisUrlSyntaxFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisUrlSyntaxFailureAnalyzerTests.java index 7e13fec03d..d258c73dd8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisUrlSyntaxFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisUrlSyntaxFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class RedisUrlSyntaxFailureAnalyzerTests { RedisUrlSyntaxException exception = new RedisUrlSyntaxException("http://127.0.0.1:26379/mymaster"); FailureAnalysis analysis = new RedisUrlSyntaxFailureAnalyzer().analyze(exception); assertThat(analysis.getDescription()).contains("The URL 'http://127.0.0.1:26379/mymaster' is not valid") - .contains("The scheme 'http' is not supported"); + .contains("The scheme 'http' is not supported"); assertThat(analysis.getAction()).contains("Use the scheme 'redis://' for insecure or 'rediss://' for secure"); } @@ -53,7 +53,7 @@ class RedisUrlSyntaxFailureAnalyzerTests { FailureAnalysis analysis = new RedisUrlSyntaxFailureAnalyzer().analyze(exception); assertThat(analysis.getDescription()).contains( "The URL 'redis-sentinel://username:password@127.0.0.1:26379,127.0.0.1:26380/mymaster' is not valid") - .contains("The scheme 'redis-sentinel' is not supported"); + .contains("The scheme 'redis-sentinel' is not supported"); assertThat(analysis.getAction()).contains("Use spring.redis.sentinel properties"); } @@ -62,7 +62,7 @@ class RedisUrlSyntaxFailureAnalyzerTests { RedisUrlSyntaxException exception = new RedisUrlSyntaxException("redis-socket:///redis/redis.sock"); FailureAnalysis analysis = new RedisUrlSyntaxFailureAnalyzer().analyze(exception); assertThat(analysis.getDescription()).contains("The URL 'redis-socket:///redis/redis.sock' is not valid") - .contains("The scheme 'redis-socket' is not supported"); + .contains("The scheme 'redis-socket' is not supported"); assertThat(analysis.getAction()).contains("Configure the appropriate Spring Data Redis connection beans"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java index 2118e427ac..67cf7109ca 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,18 +37,18 @@ import static org.assertj.core.api.Assertions.assertThat; class SpringDataWebAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SpringDataWebAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SpringDataWebAutoConfiguration.class)); @Test void webSupportIsAutoConfiguredInWebApplicationContexts() { this.contextRunner - .run((context) -> assertThat(context).hasSingleBean(PageableHandlerMethodArgumentResolver.class)); + .run((context) -> assertThat(context).hasSingleBean(PageableHandlerMethodArgumentResolver.class)); } @Test void autoConfigurationBacksOffInNonWebApplicationContexts() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(SpringDataWebAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(PageableHandlerMethodArgumentResolver.class)); + .run((context) -> assertThat(context).doesNotHaveBean(PageableHandlerMethodArgumentResolver.class)); } @Test @@ -57,17 +57,17 @@ class SpringDataWebAutoConfigurationTests { "spring.data.web.pageable.size-parameter=s", "spring.data.web.pageable.default-page-size=10", "spring.data.web.pageable.prefix=abc", "spring.data.web.pageable.qualifier-delimiter=__", "spring.data.web.pageable.max-page-size=100", "spring.data.web.pageable.one-indexed-parameters=true") - .run((context) -> { - PageableHandlerMethodArgumentResolver argumentResolver = context - .getBean(PageableHandlerMethodArgumentResolver.class); - assertThat(argumentResolver).hasFieldOrPropertyWithValue("pageParameterName", "p"); - assertThat(argumentResolver).hasFieldOrPropertyWithValue("sizeParameterName", "s"); - assertThat(argumentResolver).hasFieldOrPropertyWithValue("oneIndexedParameters", true); - assertThat(argumentResolver).hasFieldOrPropertyWithValue("prefix", "abc"); - assertThat(argumentResolver).hasFieldOrPropertyWithValue("qualifierDelimiter", "__"); - assertThat(argumentResolver).hasFieldOrPropertyWithValue("fallbackPageable", PageRequest.of(0, 10)); - assertThat(argumentResolver).hasFieldOrPropertyWithValue("maxPageSize", 100); - }); + .run((context) -> { + PageableHandlerMethodArgumentResolver argumentResolver = context + .getBean(PageableHandlerMethodArgumentResolver.class); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("pageParameterName", "p"); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("sizeParameterName", "s"); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("oneIndexedParameters", true); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("prefix", "abc"); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("qualifierDelimiter", "__"); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("fallbackPageable", PageRequest.of(0, 10)); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("maxPageSize", 100); + }); } @Test @@ -75,7 +75,7 @@ class SpringDataWebAutoConfigurationTests { this.contextRunner.run((context) -> { SpringDataWebProperties.Pageable properties = new SpringDataWebProperties().getPageable(); PageableHandlerMethodArgumentResolver argumentResolver = context - .getBean(PageableHandlerMethodArgumentResolver.class); + .getBean(PageableHandlerMethodArgumentResolver.class); assertThat(argumentResolver).hasFieldOrPropertyWithValue("pageParameterName", properties.getPageParameter()); assertThat(argumentResolver).hasFieldOrPropertyWithValue("sizeParameterName", @@ -95,7 +95,7 @@ class SpringDataWebAutoConfigurationTests { void customizeSort() { this.contextRunner.withPropertyValues("spring.data.web.sort.sort-parameter=s").run((context) -> { SortHandlerMethodArgumentResolver argumentResolver = context - .getBean(SortHandlerMethodArgumentResolver.class); + .getBean(SortHandlerMethodArgumentResolver.class); assertThat(argumentResolver).hasFieldOrPropertyWithValue("sortParameter", "s"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java index 71db00bde2..ac84555daa 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,7 +69,7 @@ class NoSuchBeanDefinitionFailureAnalyzerTests { FailureAnalysis analysis = analyzeFailure(createFailure(StringHandler.class)); assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, String.class); assertThat(analysis.getDescription()) - .doesNotContain("No matching auto-configuration has been found for this type."); + .doesNotContain("No matching auto-configuration has been found for this type."); assertThat(analysis.getAction()).startsWith( String.format("Consider defining a bean of type '%s' in your configuration.", String.class.getName())); } @@ -129,18 +129,18 @@ class NoSuchBeanDefinitionFailureAnalyzerTests { void failureAnalysisForNoMatchName() { FailureAnalysis analysis = analyzeFailure(createFailure(StringNameHandler.class)); assertThat(analysis.getDescription()) - .startsWith(String.format("Constructor in %s required a bean named '%s' that could not be found", - StringNameHandler.class.getName(), "test-string")); + .startsWith(String.format("Constructor in %s required a bean named '%s' that could not be found", + StringNameHandler.class.getName(), "test-string")); assertThat(analysis.getAction()) - .startsWith(String.format("Consider defining a bean named '%s' in your configuration.", "test-string")); + .startsWith(String.format("Consider defining a bean named '%s' in your configuration.", "test-string")); } @Test void failureAnalysisForMissingBeanName() { FailureAnalysis analysis = analyzeFailure(createFailure(StringMissingBeanNameConfiguration.class)); assertThat(analysis.getDescription()) - .startsWith(String.format("Constructor in %s required a bean named '%s' that could not be found", - StringNameHandler.class.getName(), "test-string")); + .startsWith(String.format("Constructor in %s required a bean named '%s' that could not be found", + StringNameHandler.class.getName(), "test-string")); assertBeanMethodDisabled(analysis, "@ConditionalOnBean (types: java.lang.Integer; SearchStrategy: all) did not find any beans", TestMissingBeanAutoConfiguration.class, "string"); @@ -174,8 +174,8 @@ class NoSuchBeanDefinitionFailureAnalyzerTests { createFailure(ConstructorBoundConfigurationPropertiesConfiguration.class)); assertThat(analysis.getAction()).startsWith( String.format("Consider defining a bean of type '%s' in your configuration.", String.class.getName())); - assertThat(analysis.getAction()).contains( - "Consider adding @ConstructorBinding to " + NeedsConstructorBindingProperties.class.getName()); + assertThat(analysis.getAction()) + .contains("Consider adding @ConstructorBinding to " + NeedsConstructorBindingProperties.class.getName()); } private void assertDescriptionConstructorMissingType(FailureAnalysis analysis, Class component, int index, diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java index 9f30c1c7e4..0289be2ee9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,7 +69,7 @@ class EntityScanPackagesTests { @Test void registerFromArrayWhenRegistryIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> EntityScanPackages.register(null)) - .withMessageContaining("Registry must not be null"); + .withMessageContaining("Registry must not be null"); } @@ -77,23 +77,23 @@ class EntityScanPackagesTests { void registerFromArrayWhenPackageNamesIsNullShouldThrowException() { this.context = new AnnotationConfigApplicationContext(); assertThatIllegalArgumentException() - .isThrownBy(() -> EntityScanPackages.register(this.context, (String[]) null)) - .withMessageContaining("PackageNames must not be null"); + .isThrownBy(() -> EntityScanPackages.register(this.context, (String[]) null)) + .withMessageContaining("PackageNames must not be null"); } @Test void registerFromCollectionWhenRegistryIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> EntityScanPackages.register(null, Collections.emptyList())) - .withMessageContaining("Registry must not be null"); + .isThrownBy(() -> EntityScanPackages.register(null, Collections.emptyList())) + .withMessageContaining("Registry must not be null"); } @Test void registerFromCollectionWhenPackageNamesIsNullShouldThrowException() { this.context = new AnnotationConfigApplicationContext(); assertThatIllegalArgumentException() - .isThrownBy(() -> EntityScanPackages.register(this.context, (Collection) null)) - .withMessageContaining("PackageNames must not be null"); + .isThrownBy(() -> EntityScanPackages.register(this.context, (Collection) null)) + .withMessageContaining("PackageNames must not be null"); } @Test @@ -123,8 +123,8 @@ class EntityScanPackagesTests { @Test void entityScanAnnotationWhenHasValueAndBasePackagesAttributeShouldThrow() { assertThatExceptionOfType(AnnotationConfigurationException.class) - .isThrownBy(() -> this.context = new AnnotationConfigApplicationContext( - EntityScanValueAndBasePackagesConfig.class)); + .isThrownBy(() -> this.context = new AnnotationConfigApplicationContext( + EntityScanValueAndBasePackagesConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java index a06d3ac9c1..c73c955f5d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ class EntityScannerTests { @Test void createWhenContextIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new EntityScanner(null)) - .withMessageContaining("Context must not be null"); + .withMessageContaining("Context must not be null"); } @Test @@ -70,7 +70,7 @@ class EntityScannerTests { void scanShouldScanFromResolvedPlaceholderPackage() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("com.example.entity-package=org.springframework.boot.autoconfigure.domain.scan") - .applyTo(context); + .applyTo(context); context.register(ScanPlaceholderConfig.class); context.refresh(); EntityScanner scanner = new EntityScanner(context); @@ -106,14 +106,14 @@ class EntityScannerTests { ClassPathScanningCandidateComponentProvider candidateComponentProvider = mock( ClassPathScanningCandidateComponentProvider.class); given(candidateComponentProvider.findCandidateComponents("org.springframework.boot.autoconfigure.domain.scan")) - .willReturn(Collections.emptySet()); + .willReturn(Collections.emptySet()); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScanConfig.class); TestEntityScanner scanner = new TestEntityScanner(context, candidateComponentProvider); scanner.scan(Entity.class); ArgumentCaptor annotationTypeFilter = ArgumentCaptor.forClass(AnnotationTypeFilter.class); then(candidateComponentProvider).should().addIncludeFilter(annotationTypeFilter.capture()); then(candidateComponentProvider).should() - .findCandidateComponents("org.springframework.boot.autoconfigure.domain.scan"); + .findCandidateComponents("org.springframework.boot.autoconfigure.domain.scan"); then(candidateComponentProvider).shouldHaveNoMoreInteractions(); assertThat(annotationTypeFilter.getValue().getAnnotationType()).isEqualTo(Entity.class); } @@ -121,9 +121,9 @@ class EntityScannerTests { @Test void scanShouldScanCommaSeparatedPackagesInPlaceholderPackage() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of( - "com.example.entity-package=org.springframework.boot.autoconfigure.domain.scan.a,org.springframework.boot.autoconfigure.domain.scan.b") - .applyTo(context); + TestPropertyValues + .of("com.example.entity-package=org.springframework.boot.autoconfigure.domain.scan.a,org.springframework.boot.autoconfigure.domain.scan.b") + .applyTo(context); context.register(ScanPlaceholderConfig.class); context.refresh(); EntityScanner scanner = new EntityScanner(context); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientAutoConfigurationIntegrationTests.java index e979c4d1d8..4c1c29488f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,47 +53,48 @@ class ElasticsearchRestClientAutoConfigurationIntegrationTests { @Container static final ElasticsearchContainer elasticsearch = new ElasticsearchContainer(DockerImageNames.elasticsearch()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class)); @Test @SuppressWarnings("deprecation") void restHighLevelClientCanQueryElasticsearchNode() { this.contextRunner - .withPropertyValues("spring.elasticsearch.uris=" + elasticsearch.getHttpHostAddress(), - "spring.elasticsearch.connection-timeout=120s", "spring.elasticsearch.socket-timeout=120s") - .run((context) -> { - org.elasticsearch.client.RestHighLevelClient client = context - .getBean(org.elasticsearch.client.RestHighLevelClient.class); - Map source = new HashMap<>(); - source.put("a", "alpha"); - source.put("b", "bravo"); - IndexRequest index = new IndexRequest("test").id("1").source(source); - client.index(index, RequestOptions.DEFAULT); - GetRequest getRequest = new GetRequest("test").id("1"); - assertThat(client.get(getRequest, RequestOptions.DEFAULT).isExists()).isTrue(); - }); + .withPropertyValues("spring.elasticsearch.uris=" + elasticsearch.getHttpHostAddress(), + "spring.elasticsearch.connection-timeout=120s", "spring.elasticsearch.socket-timeout=120s") + .run((context) -> { + org.elasticsearch.client.RestHighLevelClient client = context + .getBean(org.elasticsearch.client.RestHighLevelClient.class); + Map source = new HashMap<>(); + source.put("a", "alpha"); + source.put("b", "bravo"); + IndexRequest index = new IndexRequest("test").id("1").source(source); + client.index(index, RequestOptions.DEFAULT); + GetRequest getRequest = new GetRequest("test").id("1"); + assertThat(client.get(getRequest, RequestOptions.DEFAULT).isExists()).isTrue(); + }); } @Test void restClientCanQueryElasticsearchNode() { this.contextRunner - .withPropertyValues("spring.elasticsearch.uris=" + elasticsearch.getHttpHostAddress(), - "spring.elasticsearch.connection-timeout=120s", "spring.elasticsearch.socket-timeout=120s") - .run((context) -> { - RestClient client = context.getBean(RestClient.class); - Request index = new Request("PUT", "/test/_doc/2"); - index.setJsonEntity("{" + " \"a\": \"alpha\"," + " \"b\": \"bravo\"" + "}"); - client.performRequest(index); - Request getRequest = new Request("GET", "/test/_doc/2"); - Response response = client.performRequest(getRequest); - try (InputStream input = response.getEntity().getContent()) { - JsonNode result = new ObjectMapper().readTree(input); - assertThat(result.path("found").asBoolean()).isTrue(); - } - }); + .withPropertyValues("spring.elasticsearch.uris=" + elasticsearch.getHttpHostAddress(), + "spring.elasticsearch.connection-timeout=120s", "spring.elasticsearch.socket-timeout=120s") + .run((context) -> { + RestClient client = context.getBean(RestClient.class); + Request index = new Request("PUT", "/test/_doc/2"); + index.setJsonEntity("{" + " \"a\": \"alpha\"," + " \"b\": \"bravo\"" + "}"); + client.performRequest(index); + Request getRequest = new Request("GET", "/test/_doc/2"); + Response response = client.performRequest(getRequest); + try (InputStream input = response.getEntity().getContent()) { + JsonNode result = new ObjectMapper().readTree(input); + assertThat(result.path("found").asBoolean()).isTrue(); + } + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientAutoConfigurationTests.java index 11a8ee9f58..53a4c31cd4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,66 +60,68 @@ import static org.mockito.Mockito.mock; class ElasticsearchRestClientAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class)); @Test void configureShouldCreateHighLevelAndLowLevelRestClients() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(RestClient.class) - .hasSingleBean(org.elasticsearch.client.RestHighLevelClient.class) - .hasSingleBean(RestClientBuilder.class); + .hasSingleBean(org.elasticsearch.client.RestHighLevelClient.class) + .hasSingleBean(RestClientBuilder.class); assertThat(context.getBean(RestClient.class)) - .isEqualTo(context.getBean(org.elasticsearch.client.RestHighLevelClient.class).getLowLevelClient()); + .isEqualTo(context.getBean(org.elasticsearch.client.RestHighLevelClient.class).getLowLevelClient()); }); } @Test void configureWithoutRestHighLevelClientShouldOnlyCreateRestClientBuilderAndRestClient() { this.contextRunner.withClassLoader(new FilteredClassLoader(org.elasticsearch.client.RestHighLevelClient.class)) - .run((context) -> assertThat(context).hasSingleBean(RestClient.class) - .hasSingleBean(RestClientBuilder.class) - .doesNotHaveBean(org.elasticsearch.client.RestHighLevelClient.class)); + .run((context) -> assertThat(context).hasSingleBean(RestClient.class) + .hasSingleBean(RestClientBuilder.class) + .doesNotHaveBean(org.elasticsearch.client.RestHighLevelClient.class)); } @Test void configureWhenCustomRestClientShouldBackOff() { this.contextRunner.withUserConfiguration(CustomRestClientConfiguration.class) - .run((context) -> assertThat(context) - .doesNotHaveBean(org.elasticsearch.client.RestHighLevelClient.class) - .hasSingleBean(RestClientBuilder.class).hasSingleBean(RestClient.class) - .hasBean("customRestClient")); + .run((context) -> assertThat(context).doesNotHaveBean(org.elasticsearch.client.RestHighLevelClient.class) + .hasSingleBean(RestClientBuilder.class) + .hasSingleBean(RestClient.class) + .hasBean("customRestClient")); } @Test void configureWhenCustomRestHighLevelClientShouldDefineRestClientFromCustomHighLevelClient() { this.contextRunner.withUserConfiguration(CustomRestHighLevelClientConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(org.elasticsearch.client.RestHighLevelClient.class) - .hasSingleBean(RestClient.class).hasBean("elasticsearchRestClient").getBean(RestClient.class) - .isEqualTo(context.getBean(org.elasticsearch.client.RestHighLevelClient.class) - .getLowLevelClient())); + .run((context) -> assertThat(context).hasSingleBean(org.elasticsearch.client.RestHighLevelClient.class) + .hasSingleBean(RestClient.class) + .hasBean("elasticsearchRestClient") + .getBean(RestClient.class) + .isEqualTo(context.getBean(org.elasticsearch.client.RestHighLevelClient.class).getLowLevelClient())); } @Test void configureWhenCustomRestHighLevelClientAndRestClientShouldBackOff() { this.contextRunner.withUserConfiguration(CustomRestHighLevelClientWithRestClientConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(org.elasticsearch.client.RestHighLevelClient.class) - .hasBean("customRestHighLevelClient").hasSingleBean(RestClient.class) - .hasBean("customRestClient")); + .run((context) -> assertThat(context).hasSingleBean(org.elasticsearch.client.RestHighLevelClient.class) + .hasBean("customRestHighLevelClient") + .hasSingleBean(RestClient.class) + .hasBean("customRestClient")); } @Test void configureWhenNoUniqueRestHighLevelClientShouldNotDefineRestClient() { this.contextRunner.withUserConfiguration(TwoCustomRestHighLevelClientsConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(RestClient.class)); + .run((context) -> assertThat(context).doesNotHaveBean(RestClient.class)); } @Test void configureWhenBuilderCustomizerShouldApply() { this.contextRunner.withUserConfiguration(BuilderCustomizerConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(org.elasticsearch.client.RestHighLevelClient.class) - .hasSingleBean(RestClient.class); + .hasSingleBean(RestClient.class); org.elasticsearch.client.RestHighLevelClient restClient = context - .getBean(org.elasticsearch.client.RestHighLevelClient.class); + .getBean(org.elasticsearch.client.RestHighLevelClient.class); RestClient lowLevelClient = restClient.getLowLevelClient(); assertThat(lowLevelClient).hasFieldOrPropertyWithValue("pathPrefix", "/test"); assertThat(lowLevelClient).extracting("client.connmgr.pool.maxTotal").isEqualTo(100); @@ -139,29 +141,32 @@ class ElasticsearchRestClientAutoConfigurationTests { @Test void configureWithLegacyCustomTimeouts() { - this.contextRunner.withPropertyValues("spring.elasticsearch.rest.connection-timeout=15s", - "spring.elasticsearch.rest.read-timeout=1m").run((context) -> { - assertThat(context).hasSingleBean(RestClient.class); - RestClient restClient = context.getBean(RestClient.class); - assertTimeouts(restClient, Duration.ofSeconds(15), Duration.ofMinutes(1)); - }); + this.contextRunner + .withPropertyValues("spring.elasticsearch.rest.connection-timeout=15s", + "spring.elasticsearch.rest.read-timeout=1m") + .run((context) -> { + assertThat(context).hasSingleBean(RestClient.class); + RestClient restClient = context.getBean(RestClient.class); + assertTimeouts(restClient, Duration.ofSeconds(15), Duration.ofMinutes(1)); + }); } @Test void configureWithCustomTimeouts() { - this.contextRunner.withPropertyValues("spring.elasticsearch.connection-timeout=15s", - "spring.elasticsearch.socket-timeout=1m").run((context) -> { - assertThat(context).hasSingleBean(RestClient.class); - RestClient restClient = context.getBean(RestClient.class); - assertTimeouts(restClient, Duration.ofSeconds(15), Duration.ofMinutes(1)); - }); + this.contextRunner + .withPropertyValues("spring.elasticsearch.connection-timeout=15s", "spring.elasticsearch.socket-timeout=1m") + .run((context) -> { + assertThat(context).hasSingleBean(RestClient.class); + RestClient restClient = context.getBean(RestClient.class); + assertTimeouts(restClient, Duration.ofSeconds(15), Duration.ofMinutes(1)); + }); } private static void assertTimeouts(RestClient restClient, Duration connectTimeout, Duration readTimeout) { assertThat(restClient).extracting("client.defaultConfig.socketTimeout") - .isEqualTo(Math.toIntExact(readTimeout.toMillis())); + .isEqualTo(Math.toIntExact(readTimeout.toMillis())); assertThat(restClient).extracting("client.defaultConfig.connectTimeout") - .isEqualTo(Math.toIntExact(connectTimeout.toMillis())); + .isEqualTo(Math.toIntExact(connectTimeout.toMillis())); } @ParameterizedPropertyPrefixTest @@ -169,7 +174,7 @@ class ElasticsearchRestClientAutoConfigurationTests { this.contextRunner.withPropertyValues(prefix + "uris=localhost:9876").run((context) -> { RestClient client = context.getBean(RestClient.class); assertThat(client.getNodes().stream().map(Node::getHost).map(HttpHost::toString)) - .containsExactly("http://localhost:9876"); + .containsExactly("http://localhost:9876"); }); } @@ -178,14 +183,14 @@ class ElasticsearchRestClientAutoConfigurationTests { this.contextRunner.withPropertyValues(prefix + "uris=http://user@localhost:9200").run((context) -> { RestClient client = context.getBean(RestClient.class); assertThat(client.getNodes().stream().map(Node::getHost).map(HttpHost::toString)) - .containsExactly("http://localhost:9200"); + .containsExactly("http://localhost:9200"); assertThat(client) - .extracting("client.credentialsProvider", InstanceOfAssertFactories.type(CredentialsProvider.class)) - .satisfies((credentialsProvider) -> { - Credentials credentials = credentialsProvider.getCredentials(new AuthScope("localhost", 9200)); - assertThat(credentials.getUserPrincipal().getName()).isEqualTo("user"); - assertThat(credentials.getPassword()).isNull(); - }); + .extracting("client.credentialsProvider", InstanceOfAssertFactories.type(CredentialsProvider.class)) + .satisfies((credentialsProvider) -> { + Credentials credentials = credentialsProvider.getCredentials(new AuthScope("localhost", 9200)); + assertThat(credentials.getUserPrincipal().getName()).isEqualTo("user"); + assertThat(credentials.getPassword()).isNull(); + }); }); } @@ -194,38 +199,39 @@ class ElasticsearchRestClientAutoConfigurationTests { this.contextRunner.withPropertyValues(prefix + "uris=http://user:@localhost:9200").run((context) -> { RestClient client = context.getBean(RestClient.class); assertThat(client.getNodes().stream().map(Node::getHost).map(HttpHost::toString)) - .containsExactly("http://localhost:9200"); + .containsExactly("http://localhost:9200"); assertThat(client) - .extracting("client.credentialsProvider", InstanceOfAssertFactories.type(CredentialsProvider.class)) - .satisfies((credentialsProvider) -> { - Credentials credentials = credentialsProvider.getCredentials(new AuthScope("localhost", 9200)); - assertThat(credentials.getUserPrincipal().getName()).isEqualTo("user"); - assertThat(credentials.getPassword()).isEmpty(); - }); + .extracting("client.credentialsProvider", InstanceOfAssertFactories.type(CredentialsProvider.class)) + .satisfies((credentialsProvider) -> { + Credentials credentials = credentialsProvider.getCredentials(new AuthScope("localhost", 9200)); + assertThat(credentials.getUserPrincipal().getName()).isEqualTo("user"); + assertThat(credentials.getPassword()).isEmpty(); + }); }); } @ParameterizedPropertyPrefixTest void configureUriWithUsernameAndPasswordWhenUsernameAndPasswordPropertiesSet(String prefix) { - this.contextRunner.withPropertyValues(prefix + "uris=http://user:password@localhost:9200,localhost:9201", - prefix + "username=admin", prefix + "password=admin").run((context) -> { - RestClient client = context.getBean(RestClient.class); - assertThat(client.getNodes().stream().map(Node::getHost).map(HttpHost::toString)) - .containsExactly("http://localhost:9200", "http://localhost:9201"); - assertThat(client) - .extracting("client.credentialsProvider", - InstanceOfAssertFactories.type(CredentialsProvider.class)) - .satisfies((credentialsProvider) -> { - Credentials uriCredentials = credentialsProvider - .getCredentials(new AuthScope("localhost", 9200)); - assertThat(uriCredentials.getUserPrincipal().getName()).isEqualTo("user"); - assertThat(uriCredentials.getPassword()).isEqualTo("password"); - Credentials defaultCredentials = credentialsProvider - .getCredentials(new AuthScope("localhost", 9201)); - assertThat(defaultCredentials.getUserPrincipal().getName()).isEqualTo("admin"); - assertThat(defaultCredentials.getPassword()).isEqualTo("admin"); - }); - }); + this.contextRunner + .withPropertyValues(prefix + "uris=http://user:password@localhost:9200,localhost:9201", + prefix + "username=admin", prefix + "password=admin") + .run((context) -> { + RestClient client = context.getBean(RestClient.class); + assertThat(client.getNodes().stream().map(Node::getHost).map(HttpHost::toString)) + .containsExactly("http://localhost:9200", "http://localhost:9201"); + assertThat(client) + .extracting("client.credentialsProvider", InstanceOfAssertFactories.type(CredentialsProvider.class)) + .satisfies((credentialsProvider) -> { + Credentials uriCredentials = credentialsProvider + .getCredentials(new AuthScope("localhost", 9200)); + assertThat(uriCredentials.getUserPrincipal().getName()).isEqualTo("user"); + assertThat(uriCredentials.getPassword()).isEqualTo("password"); + Credentials defaultCredentials = credentialsProvider + .getCredentials(new AuthScope("localhost", 9201)); + assertThat(defaultCredentials.getUserPrincipal().getName()).isEqualTo("admin"); + assertThat(defaultCredentials.getPassword()).isEqualTo("admin"); + }); + }); } @Test @@ -239,35 +245,36 @@ class ElasticsearchRestClientAutoConfigurationTests { @Test void configureWithoutSnifferLibraryShouldNotCreateSniffer() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.elasticsearch.client.sniff")) - .run((context) -> assertThat(context).hasSingleBean(org.elasticsearch.client.RestHighLevelClient.class) - .hasSingleBean(RestClient.class).doesNotHaveBean(Sniffer.class)); + .run((context) -> assertThat(context).hasSingleBean(org.elasticsearch.client.RestHighLevelClient.class) + .hasSingleBean(RestClient.class) + .doesNotHaveBean(Sniffer.class)); } @Test void configureShouldCreateSnifferUsingRestClient() { this.contextRunner.withClassLoader(new FilteredClassLoader(org.elasticsearch.client.RestHighLevelClient.class)) - .run((context) -> { - assertThat(context).hasSingleBean(Sniffer.class); - assertThat(context.getBean(Sniffer.class)).hasFieldOrPropertyWithValue("restClient", - context.getBean(RestClient.class)); - // Validate shutdown order as the sniffer must be shutdown before the - // client - assertThat(context.getBeanFactory().getDependentBeans("elasticsearchRestClient")) - .contains("elasticsearchSniffer"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Sniffer.class); + assertThat(context.getBean(Sniffer.class)).hasFieldOrPropertyWithValue("restClient", + context.getBean(RestClient.class)); + // Validate shutdown order as the sniffer must be shutdown before the + // client + assertThat(context.getBeanFactory().getDependentBeans("elasticsearchRestClient")) + .contains("elasticsearchSniffer"); + }); } @ParameterizedSnifferPropertyPrefixTest void configureWithCustomSnifferSettings(String prefix) { this.contextRunner.withPropertyValues(prefix + "interval=180s", prefix + "delay-after-failure=30s") - .run((context) -> { - assertThat(context).hasSingleBean(Sniffer.class); - Sniffer sniffer = context.getBean(Sniffer.class); - assertThat(sniffer).hasFieldOrPropertyWithValue("sniffIntervalMillis", - Duration.ofMinutes(3).toMillis()); - assertThat(sniffer).hasFieldOrPropertyWithValue("sniffAfterFailureDelayMillis", - Duration.ofSeconds(30).toMillis()); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Sniffer.class); + Sniffer sniffer = context.getBean(Sniffer.class); + assertThat(sniffer).hasFieldOrPropertyWithValue("sniffIntervalMillis", + Duration.ofMinutes(3).toMillis()); + assertThat(sniffer).hasFieldOrPropertyWithValue("sniffAfterFailureDelayMillis", + Duration.ofSeconds(30).toMillis()); + }); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/Flyway5xAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/Flyway5xAutoConfigurationTests.java index d2fc87842a..dfc83693a0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/Flyway5xAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/Flyway5xAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,8 @@ import static org.assertj.core.api.Assertions.assertThat; class Flyway5xAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) - .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:" + UUID.randomUUID()); + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) + .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:" + UUID.randomUUID()); @Test void defaultFlyway() { @@ -51,15 +51,15 @@ class Flyway5xAutoConfigurationTests { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); assertThat(flyway.getConfiguration().getLocations()) - .containsExactly(new Location("classpath:db/migration")); + .containsExactly(new Location("classpath:db/migration")); }); } @Test void flywayJavaMigrationsAreIgnored() { this.contextRunner - .withUserConfiguration(DataSourceAutoConfiguration.class, FlywayJavaMigrationsConfiguration.class) - .run((context) -> assertThat(context).hasNotFailed()); + .withUserConfiguration(DataSourceAutoConfiguration.class, FlywayJavaMigrationsConfiguration.class) + .run((context) -> assertThat(context).hasNotFailed()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/Flyway6xAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/Flyway6xAutoConfigurationTests.java index bb5faa2e85..15698c8ed1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/Flyway6xAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/Flyway6xAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,8 @@ import static org.mockito.Mockito.mock; class Flyway6xAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) - .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:" + UUID.randomUUID()); + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) + .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:" + UUID.randomUUID()); @Test void defaultFlyway() { @@ -58,24 +58,24 @@ class Flyway6xAutoConfigurationTests { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); assertThat(flyway.getConfiguration().getLocations()) - .containsExactly(new Location("classpath:db/migration")); + .containsExactly(new Location("classpath:db/migration")); }); } @Test void callbacksAreConfiguredAndOrdered() { this.contextRunner.withUserConfiguration(DataSourceAutoConfiguration.class, CallbackConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - Callback callbackOne = context.getBean("callbackOne", Callback.class); - Callback callbackTwo = context.getBean("callbackTwo", Callback.class); - assertThat(flyway.getConfiguration().getCallbacks()).hasSize(2); - assertThat(flyway.getConfiguration().getCallbacks()).containsExactly(callbackTwo, callbackOne); - InOrder orderedCallbacks = inOrder(callbackOne, callbackTwo); - orderedCallbacks.verify(callbackTwo).handle(any(Event.class), any(Context.class)); - orderedCallbacks.verify(callbackOne).handle(any(Event.class), any(Context.class)); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + Callback callbackOne = context.getBean("callbackOne", Callback.class); + Callback callbackTwo = context.getBean("callbackTwo", Callback.class); + assertThat(flyway.getConfiguration().getCallbacks()).hasSize(2); + assertThat(flyway.getConfiguration().getCallbacks()).containsExactly(callbackTwo, callbackOne); + InOrder orderedCallbacks = inOrder(callbackOne, callbackTwo); + orderedCallbacks.verify(callbackTwo).handle(any(Event.class), any(Context.class)); + orderedCallbacks.verify(callbackOne).handle(any(Event.class), any(Context.class)); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/Flyway7xAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/Flyway7xAutoConfigurationTests.java index 777b7e38a6..8eb8f2f8b9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/Flyway7xAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/Flyway7xAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +48,8 @@ import static org.mockito.Mockito.mock; class Flyway7xAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) - .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:" + UUID.randomUUID()); + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) + .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:" + UUID.randomUUID()); @Test void defaultFlyway() { @@ -57,24 +57,24 @@ class Flyway7xAutoConfigurationTests { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); assertThat(flyway.getConfiguration().getLocations()) - .containsExactly(new Location("classpath:db/migration")); + .containsExactly(new Location("classpath:db/migration")); }); } @Test void callbacksAreConfigured() { this.contextRunner.withUserConfiguration(DataSourceAutoConfiguration.class, CallbackConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - Callback callbackOne = context.getBean("callbackOne", Callback.class); - Callback callbackTwo = context.getBean("callbackTwo", Callback.class); - assertThat(flyway.getConfiguration().getCallbacks()).hasSize(2); - assertThat(flyway.getConfiguration().getCallbacks()).containsExactlyInAnyOrder(callbackTwo, - callbackOne); - then(callbackOne).should(atLeastOnce()).handle(any(Event.class), any(Context.class)); - then(callbackTwo).should(atLeastOnce()).handle(any(Event.class), any(Context.class)); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + Callback callbackOne = context.getBean("callbackOne", Callback.class); + Callback callbackTwo = context.getBean("callbackTwo", Callback.class); + assertThat(flyway.getConfiguration().getCallbacks()).hasSize(2); + assertThat(flyway.getConfiguration().getCallbacks()).containsExactlyInAnyOrder(callbackTwo, + callbackOne); + then(callbackOne).should(atLeastOnce()).handle(any(Event.class), any(Context.class)); + then(callbackTwo).should(atLeastOnce()).handle(any(Event.class), any(Context.class)); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/Flyway9xAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/Flyway9xAutoConfigurationTests.java index 5f223f791d..51d859f42c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/Flyway9xAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/Flyway9xAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,8 @@ import static org.assertj.core.api.Assertions.assertThat; class Flyway9xAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true"); + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test void defaultFlyway() { @@ -45,7 +45,7 @@ class Flyway9xAutoConfigurationTests { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); assertThat(flyway.getConfiguration().getLocations()) - .containsExactly(new Location("classpath:db/migration")); + .containsExactly(new Location("classpath:db/migration")); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java index a535d4572e..f6cd5f2f14 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -101,8 +101,8 @@ import static org.mockito.Mockito.mock; class FlywayAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true"); + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test void backsOffWithNoDataSourceBeanAndNoFlywayUrl() { @@ -112,88 +112,90 @@ class FlywayAutoConfigurationTests { @Test void createsDataSourceWithNoDataSourceBeanAndFlywayUrl() { this.contextRunner.withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:" + UUID.randomUUID()) - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()).isNotNull(); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()).isNotNull(); + }); } @Test void backsOffWithFlywayUrlAndNoSpringJdbc() { this.contextRunner.withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:" + UUID.randomUUID()) - .withClassLoader(new FilteredClassLoader("org.springframework.jdbc")) - .run((context) -> assertThat(context).doesNotHaveBean(Flyway.class)); + .withClassLoader(new FilteredClassLoader("org.springframework.jdbc")) + .run((context) -> assertThat(context).doesNotHaveBean(Flyway.class)); } @Test void createDataSourceWithUrl() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:flywaytest").run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()).isNotNull(); - }); + .withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:flywaytest") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()).isNotNull(); + }); } @Test void createDataSourceWithUser() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:" + UUID.randomUUID(), - "spring.flyway.user:sa") - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()).isNotNull(); - }); + .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:" + UUID.randomUUID(), "spring.flyway.user:sa") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()).isNotNull(); + }); } @Test void createDataSourceDoesNotFallbackToEmbeddedProperties() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:flywaytest").run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - DataSource dataSource = context.getBean(Flyway.class).getConfiguration().getDataSource(); - assertThat(dataSource).isNotNull(); - assertThat(dataSource).hasFieldOrPropertyWithValue("username", null); - assertThat(dataSource).hasFieldOrPropertyWithValue("password", ""); - }); + .withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:flywaytest") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + DataSource dataSource = context.getBean(Flyway.class).getConfiguration().getDataSource(); + assertThat(dataSource).isNotNull(); + assertThat(dataSource).hasFieldOrPropertyWithValue("username", null); + assertThat(dataSource).hasFieldOrPropertyWithValue("password", ""); + }); } @Test void createDataSourceWithUserAndFallbackToEmbeddedProperties() { this.contextRunner.withUserConfiguration(PropertiesBackedH2DataSourceConfiguration.class) - .withPropertyValues("spring.flyway.user:test", "spring.flyway.password:secret").run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - DataSource dataSource = context.getBean(Flyway.class).getConfiguration().getDataSource(); - assertThat(dataSource).isNotNull(); - assertThat(dataSource).extracting("url").asString().startsWith("jdbc:h2:mem:"); - assertThat(dataSource).extracting("username").asString().isEqualTo("test"); - }); + .withPropertyValues("spring.flyway.user:test", "spring.flyway.password:secret") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + DataSource dataSource = context.getBean(Flyway.class).getConfiguration().getDataSource(); + assertThat(dataSource).isNotNull(); + assertThat(dataSource).extracting("url").asString().startsWith("jdbc:h2:mem:"); + assertThat(dataSource).extracting("username").asString().isEqualTo("test"); + }); } @Test void createDataSourceWithUserAndCustomEmbeddedProperties() { this.contextRunner.withUserConfiguration(CustomBackedH2DataSourceConfiguration.class) - .withPropertyValues("spring.flyway.user:test", "spring.flyway.password:secret").run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - String expectedName = context.getBean(CustomBackedH2DataSourceConfiguration.class).name; - String propertiesName = context.getBean(DataSourceProperties.class).determineDatabaseName(); - assertThat(expectedName).isNotEqualTo(propertiesName); - DataSource dataSource = context.getBean(Flyway.class).getConfiguration().getDataSource(); - assertThat(dataSource).isNotNull(); - assertThat(dataSource).extracting("url").asString().startsWith("jdbc:h2:mem:") - .contains(expectedName); - assertThat(dataSource).extracting("username").asString().isEqualTo("test"); - }); + .withPropertyValues("spring.flyway.user:test", "spring.flyway.password:secret") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + String expectedName = context.getBean(CustomBackedH2DataSourceConfiguration.class).name; + String propertiesName = context.getBean(DataSourceProperties.class).determineDatabaseName(); + assertThat(expectedName).isNotEqualTo(propertiesName); + DataSource dataSource = context.getBean(Flyway.class).getConfiguration().getDataSource(); + assertThat(dataSource).isNotNull(); + assertThat(dataSource).extracting("url").asString().startsWith("jdbc:h2:mem:").contains(expectedName); + assertThat(dataSource).extracting("username").asString().isEqualTo("test"); + }); } @Test void flywayDataSource() { this.contextRunner - .withUserConfiguration(FlywayDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()) - .isEqualTo(context.getBean("flywayDataSource")); - }); + .withUserConfiguration(FlywayDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()) + .isEqualTo(context.getBean("flywayDataSource")); + }); } @Test @@ -201,7 +203,7 @@ class FlywayAutoConfigurationTests { this.contextRunner.withUserConfiguration(FlywayDataSourceConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(Flyway.class); assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()) - .isEqualTo(context.getBean("flywayDataSource")); + .isEqualTo(context.getBean("flywayDataSource")); }); } @@ -210,23 +212,23 @@ class FlywayAutoConfigurationTests { this.contextRunner.withUserConfiguration(FlywayMultipleDataSourcesConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(Flyway.class); assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()) - .isEqualTo(context.getBean("flywayDataSource")); + .isEqualTo(context.getBean("flywayDataSource")); }); } @Test void schemaManagementProviderDetectsDataSource() { this.contextRunner - .withUserConfiguration(FlywayDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - FlywaySchemaManagementProvider schemaManagementProvider = context - .getBean(FlywaySchemaManagementProvider.class); - assertThat(schemaManagementProvider.getSchemaManagement(context.getBean(DataSource.class))) - .isEqualTo(SchemaManagement.UNMANAGED); - assertThat(schemaManagementProvider - .getSchemaManagement(context.getBean("flywayDataSource", DataSource.class))) - .isEqualTo(SchemaManagement.MANAGED); - }); + .withUserConfiguration(FlywayDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { + FlywaySchemaManagementProvider schemaManagementProvider = context + .getBean(FlywaySchemaManagementProvider.class); + assertThat(schemaManagementProvider.getSchemaManagement(context.getBean(DataSource.class))) + .isEqualTo(SchemaManagement.UNMANAGED); + assertThat(schemaManagementProvider + .getSchemaManagement(context.getBean("flywayDataSource", DataSource.class))) + .isEqualTo(SchemaManagement.MANAGED); + }); } @Test @@ -235,372 +237,380 @@ class FlywayAutoConfigurationTests { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); assertThat(flyway.getConfiguration().getLocations()) - .containsExactly(new Location("classpath:db/migration")); + .containsExactly(new Location("classpath:db/migration")); }); } @Test void overrideLocations() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.locations:classpath:db/changelog,classpath:db/migration") - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getLocations()).containsExactly( - new Location("classpath:db/changelog"), new Location("classpath:db/migration")); - }); + .withPropertyValues("spring.flyway.locations:classpath:db/changelog,classpath:db/migration") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getLocations()) + .containsExactly(new Location("classpath:db/changelog"), new Location("classpath:db/migration")); + }); } @Test void overrideLocationsList() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.locations[0]:classpath:db/changelog", - "spring.flyway.locations[1]:classpath:db/migration") - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getLocations()).containsExactly( - new Location("classpath:db/changelog"), new Location("classpath:db/migration")); - }); + .withPropertyValues("spring.flyway.locations[0]:classpath:db/changelog", + "spring.flyway.locations[1]:classpath:db/migration") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getLocations()) + .containsExactly(new Location("classpath:db/changelog"), new Location("classpath:db/migration")); + }); } @Test void overrideSchemas() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.schemas:public").run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(Arrays.asList(flyway.getConfiguration().getSchemas()).toString()).isEqualTo("[public]"); - }); + .withPropertyValues("spring.flyway.schemas:public") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(Arrays.asList(flyway.getConfiguration().getSchemas()).toString()).isEqualTo("[public]"); + }); } @Test void overrideDataSourceAndDriverClassName() { String jdbcUrl = "jdbc:hsqldb:mem:flyway" + UUID.randomUUID(); String driverClassName = "org.hsqldb.jdbcDriver"; - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class).withPropertyValues( - "spring.flyway.url:" + jdbcUrl, "spring.flyway.driver-class-name:" + driverClassName).run((context) -> { - Flyway flyway = context.getBean(Flyway.class); - SimpleDriverDataSource dataSource = (SimpleDriverDataSource) flyway.getConfiguration() - .getDataSource(); - assertThat(dataSource.getUrl()).isEqualTo(jdbcUrl); - assertThat(dataSource.getDriver().getClass().getName()).isEqualTo(driverClassName); - }); + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) + .withPropertyValues("spring.flyway.url:" + jdbcUrl, "spring.flyway.driver-class-name:" + driverClassName) + .run((context) -> { + Flyway flyway = context.getBean(Flyway.class); + SimpleDriverDataSource dataSource = (SimpleDriverDataSource) flyway.getConfiguration().getDataSource(); + assertThat(dataSource.getUrl()).isEqualTo(jdbcUrl); + assertThat(dataSource.getDriver().getClass().getName()).isEqualTo(driverClassName); + }); } @Test void changeLogDoesNotExist() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.fail-on-missing-locations=true", - "spring.flyway.locations:filesystem:no-such-dir") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().isInstanceOf(BeanCreationException.class); - }); + .withPropertyValues("spring.flyway.fail-on-missing-locations=true", + "spring.flyway.locations:filesystem:no-such-dir") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().isInstanceOf(BeanCreationException.class); + }); } @Test void failOnMissingLocationsAllMissing() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.fail-on-missing-locations=true") - .withPropertyValues("spring.flyway.locations:classpath:db/missing1,classpath:db/migration2") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().isInstanceOf(BeanCreationException.class); - assertThat(context).getFailure().hasMessageContaining("Unable to resolve location"); - }); + .withPropertyValues("spring.flyway.fail-on-missing-locations=true") + .withPropertyValues("spring.flyway.locations:classpath:db/missing1,classpath:db/migration2") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().isInstanceOf(BeanCreationException.class); + assertThat(context).getFailure().hasMessageContaining("Unable to resolve location"); + }); } @Test void failOnMissingLocationsAllExist() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.fail-on-missing-locations=true") - .withPropertyValues("spring.flyway.locations:classpath:db/changelog,classpath:db/migration") - .run((context) -> assertThat(context).hasNotFailed()); + .withPropertyValues("spring.flyway.fail-on-missing-locations=true") + .withPropertyValues("spring.flyway.locations:classpath:db/changelog,classpath:db/migration") + .run((context) -> assertThat(context).hasNotFailed()); } @Test void failOnMissingLocationsAllExistWithImplicitClasspathPrefix() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.fail-on-missing-locations=true") - .withPropertyValues("spring.flyway.locations:db/changelog,db/migration") - .run((context) -> assertThat(context).hasNotFailed()); + .withPropertyValues("spring.flyway.fail-on-missing-locations=true") + .withPropertyValues("spring.flyway.locations:db/changelog,db/migration") + .run((context) -> assertThat(context).hasNotFailed()); } @Test void failOnMissingLocationsAllExistWithFilesystemPrefix() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.fail-on-missing-locations=true") - .withPropertyValues("spring.flyway.locations:filesystem:src/test/resources/db/migration") - .run((context) -> assertThat(context).hasNotFailed()); + .withPropertyValues("spring.flyway.fail-on-missing-locations=true") + .withPropertyValues("spring.flyway.locations:filesystem:src/test/resources/db/migration") + .run((context) -> assertThat(context).hasNotFailed()); } @Test void customFlywayMigrationStrategy() { this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MockFlywayMigrationStrategy.class) - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - context.getBean(MockFlywayMigrationStrategy.class).assertCalled(); - }); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MockFlywayMigrationStrategy.class) + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + context.getBean(MockFlywayMigrationStrategy.class).assertCalled(); + }); } @Test void flywayJavaMigrations() { this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, FlywayJavaMigrationsConfiguration.class) - .run((context) -> { - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getJavaMigrations()).hasSize(2); - }); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, FlywayJavaMigrationsConfiguration.class) + .run((context) -> { + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getJavaMigrations()).hasSize(2); + }); } @Test void customFlywayMigrationInitializer() { this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, CustomFlywayMigrationInitializer.class) - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - FlywayMigrationInitializer initializer = context.getBean(FlywayMigrationInitializer.class); - assertThat(initializer.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE); - }); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, CustomFlywayMigrationInitializer.class) + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + FlywayMigrationInitializer initializer = context.getBean(FlywayMigrationInitializer.class); + assertThat(initializer.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE); + }); } @Test void customFlywayWithJpa() { this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, CustomFlywayWithJpaConfiguration.class) - .run((context) -> assertThat(context).hasNotFailed()); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, CustomFlywayWithJpaConfiguration.class) + .run((context) -> assertThat(context).hasNotFailed()); } @Test void customFlywayWithJdbc() { this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, CustomFlywayWithJdbcConfiguration.class) - .run((context) -> assertThat(context).hasNotFailed()); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, CustomFlywayWithJdbcConfiguration.class) + .run((context) -> assertThat(context).hasNotFailed()); } @Test void customFlywayMigrationInitializerWithJpa() { this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, - CustomFlywayMigrationInitializerWithJpaConfiguration.class) - .run((context) -> assertThat(context).hasNotFailed()); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, + CustomFlywayMigrationInitializerWithJpaConfiguration.class) + .run((context) -> assertThat(context).hasNotFailed()); } @Test void customFlywayMigrationInitializerWithJdbc() { this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, - CustomFlywayMigrationInitializerWithJdbcConfiguration.class) - .run((context) -> assertThat(context).hasNotFailed()); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, + CustomFlywayMigrationInitializerWithJdbcConfiguration.class) + .run((context) -> assertThat(context).hasNotFailed()); } @Test void overrideBaselineVersionString() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.baseline-version=0").run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getBaselineVersion()) - .isEqualTo(MigrationVersion.fromVersion("0")); - }); + .withPropertyValues("spring.flyway.baseline-version=0") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getBaselineVersion()).isEqualTo(MigrationVersion.fromVersion("0")); + }); } @Test void overrideBaselineVersionNumber() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.baseline-version=1").run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getBaselineVersion()) - .isEqualTo(MigrationVersion.fromVersion("1")); - }); + .withPropertyValues("spring.flyway.baseline-version=1") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getBaselineVersion()).isEqualTo(MigrationVersion.fromVersion("1")); + }); } @Test void useVendorDirectory() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.locations=classpath:db/vendors/{vendor},classpath:db/changelog") - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getLocations()).containsExactlyInAnyOrder( - new Location("classpath:db/vendors/h2"), new Location("classpath:db/changelog")); - }); + .withPropertyValues("spring.flyway.locations=classpath:db/vendors/{vendor},classpath:db/changelog") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getLocations()).containsExactlyInAnyOrder( + new Location("classpath:db/vendors/h2"), new Location("classpath:db/changelog")); + }); } @Test void useOneLocationWithVendorDirectory() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.locations=classpath:db/vendors/{vendor}").run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getLocations()) - .containsExactly(new Location("classpath:db/vendors/h2")); - }); + .withPropertyValues("spring.flyway.locations=classpath:db/vendors/{vendor}") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getLocations()) + .containsExactly(new Location("classpath:db/vendors/h2")); + }); } @Test void callbacksAreConfiguredAndOrderedByName() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, CallbackConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - Callback callbackOne = context.getBean("callbackOne", Callback.class); - Callback callbackTwo = context.getBean("callbackTwo", Callback.class); - assertThat(flyway.getConfiguration().getCallbacks()).hasSize(2); - InOrder orderedCallbacks = inOrder(callbackOne, callbackTwo); - orderedCallbacks.verify(callbackTwo).handle(any(Event.class), any(Context.class)); - orderedCallbacks.verify(callbackOne).handle(any(Event.class), any(Context.class)); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + Callback callbackOne = context.getBean("callbackOne", Callback.class); + Callback callbackTwo = context.getBean("callbackTwo", Callback.class); + assertThat(flyway.getConfiguration().getCallbacks()).hasSize(2); + InOrder orderedCallbacks = inOrder(callbackOne, callbackTwo); + orderedCallbacks.verify(callbackTwo).handle(any(Event.class), any(Context.class)); + orderedCallbacks.verify(callbackOne).handle(any(Event.class), any(Context.class)); + }); } @Test void configurationCustomizersAreConfiguredAndOrdered() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, - ConfigurationCustomizerConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getConnectRetries()).isEqualTo(5); - assertThat(flyway.getConfiguration().getBaselineDescription()).isEqualTo("<< Custom baseline >>"); - assertThat(flyway.getConfiguration().getBaselineVersion()) - .isEqualTo(MigrationVersion.fromVersion("1")); - }); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, ConfigurationCustomizerConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getConnectRetries()).isEqualTo(5); + assertThat(flyway.getConfiguration().getBaselineDescription()).isEqualTo("<< Custom baseline >>"); + assertThat(flyway.getConfiguration().getBaselineVersion()).isEqualTo(MigrationVersion.fromVersion("1")); + }); } @Test void batchIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.batch=true").run(validateFlywayTeamsPropertyOnly("batch")); + .withPropertyValues("spring.flyway.batch=true") + .run(validateFlywayTeamsPropertyOnly("batch")); } @Test void dryRunOutputIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.dryRunOutput=dryrun.sql") - .run(validateFlywayTeamsPropertyOnly("dryRunOutput")); + .withPropertyValues("spring.flyway.dryRunOutput=dryrun.sql") + .run(validateFlywayTeamsPropertyOnly("dryRunOutput")); } @Test void errorOverridesIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.errorOverrides=D12345") - .run(validateFlywayTeamsPropertyOnly("errorOverrides")); + .withPropertyValues("spring.flyway.errorOverrides=D12345") + .run(validateFlywayTeamsPropertyOnly("errorOverrides")); } @Test void licenseKeyIsCorrectlyMapped(CapturedOutput output) { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.license-key=<>") - .run((context) -> assertThat(output).contains( - "Flyway Teams Edition upgrade required: licenseKey is not supported by Flyway Community Edition.")); + .withPropertyValues("spring.flyway.license-key=<>") + .run((context) -> assertThat(output).contains( + "Flyway Teams Edition upgrade required: licenseKey is not supported by Flyway Community Edition.")); } @Test void oracleSqlplusIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.oracle-sqlplus=true") - .run(validateFlywayTeamsPropertyOnly("oracle.sqlplus")); + .withPropertyValues("spring.flyway.oracle-sqlplus=true") + .run(validateFlywayTeamsPropertyOnly("oracle.sqlplus")); } @Test void oracleSqlplusWarnIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.oracle-sqlplus-warn=true") - .run(validateFlywayTeamsPropertyOnly("oracle.sqlplusWarn")); + .withPropertyValues("spring.flyway.oracle-sqlplus-warn=true") + .run(validateFlywayTeamsPropertyOnly("oracle.sqlplusWarn")); } @Test void streamIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.stream=true").run(validateFlywayTeamsPropertyOnly("stream")); + .withPropertyValues("spring.flyway.stream=true") + .run(validateFlywayTeamsPropertyOnly("stream")); } @Test void undoSqlMigrationPrefix() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.undo-sql-migration-prefix=undo") - .run(validateFlywayTeamsPropertyOnly("undoSqlMigrationPrefix")); + .withPropertyValues("spring.flyway.undo-sql-migration-prefix=undo") + .run(validateFlywayTeamsPropertyOnly("undoSqlMigrationPrefix")); } @Test void customFlywayClassLoader() { this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, ResourceLoaderConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getClassLoader()).isInstanceOf(CustomClassLoader.class); - }); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, ResourceLoaderConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getClassLoader()).isInstanceOf(CustomClassLoader.class); + }); } @Test void initSqlsWithDataSource() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.init-sqls=SELECT 1").run((context) -> { - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getInitSql()).isEqualTo("SELECT 1"); - }); + .withPropertyValues("spring.flyway.init-sqls=SELECT 1") + .run((context) -> { + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getInitSql()).isEqualTo("SELECT 1"); + }); } @Test void initSqlsWithFlywayUrl() { - this.contextRunner.withPropertyValues("spring.flyway.url:jdbc:h2:mem:" + UUID.randomUUID(), - "spring.flyway.init-sqls=SELECT 1").run((context) -> { - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getInitSql()).isEqualTo("SELECT 1"); - }); + this.contextRunner + .withPropertyValues("spring.flyway.url:jdbc:h2:mem:" + UUID.randomUUID(), + "spring.flyway.init-sqls=SELECT 1") + .run((context) -> { + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getInitSql()).isEqualTo("SELECT 1"); + }); } @Test void cherryPickIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.cherry-pick=1.1").run(validateFlywayTeamsPropertyOnly("cherryPick")); + .withPropertyValues("spring.flyway.cherry-pick=1.1") + .run(validateFlywayTeamsPropertyOnly("cherryPick")); } @Test void jdbcPropertiesAreCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.jdbc-properties.prop=value") - .run(validateFlywayTeamsPropertyOnly("jdbcProperties")); + .withPropertyValues("spring.flyway.jdbc-properties.prop=value") + .run(validateFlywayTeamsPropertyOnly("jdbcProperties")); } @Test void kerberosConfigFileIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.kerberos-config-file=/tmp/config") - .run(validateFlywayTeamsPropertyOnly("kerberosConfigFile")); + .withPropertyValues("spring.flyway.kerberos-config-file=/tmp/config") + .run(validateFlywayTeamsPropertyOnly("kerberosConfigFile")); } @Test @Deprecated void oracleKerberosConfigFileIsCorrectlyMappedToReplacementProperty() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.oracle-kerberos-config-file=/tmp/config") - .run(validateFlywayTeamsPropertyOnly("kerberosConfigFile")); + .withPropertyValues("spring.flyway.oracle-kerberos-config-file=/tmp/config") + .run(validateFlywayTeamsPropertyOnly("kerberosConfigFile")); } @Test void oracleKerberosCacheFileIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.oracle-kerberos-cache-file=/tmp/cache") - .run(validateFlywayTeamsPropertyOnly("oracle.kerberosCacheFile")); + .withPropertyValues("spring.flyway.oracle-kerberos-cache-file=/tmp/cache") + .run(validateFlywayTeamsPropertyOnly("oracle.kerberosCacheFile")); } @Test void outputQueryResultsIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.output-query-results=false") - .run(validateFlywayTeamsPropertyOnly("outputQueryResults")); + .withPropertyValues("spring.flyway.output-query-results=false") + .run(validateFlywayTeamsPropertyOnly("outputQueryResults")); } @Test void sqlServerKerberosLoginFileIsCorrectlyMapped() { try { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.sql-server-kerberos-login-file=/tmp/config") - .run(validateFlywayTeamsPropertyOnly("sqlserver.kerberos.login.file")); + .withPropertyValues("spring.flyway.sql-server-kerberos-login-file=/tmp/config") + .run(validateFlywayTeamsPropertyOnly("sqlserver.kerberos.login.file")); } finally { // Reset to default value @@ -611,61 +621,62 @@ class FlywayAutoConfigurationTests { @Test void skipExecutingMigrationsIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.skip-executing-migrations=true") - .run(validateFlywayTeamsPropertyOnly("skipExecutingMigrations")); + .withPropertyValues("spring.flyway.skip-executing-migrations=true") + .run(validateFlywayTeamsPropertyOnly("skipExecutingMigrations")); } @Test void whenFlywayIsAutoConfiguredThenJooqDslContextDependsOnFlywayBeans() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, JooqConfiguration.class) - .run((context) -> { - BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); - assertThat(beanDefinition.getDependsOn()).containsExactlyInAnyOrder("flywayInitializer", "flyway"); - }); + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); + assertThat(beanDefinition.getDependsOn()).containsExactlyInAnyOrder("flywayInitializer", "flyway"); + }); } @Test void whenCustomMigrationInitializerIsDefinedThenJooqDslContextDependsOnIt() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, JooqConfiguration.class, - CustomFlywayMigrationInitializer.class).run((context) -> { - BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); - assertThat(beanDefinition.getDependsOn()).containsExactlyInAnyOrder("flywayMigrationInitializer", - "flyway"); - }); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, JooqConfiguration.class, + CustomFlywayMigrationInitializer.class) + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); + assertThat(beanDefinition.getDependsOn()).containsExactlyInAnyOrder("flywayMigrationInitializer", + "flyway"); + }); } @Test void whenCustomFlywayIsDefinedThenJooqDslContextDependsOnIt() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, JooqConfiguration.class, - CustomFlyway.class).run((context) -> { - BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); - assertThat(beanDefinition.getDependsOn()).containsExactlyInAnyOrder("customFlyway"); - }); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, JooqConfiguration.class, CustomFlyway.class) + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); + assertThat(beanDefinition.getDependsOn()).containsExactlyInAnyOrder("customFlyway"); + }); } @Test void baselineMigrationPrefixIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.baseline-migration-prefix=BL") - .run(validateFlywayTeamsPropertyOnly("baselineMigrationPrefix")); + .withPropertyValues("spring.flyway.baseline-migration-prefix=BL") + .run(validateFlywayTeamsPropertyOnly("baselineMigrationPrefix")); } @Test void scriptPlaceholderPrefixIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.script-placeholder-prefix=SPP") - .run((context) -> assertThat( - context.getBean(Flyway.class).getConfiguration().getScriptPlaceholderPrefix()) - .isEqualTo("SPP")); + .withPropertyValues("spring.flyway.script-placeholder-prefix=SPP") + .run((context) -> assertThat(context.getBean(Flyway.class).getConfiguration().getScriptPlaceholderPrefix()) + .isEqualTo("SPP")); } @Test void scriptPlaceholderSuffixIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.script-placeholder-suffix=SPS") - .run((context) -> assertThat( - context.getBean(Flyway.class).getConfiguration().getScriptPlaceholderSuffix()) - .isEqualTo("SPS")); + .withPropertyValues("spring.flyway.script-placeholder-suffix=SPS") + .run((context) -> assertThat(context.getBean(Flyway.class).getConfiguration().getScriptPlaceholderSuffix()) + .isEqualTo("SPS")); } private ContextConsumer validateFlywayTeamsPropertyOnly(String propertyName) { @@ -777,7 +788,8 @@ class FlywayAutoConfigurationTests { properties.put("configured", "manually"); properties.put("hibernate.transaction.jta.platform", NoJtaPlatform.INSTANCE); return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), properties, null) - .dataSource(dataSource).build(); + .dataSource(dataSource) + .build(); } } @@ -802,7 +814,8 @@ class FlywayAutoConfigurationTests { properties.put("configured", "manually"); properties.put("hibernate.transaction.jta.platform", NoJtaPlatform.INSTANCE); return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), properties, null) - .dataSource(this.dataSource).build(); + .dataSource(this.dataSource) + .build(); } } @@ -931,7 +944,8 @@ class FlywayAutoConfigurationTests { @Bean(destroyMethod = "shutdown") EmbeddedDatabase dataSource(DataSourceProperties properties) throws SQLException { EmbeddedDatabase database = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) - .setName(getDatabaseName(properties)).build(); + .setName(getDatabaseName(properties)) + .build(); insertUser(database); return database; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayPropertiesTests.java index 996be24636..037c4b70b9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,7 @@ class FlywayPropertiesTests { Configuration configuration = new FluentConfiguration(); assertThat(configuration.isFailOnMissingLocations()).isEqualTo(properties.isFailOnMissingLocations()); assertThat(properties.getLocations().stream().map(Location::new).toArray(Location[]::new)) - .isEqualTo(configuration.getLocations()); + .isEqualTo(configuration.getLocations()); assertThat(properties.getEncoding()).isEqualTo(configuration.getEncoding()); assertThat(properties.getConnectRetries()).isEqualTo(configuration.getConnectRetries()); // Can't assert connect retries interval as it is new in Flyway 7.15 @@ -66,7 +66,7 @@ class FlywayPropertiesTests { assertThat(properties.getTable()).isEqualTo(configuration.getTable()); assertThat(properties.getBaselineDescription()).isEqualTo(configuration.getBaselineDescription()); assertThat(MigrationVersion.fromVersion(properties.getBaselineVersion())) - .isEqualTo(configuration.getBaselineVersion()); + .isEqualTo(configuration.getBaselineVersion()); assertThat(properties.getInstalledBy()).isEqualTo(configuration.getInstalledBy()); assertThat(properties.getPlaceholders()).isEqualTo(configuration.getPlaceholders()); assertThat(properties.getPlaceholderPrefix()).isEqualToIgnoringWhitespace(configuration.getPlaceholderPrefix()); @@ -74,10 +74,10 @@ class FlywayPropertiesTests { assertThat(properties.isPlaceholderReplacement()).isEqualTo(configuration.isPlaceholderReplacement()); assertThat(properties.getSqlMigrationPrefix()).isEqualTo(configuration.getSqlMigrationPrefix()); assertThat(properties.getSqlMigrationSuffixes()) - .isEqualTo(Arrays.asList(configuration.getSqlMigrationSuffixes())); + .isEqualTo(Arrays.asList(configuration.getSqlMigrationSuffixes())); assertThat(properties.getSqlMigrationSeparator()).isEqualTo(properties.getSqlMigrationSeparator()); assertThat(properties.getRepeatableSqlMigrationPrefix()) - .isEqualTo(properties.getRepeatableSqlMigrationPrefix()); + .isEqualTo(properties.getRepeatableSqlMigrationPrefix()); assertThat(properties.getTarget()).isNull(); assertThat(configuration.getTarget()).isNull(); assertThat(configuration.getInitSql()).isNull(); @@ -140,7 +140,7 @@ class FlywayPropertiesTests { private void ignoreProperties(Map index, String... propertyNames) { for (String propertyName : propertyNames) { assertThat(index.remove(propertyName)).describedAs("Property to ignore should be present " + propertyName) - .isNotNull(); + .isNotNull(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationReactiveIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationReactiveIntegrationTests.java index 108ad43859..3a47775541 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationReactiveIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ import static org.assertj.core.api.Assertions.assertThat; class FreeMarkerAutoConfigurationReactiveIntegrationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(FreeMarkerAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(FreeMarkerAutoConfiguration.class)); @Test void defaultConfiguration() { @@ -87,20 +87,20 @@ class FreeMarkerAutoConfigurationReactiveIntegrationTests { @Test void customTemplateLoaderPath() { this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:classpath:/custom-templates/") - .run((context) -> { - MockServerWebExchange exchange = render(context, "custom"); - String result = exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(30)); - assertThat(result).contains("custom"); - }); + .run((context) -> { + MockServerWebExchange exchange = render(context, "custom"); + String result = exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(30)); + assertThat(result).contains("custom"); + }); } @SuppressWarnings("deprecation") @Test void customFreeMarkerSettings() { this.contextRunner.withPropertyValues("spring.freemarker.settings.boolean_format:yup,nope") - .run((context) -> assertThat( - context.getBean(FreeMarkerConfigurer.class).getConfiguration().getSetting("boolean_format")) - .isEqualTo("yup,nope")); + .run((context) -> assertThat( + context.getBean(FreeMarkerConfigurer.class).getConfiguration().getSetting("boolean_format")) + .isEqualTo("yup,nope")); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationServletIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationServletIntegrationTests.java index e9f6b21f18..08a2a55cd8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationServletIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationServletIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -135,7 +135,7 @@ class FreeMarkerAutoConfigurationServletIntegrationTests { void customFreeMarkerSettings() { load("spring.freemarker.settings.boolean_format:yup,nope"); assertThat(this.context.getBean(FreeMarkerConfigurer.class).getConfiguration().getSetting("boolean_format")) - .isEqualTo("yup,nope"); + .isEqualTo("yup,nope"); } @Test @@ -169,8 +169,11 @@ class FreeMarkerAutoConfigurationServletIntegrationTests { load(FilterRegistrationOtherConfiguration.class, "spring.web.resources.chain.enabled:true"); Map beans = this.context.getBeansOfType(FilterRegistrationBean.class); assertThat(beans).hasSize(2); - FilterRegistrationBean registration = beans.values().stream() - .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter).findFirst().get(); + FilterRegistrationBean registration = beans.values() + .stream() + .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter) + .findFirst() + .get(); assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR)); } @@ -182,8 +185,11 @@ class FreeMarkerAutoConfigurationServletIntegrationTests { load(FilterRegistrationResourceConfiguration.class, "spring.web.resources.chain.enabled:true"); Map beans = this.context.getBeansOfType(FilterRegistrationBean.class); assertThat(beans).hasSize(1); - FilterRegistrationBean registration = beans.values().stream() - .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter).findFirst().get(); + FilterRegistrationBean registration = beans.values() + .stream() + .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter) + .findFirst() + .get(); assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", EnumSet.of(DispatcherType.INCLUDE)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java index 6b60297a2b..77658ef5fb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class FreeMarkerAutoConfigurationTests { private final BuildOutput buildOutput = new BuildOutput(getClass()); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(FreeMarkerAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(FreeMarkerAutoConfiguration.class)); @Test void renderNonWebAppTemplate() { @@ -57,9 +57,9 @@ class FreeMarkerAutoConfigurationTests { @Test void nonExistentTemplateLocation(CapturedOutput output) { this.contextRunner - .withPropertyValues("spring.freemarker.templateLoaderPath:" - + "classpath:/does-not-exist/,classpath:/also-does-not-exist") - .run((context) -> assertThat(output).contains("Cannot find template location")); + .withPropertyValues("spring.freemarker.templateLoaderPath:" + + "classpath:/does-not-exist/,classpath:/also-does-not-exist") + .run((context) -> assertThat(output).contains("Cannot find template location")); } @Test @@ -67,17 +67,17 @@ class FreeMarkerAutoConfigurationTests { File emptyDirectory = new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory"); emptyDirectory.mkdirs(); this.contextRunner - .withPropertyValues("spring.freemarker.templateLoaderPath:classpath:/empty-templates/empty-directory/") - .run((context) -> assertThat(output).doesNotContain("Cannot find template location")); + .withPropertyValues("spring.freemarker.templateLoaderPath:classpath:/empty-templates/empty-directory/") + .run((context) -> assertThat(output).doesNotContain("Cannot find template location")); } @Test void nonExistentLocationAndEmptyLocation(CapturedOutput output) { new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs(); this.contextRunner - .withPropertyValues("spring.freemarker.templateLoaderPath:" - + "classpath:/does-not-exist/,classpath:/empty-templates/empty-directory/") - .run((context) -> assertThat(output).doesNotContain("Cannot find template location")); + .withPropertyValues("spring.freemarker.templateLoaderPath:" + + "classpath:/does-not-exist/,classpath:/empty-templates/empty-directory/") + .run((context) -> assertThat(output).doesNotContain("Cannot find template location")); } public static class DataModel { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java index 5a6796888b..897c888f62 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,41 +41,47 @@ class FreeMarkerTemplateAvailabilityProviderTests { @Test void availabilityOfTemplateInDefaultLocation() { assertThat(this.provider.isTemplateAvailable("home", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateThatDoesNotExist() { assertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isFalse(); + this.resourceLoader)) + .isFalse(); } @Test void availabilityOfTemplateWithCustomLoaderPath() { this.environment.setProperty("spring.freemarker.template-loader-path", "classpath:/custom-templates/"); assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateWithCustomLoaderPathConfiguredAsAList() { this.environment.setProperty("spring.freemarker.template-loader-path[0]", "classpath:/custom-templates/"); assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.freemarker.prefix", "prefix/"); assertThat(this.provider.isTemplateAvailable("prefixed", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.freemarker.suffix", ".freemarker"); assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/DefaultGraphQlSchemaConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/DefaultGraphQlSchemaConditionTests.java index cd8391f723..7e54b9a1e9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/DefaultGraphQlSchemaConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/DefaultGraphQlSchemaConditionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,30 +42,32 @@ class DefaultGraphQlSchemaConditionTests { this.contextRunner.withUserConfiguration(TestingConfiguration.class).run((context) -> { didMatch(context); assertThat(conditionReportMessage(context)).contains("@ConditionalOnGraphQlSchema found schemas") - .contains("@ConditionalOnGraphQlSchema did not find GraphQlSourceBuilderCustomizer"); + .contains("@ConditionalOnGraphQlSchema did not find GraphQlSourceBuilderCustomizer"); }); } @Test void matchesWhenCustomizerIsDetected() { this.contextRunner.withUserConfiguration(CustomCustomizerConfiguration.class, TestingConfiguration.class) - .withPropertyValues("spring.graphql.schema.locations=classpath:graphql/missing").run((context) -> { - didMatch(context); - assertThat(conditionReportMessage(context)).contains( - "@ConditionalOnGraphQlSchema did not find schema files in locations 'classpath:graphql/missing/'") - .contains("@ConditionalOnGraphQlSchema found customizer myBuilderCuystomizer"); - }); + .withPropertyValues("spring.graphql.schema.locations=classpath:graphql/missing") + .run((context) -> { + didMatch(context); + assertThat(conditionReportMessage(context)).contains( + "@ConditionalOnGraphQlSchema did not find schema files in locations 'classpath:graphql/missing/'") + .contains("@ConditionalOnGraphQlSchema found customizer myBuilderCuystomizer"); + }); } @Test void doesNotMatchWhenBothAreMissing() { this.contextRunner.withUserConfiguration(TestingConfiguration.class) - .withPropertyValues("spring.graphql.schema.locations=classpath:graphql/missing").run((context) -> { - assertThat(context).doesNotHaveBean("success"); - assertThat(conditionReportMessage(context)).contains( - "@ConditionalOnGraphQlSchema did not find schema files in locations 'classpath:graphql/missing/'") - .contains("@ConditionalOnGraphQlSchema did not find GraphQlSourceBuilderCustomizer"); - }); + .withPropertyValues("spring.graphql.schema.locations=classpath:graphql/missing") + .run((context) -> { + assertThat(context).doesNotHaveBean("success"); + assertThat(conditionReportMessage(context)).contains( + "@ConditionalOnGraphQlSchema did not find schema files in locations 'classpath:graphql/missing/'") + .contains("@ConditionalOnGraphQlSchema did not find GraphQlSourceBuilderCustomizer"); + }); } private void didMatch(AssertableApplicationContext context) { @@ -75,7 +77,9 @@ class DefaultGraphQlSchemaConditionTests { private String conditionReportMessage(AssertableApplicationContext context) { Collection conditionAndOutcomes = ConditionEvaluationReport - .get(context.getSourceApplicationContext().getBeanFactory()).getConditionAndOutcomesBySource().values(); + .get(context.getSourceApplicationContext().getBeanFactory()) + .getConditionAndOutcomesBySource() + .values(); return conditionAndOutcomes.iterator().next().iterator().next().getOutcome().getMessage(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/GraphQlAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/GraphQlAutoConfigurationTests.java index 662d442934..7628be5da3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/GraphQlAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/GraphQlAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,7 @@ import static org.mockito.Mockito.mock; class GraphQlAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(GraphQlAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(GraphQlAutoConfiguration.class)); @Test void shouldContributeDefaultBeans() { @@ -76,7 +76,7 @@ class GraphQlAutoConfigurationTests { @Test void shouldBackoffWhenSchemaFileIsMissing() { this.contextRunner.withPropertyValues("spring.graphql.schema.locations:classpath:missing/") - .run((context) -> assertThat(context).hasNotFailed().doesNotHaveBean(GraphQlSource.class)); + .run((context) -> assertThat(context).hasNotFailed().doesNotHaveBean(GraphQlSource.class)); } @Test @@ -90,13 +90,13 @@ class GraphQlAutoConfigurationTests { @Test void shouldScanLocationsWithCustomExtension() { this.contextRunner.withPropertyValues("spring.graphql.schema.file-extensions:.graphqls,.custom") - .run((context) -> { - assertThat(context).hasSingleBean(GraphQlSource.class); - GraphQlSource graphQlSource = context.getBean(GraphQlSource.class); - GraphQLSchema schema = graphQlSource.schema(); - assertThat(schema.getObjectType("Book")).isNotNull(); - assertThat(schema.getObjectType("Person")).isNotNull(); - }); + .run((context) -> { + assertThat(context).hasSingleBean(GraphQlSource.class); + GraphQlSource graphQlSource = context.getBean(GraphQlSource.class); + GraphQLSchema schema = graphQlSource.schema(); + assertThat(schema.getObjectType("Book")).isNotNull(); + assertThat(schema.getObjectType("Person")).isNotNull(); + }); } @Test @@ -113,8 +113,8 @@ class GraphQlAutoConfigurationTests { GraphQlSource graphQlSource = context.getBean(GraphQlSource.class); GraphQL graphQL = graphQlSource.graphQl(); assertThat(graphQL.getQueryStrategy()).extracting("dataFetcherExceptionHandler") - .satisfies((exceptionHandler) -> assertThat(exceptionHandler.getClass().getName()) - .endsWith("ExceptionResolversExceptionHandler")); + .satisfies((exceptionHandler) -> assertThat(exceptionHandler.getClass().getName()) + .endsWith("ExceptionResolversExceptionHandler")); }); } @@ -124,9 +124,10 @@ class GraphQlAutoConfigurationTests { GraphQlSource graphQlSource = context.getBean(GraphQlSource.class); Instrumentation customInstrumentation = context.getBean("customInstrumentation", Instrumentation.class); GraphQL graphQL = graphQlSource.graphQl(); - assertThat(graphQL).extracting("instrumentation").isInstanceOf(ChainedInstrumentation.class) - .extracting("instrumentations", InstanceOfAssertFactories.iterable(Instrumentation.class)) - .contains(customInstrumentation); + assertThat(graphQL).extracting("instrumentation") + .isInstanceOf(ChainedInstrumentation.class) + .extracting("instrumentations", InstanceOfAssertFactories.iterable(Instrumentation.class)) + .contains(customInstrumentation); }); } @@ -134,7 +135,7 @@ class GraphQlAutoConfigurationTests { void shouldApplyRuntimeWiringConfigurers() { this.contextRunner.withUserConfiguration(RuntimeWiringConfigurerConfiguration.class).run((context) -> { RuntimeWiringConfigurerConfiguration.CustomRuntimeWiringConfigurer configurer = context - .getBean(RuntimeWiringConfigurerConfiguration.CustomRuntimeWiringConfigurer.class); + .getBean(RuntimeWiringConfigurerConfiguration.CustomRuntimeWiringConfigurer.class); assertThat(configurer.applied).isTrue(); }); } @@ -143,7 +144,7 @@ class GraphQlAutoConfigurationTests { void shouldApplyGraphQlSourceBuilderCustomizer() { this.contextRunner.withUserConfiguration(GraphQlSourceBuilderCustomizerConfiguration.class).run((context) -> { GraphQlSourceBuilderCustomizerConfiguration.CustomGraphQlSourceBuilderCustomizer customizer = context - .getBean(GraphQlSourceBuilderCustomizerConfiguration.CustomGraphQlSourceBuilderCustomizer.class); + .getBean(GraphQlSourceBuilderCustomizerConfiguration.CustomGraphQlSourceBuilderCustomizer.class); assertThat(customizer.applied).isTrue(); }); } @@ -163,23 +164,22 @@ class GraphQlAutoConfigurationTests { GraphQlSource graphQlSource = context.getBean(GraphQlSource.class); GraphQLSchema schema = graphQlSource.schema(); assertThat(schema.getCodeRegistry().getFieldVisibility()) - .isInstanceOf(NoIntrospectionGraphqlFieldVisibility.class); + .isInstanceOf(NoIntrospectionGraphqlFieldVisibility.class); }); } @Test void shouldConfigureCustomBatchLoaderRegistry() { this.contextRunner - .withBean("customBatchLoaderRegistry", BatchLoaderRegistry.class, () -> mock(BatchLoaderRegistry.class)) - .run((context) -> { - assertThat(context).hasSingleBean(BatchLoaderRegistry.class); - assertThat(context.getBean("customBatchLoaderRegistry")) - .isSameAs(context.getBean(BatchLoaderRegistry.class)); - assertThat(context.getBean(ExecutionGraphQlService.class)) - .extracting("dataLoaderRegistrars", - InstanceOfAssertFactories.list(DataLoaderRegistrar.class)) - .containsOnly(context.getBean(BatchLoaderRegistry.class)); - }); + .withBean("customBatchLoaderRegistry", BatchLoaderRegistry.class, () -> mock(BatchLoaderRegistry.class)) + .run((context) -> { + assertThat(context).hasSingleBean(BatchLoaderRegistry.class); + assertThat(context.getBean("customBatchLoaderRegistry")) + .isSameAs(context.getBean(BatchLoaderRegistry.class)); + assertThat(context.getBean(ExecutionGraphQlService.class)) + .extracting("dataLoaderRegistrars", InstanceOfAssertFactories.list(DataLoaderRegistrar.class)) + .containsOnly(context.getBean(BatchLoaderRegistry.class)); + }); } @Configuration(proxyBeanMethods = false) @@ -187,9 +187,9 @@ class GraphQlAutoConfigurationTests { @Bean GraphQlSource.SchemaResourceBuilder customGraphQlSourceBuilder() { - return GraphQlSource.schemaResourceBuilder().schemaResources( - new ClassPathResource("graphql/schema.graphqls"), - new ClassPathResource("graphql/types/book.graphqls")); + return GraphQlSource.schemaResourceBuilder() + .schemaResources(new ClassPathResource("graphql/schema.graphqls"), + new ClassPathResource("graphql/types/book.graphqls")); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlQueryByExampleAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlQueryByExampleAutoConfigurationTests.java index a8c4c1d6f8..0998bfe10a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlQueryByExampleAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlQueryByExampleAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,18 +46,21 @@ class GraphQlQueryByExampleAutoConfigurationTests { private static final Book book = new Book("42", "Test title", 42, "Test Author"); private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(GraphQlAutoConfiguration.class, GraphQlQueryByExampleAutoConfiguration.class)) - .withUserConfiguration(MockRepositoryConfig.class) - .withPropertyValues("spring.main.web-application-type=reactive"); + .withConfiguration( + AutoConfigurations.of(GraphQlAutoConfiguration.class, GraphQlQueryByExampleAutoConfiguration.class)) + .withUserConfiguration(MockRepositoryConfig.class) + .withPropertyValues("spring.main.web-application-type=reactive"); @Test void shouldRegisterDataFetcherForQueryByExampleRepositories() { this.contextRunner.run((context) -> { ExecutionGraphQlService graphQlService = context.getBean(ExecutionGraphQlService.class); ExecutionGraphQlServiceTester graphQlTester = ExecutionGraphQlServiceTester.create(graphQlService); - graphQlTester.document("{ bookById(id: 1) {name}}").execute().path("bookById.name").entity(String.class) - .isEqualTo("Test title"); + graphQlTester.document("{ bookById(id: 1) {name}}") + .execute() + .path("bookById.name") + .entity(String.class) + .isEqualTo("Test title"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlQuerydslAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlQuerydslAutoConfigurationTests.java index 27e4b5cb0a..3bbb3df8a0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlQuerydslAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlQuerydslAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,18 +47,21 @@ class GraphQlQuerydslAutoConfigurationTests { private static final Book book = new Book("42", "Test title", 42, "Test Author"); private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(GraphQlAutoConfiguration.class, GraphQlQuerydslAutoConfiguration.class)) - .withUserConfiguration(MockRepositoryConfig.class) - .withPropertyValues("spring.main.web-application-type=reactive"); + .withConfiguration( + AutoConfigurations.of(GraphQlAutoConfiguration.class, GraphQlQuerydslAutoConfiguration.class)) + .withUserConfiguration(MockRepositoryConfig.class) + .withPropertyValues("spring.main.web-application-type=reactive"); @Test void shouldRegisterDataFetcherForQueryDslRepositories() { this.contextRunner.run((context) -> { ExecutionGraphQlService graphQlService = context.getBean(ExecutionGraphQlService.class); GraphQlTester graphQlTester = ExecutionGraphQlServiceTester.create(graphQlService); - graphQlTester.document("{ bookById(id: 1) {name}}").execute().path("bookById.name").entity(String.class) - .isEqualTo("Test title"); + graphQlTester.document("{ bookById(id: 1) {name}}") + .execute() + .path("bookById.name") + .entity(String.class) + .isEqualTo("Test title"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlReactiveQueryByExampleAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlReactiveQueryByExampleAutoConfigurationTests.java index 48c9be1cab..8f4a94a410 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlReactiveQueryByExampleAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlReactiveQueryByExampleAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,18 +46,21 @@ class GraphQlReactiveQueryByExampleAutoConfigurationTests { private static final Mono bookPublisher = Mono.just(new Book("42", "Test title", 42, "Test Author")); private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(GraphQlAutoConfiguration.class, - GraphQlReactiveQueryByExampleAutoConfiguration.class)) - .withUserConfiguration(MockRepositoryConfig.class) - .withPropertyValues("spring.main.web-application-type=reactive"); + .withConfiguration(AutoConfigurations.of(GraphQlAutoConfiguration.class, + GraphQlReactiveQueryByExampleAutoConfiguration.class)) + .withUserConfiguration(MockRepositoryConfig.class) + .withPropertyValues("spring.main.web-application-type=reactive"); @Test void shouldRegisterDataFetcherForQueryByExampleRepositories() { this.contextRunner.run((context) -> { ExecutionGraphQlService graphQlService = context.getBean(ExecutionGraphQlService.class); GraphQlTester graphQlTester = ExecutionGraphQlServiceTester.create(graphQlService); - graphQlTester.document("{ bookById(id: 1) {name}}").execute().path("bookById.name").entity(String.class) - .isEqualTo("Test title"); + graphQlTester.document("{ bookById(id: 1) {name}}") + .execute() + .path("bookById.name") + .entity(String.class) + .isEqualTo("Test title"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlReactiveQuerydslAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlReactiveQuerydslAutoConfigurationTests.java index d2a33df2fc..9901d096cb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlReactiveQuerydslAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlReactiveQuerydslAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,18 +46,21 @@ class GraphQlReactiveQuerydslAutoConfigurationTests { private static final Mono bookPublisher = Mono.just(new Book("42", "Test title", 42, "Test Author")); private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(GraphQlAutoConfiguration.class, - GraphQlReactiveQuerydslAutoConfiguration.class)) - .withUserConfiguration(MockRepositoryConfig.class) - .withPropertyValues("spring.main.web-application-type=reactive"); + .withConfiguration( + AutoConfigurations.of(GraphQlAutoConfiguration.class, GraphQlReactiveQuerydslAutoConfiguration.class)) + .withUserConfiguration(MockRepositoryConfig.class) + .withPropertyValues("spring.main.web-application-type=reactive"); @Test void shouldRegisterDataFetcherForQueryDslRepositories() { this.contextRunner.run((context) -> { ExecutionGraphQlService graphQlService = context.getBean(ExecutionGraphQlService.class); GraphQlTester graphQlTester = ExecutionGraphQlServiceTester.create(graphQlService); - graphQlTester.document("{ bookById(id: 1) {name}}").execute().path("bookById.name").entity(String.class) - .isEqualTo("Test title"); + graphQlTester.document("{ bookById(id: 1) {name}}") + .execute() + .path("bookById.name") + .entity(String.class) + .isEqualTo("Test title"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/reactive/GraphQlWebFluxAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/reactive/GraphQlWebFluxAutoConfigurationTests.java index 0f06e12a99..f191cafd9d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/reactive/GraphQlWebFluxAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/reactive/GraphQlWebFluxAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,28 +58,36 @@ class GraphQlWebFluxAutoConfigurationTests { private static final String BASE_URL = "https://spring.example.org/"; private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, - CodecsAutoConfiguration.class, JacksonAutoConfiguration.class, GraphQlAutoConfiguration.class, - GraphQlWebFluxAutoConfiguration.class)) - .withUserConfiguration(DataFetchersConfiguration.class, CustomWebInterceptor.class) - .withPropertyValues("spring.main.web-application-type=reactive", "spring.graphql.graphiql.enabled=true", - "spring.graphql.schema.printer.enabled=true", - "spring.graphql.cors.allowed-origins=https://example.com", - "spring.graphql.cors.allowed-methods=POST", "spring.graphql.cors.allow-credentials=true"); + .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, + CodecsAutoConfiguration.class, JacksonAutoConfiguration.class, GraphQlAutoConfiguration.class, + GraphQlWebFluxAutoConfiguration.class)) + .withUserConfiguration(DataFetchersConfiguration.class, CustomWebInterceptor.class) + .withPropertyValues("spring.main.web-application-type=reactive", "spring.graphql.graphiql.enabled=true", + "spring.graphql.schema.printer.enabled=true", "spring.graphql.cors.allowed-origins=https://example.com", + "spring.graphql.cors.allowed-methods=POST", "spring.graphql.cors.allow-credentials=true"); @Test void shouldContributeDefaultBeans() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(GraphQlHttpHandler.class) - .hasSingleBean(WebGraphQlHandler.class).doesNotHaveBean(GraphQlWebSocketHandler.class)); + .hasSingleBean(WebGraphQlHandler.class) + .doesNotHaveBean(GraphQlWebSocketHandler.class)); } @Test void simpleQueryShouldWork() { testWithWebClient((client) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author } }"; - client.post().uri("/graphql").bodyValue("{ \"query\": \"" + query + "\"}").exchange().expectStatus().isOk() - .expectHeader().contentType("application/json").expectBody().jsonPath("data.bookById.name") - .isEqualTo("GraphQL for beginners"); + client.post() + .uri("/graphql") + .bodyValue("{ \"query\": \"" + query + "\"}") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType("application/json") + .expectBody() + .jsonPath("data.bookById.name") + .isEqualTo("GraphQL for beginners"); }); } @@ -87,8 +95,13 @@ class GraphQlWebFluxAutoConfigurationTests { void httpGetQueryShouldBeSupported() { testWithWebClient((client) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author } }"; - client.get().uri("/graphql?query={query}", "{ \"query\": \"" + query + "\"}").exchange().expectStatus() - .isEqualTo(HttpStatus.METHOD_NOT_ALLOWED).expectHeader().valueEquals("Allow", "POST"); + client.get() + .uri("/graphql?query={query}", "{ \"query\": \"" + query + "\"}") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.METHOD_NOT_ALLOWED) + .expectHeader() + .valueEquals("Allow", "POST"); }); } @@ -109,25 +122,49 @@ class GraphQlWebFluxAutoConfigurationTests { testWithWebClient((client) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author } }"; - client.post().uri("/graphql").bodyValue("{ \"query\": \"" + query + "\"}").exchange().expectStatus().isOk() - .expectHeader().valueEquals("X-Custom-Header", "42"); + client.post() + .uri("/graphql") + .bodyValue("{ \"query\": \"" + query + "\"}") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueEquals("X-Custom-Header", "42"); }); } @Test void shouldExposeSchemaEndpoint() { - testWithWebClient((client) -> client.get().uri("/graphql/schema").accept(MediaType.ALL).exchange() - .expectStatus().isOk().expectHeader().contentType(MediaType.TEXT_PLAIN).expectBody(String.class) - .value(containsString("type Book"))); + testWithWebClient((client) -> client.get() + .uri("/graphql/schema") + .accept(MediaType.ALL) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.TEXT_PLAIN) + .expectBody(String.class) + .value(containsString("type Book"))); } @Test void shouldExposeGraphiqlEndpoint() { testWithWebClient((client) -> { - client.get().uri("/graphiql").exchange().expectStatus().is3xxRedirection().expectHeader() - .location("https://spring.example.org/graphiql?path=/graphql"); - client.get().uri("/graphiql?path=/graphql").accept(MediaType.ALL).exchange().expectStatus().isOk() - .expectHeader().contentType(MediaType.TEXT_HTML); + client.get() + .uri("/graphiql") + .exchange() + .expectStatus() + .is3xxRedirection() + .expectHeader() + .location("https://spring.example.org/graphiql?path=/graphql"); + client.get() + .uri("/graphiql?path=/graphql") + .accept(MediaType.ALL) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.TEXT_HTML); }); } @@ -136,18 +173,25 @@ class GraphQlWebFluxAutoConfigurationTests { testWithWebClient((client) -> { String query = "{" + " bookById(id: \\\"book-1\\\"){ " + " id" + " name" + " pageCount" + " author" + " }" + "}"; - client.post().uri("/graphql").bodyValue("{ \"query\": \"" + query + "\"}") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST") - .header(HttpHeaders.ORIGIN, "https://example.com").exchange().expectStatus().isOk().expectHeader() - .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "https://example.com").expectHeader() - .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); + client.post() + .uri("/graphql") + .bodyValue("{ \"query\": \"" + query + "\"}") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST") + .header(HttpHeaders.ORIGIN, "https://example.com") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "https://example.com") + .expectHeader() + .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); }); } @Test void shouldConfigureWebSocketBeans() { this.contextRunner.withPropertyValues("spring.graphql.websocket.path=/ws") - .run((context) -> assertThat(context).hasSingleBean(GraphQlWebSocketHandler.class)); + .run((context) -> assertThat(context).hasSingleBean(GraphQlWebSocketHandler.class)); } @Test @@ -163,11 +207,14 @@ class GraphQlWebFluxAutoConfigurationTests { private void testWithWebClient(Consumer consumer) { this.contextRunner.run((context) -> { - WebTestClient client = WebTestClient.bindToApplicationContext(context).configureClient() - .defaultHeaders((headers) -> { - headers.setContentType(MediaType.APPLICATION_JSON); - headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); - }).baseUrl(BASE_URL).build(); + WebTestClient client = WebTestClient.bindToApplicationContext(context) + .configureClient() + .defaultHeaders((headers) -> { + headers.setContentType(MediaType.APPLICATION_JSON); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + }) + .baseUrl(BASE_URL) + .build(); consumer.accept(client); }); } @@ -177,8 +224,8 @@ class GraphQlWebFluxAutoConfigurationTests { @Bean RuntimeWiringConfigurer bookDataFetcher() { - return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query").dataFetcher("bookById", - GraphQlTestDataFetchers.getBookByIdDataFetcher())); + return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query") + .dataFetcher("bookById", GraphQlTestDataFetchers.getBookByIdDataFetcher())); } } @@ -189,7 +236,7 @@ class GraphQlWebFluxAutoConfigurationTests { @Bean WebGraphQlInterceptor customWebGraphQlInterceptor() { return (webInput, interceptorChain) -> interceptorChain.next(webInput) - .doOnNext((output) -> output.getResponseHeaders().add("X-Custom-Header", "42")); + .doOnNext((output) -> output.getResponseHeaders().add("X-Custom-Header", "42")); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/rsocket/GraphQlRSocketAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/rsocket/GraphQlRSocketAutoConfigurationTests.java index 827a47e495..69f664ef0e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/rsocket/GraphQlRSocketAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/rsocket/GraphQlRSocketAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,17 +56,17 @@ import static org.assertj.core.api.Assertions.assertThat; class GraphQlRSocketAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(JacksonAutoConfiguration.class, RSocketStrategiesAutoConfiguration.class, - RSocketMessagingAutoConfiguration.class, RSocketServerAutoConfiguration.class, - GraphQlAutoConfiguration.class, GraphQlRSocketAutoConfiguration.class)) - .withUserConfiguration(DataFetchersConfiguration.class) - .withPropertyValues("spring.main.web-application-type=reactive", "spring.graphql.rsocket.mapping=graphql"); + .withConfiguration( + AutoConfigurations.of(JacksonAutoConfiguration.class, RSocketStrategiesAutoConfiguration.class, + RSocketMessagingAutoConfiguration.class, RSocketServerAutoConfiguration.class, + GraphQlAutoConfiguration.class, GraphQlRSocketAutoConfiguration.class)) + .withUserConfiguration(DataFetchersConfiguration.class) + .withPropertyValues("spring.main.web-application-type=reactive", "spring.graphql.rsocket.mapping=graphql"); @Test void shouldContributeDefaultBeans() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(GraphQlRSocketHandler.class) - .hasSingleBean(GraphQlRSocketController.class)); + .hasSingleBean(GraphQlRSocketController.class)); } @Test @@ -81,45 +81,52 @@ class GraphQlRSocketAutoConfigurationTests { private void assertThatSimpleQueryWorks(RSocketGraphQlClient client) { String document = "{ bookById(id: \"book-1\"){ id name pageCount author } }"; - String bookName = client.document(document).retrieve("bookById.name").toEntity(String.class) - .block(Duration.ofSeconds(5)); + String bookName = client.document(document) + .retrieve("bookById.name") + .toEntity(String.class) + .block(Duration.ofSeconds(5)); assertThat(bookName).isEqualTo("GraphQL for beginners"); } private void testWithRSocketTcp(Consumer consumer) { ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(JacksonAutoConfiguration.class, RSocketStrategiesAutoConfiguration.class, - RSocketMessagingAutoConfiguration.class, RSocketServerAutoConfiguration.class, - GraphQlAutoConfiguration.class, GraphQlRSocketAutoConfiguration.class)) - .withUserConfiguration(DataFetchersConfiguration.class).withPropertyValues( - "spring.main.web-application-type=reactive", "spring.graphql.rsocket.mapping=graphql"); + .withConfiguration( + AutoConfigurations.of(JacksonAutoConfiguration.class, RSocketStrategiesAutoConfiguration.class, + RSocketMessagingAutoConfiguration.class, RSocketServerAutoConfiguration.class, + GraphQlAutoConfiguration.class, GraphQlRSocketAutoConfiguration.class)) + .withUserConfiguration(DataFetchersConfiguration.class) + .withPropertyValues("spring.main.web-application-type=reactive", "spring.graphql.rsocket.mapping=graphql"); contextRunner.withInitializer(new RSocketPortInfoApplicationContextInitializer()) - .withPropertyValues("spring.rsocket.server.port=0").run((context) -> { - String serverPort = context.getEnvironment().getProperty("local.rsocket.server.port"); - RSocketGraphQlClient client = RSocketGraphQlClient.builder() - .tcp("localhost", Integer.parseInt(serverPort)).route("graphql").build(); - consumer.accept(client); - }); + .withPropertyValues("spring.rsocket.server.port=0") + .run((context) -> { + String serverPort = context.getEnvironment().getProperty("local.rsocket.server.port"); + RSocketGraphQlClient client = RSocketGraphQlClient.builder() + .tcp("localhost", Integer.parseInt(serverPort)) + .route("graphql") + .build(); + consumer.accept(client); + }); } private void testWithRSocketWebSocket(Consumer consumer) { ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner( - AnnotationConfigReactiveWebServerApplicationContext::new).withConfiguration( - AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, - ErrorWebFluxAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - JacksonAutoConfiguration.class, RSocketStrategiesAutoConfiguration.class, - RSocketMessagingAutoConfiguration.class, RSocketServerAutoConfiguration.class, - GraphQlAutoConfiguration.class, GraphQlRSocketAutoConfiguration.class)) - .withInitializer(new ServerPortInfoApplicationContextInitializer()) - .withUserConfiguration(DataFetchersConfiguration.class, NettyServerConfiguration.class) - .withPropertyValues("spring.main.web-application-type=reactive", "server.port=0", - "spring.graphql.rsocket.mapping=graphql", "spring.rsocket.server.transport=websocket", - "spring.rsocket.server.mapping-path=/rsocket"); + AnnotationConfigReactiveWebServerApplicationContext::new) + .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, + ErrorWebFluxAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + JacksonAutoConfiguration.class, RSocketStrategiesAutoConfiguration.class, + RSocketMessagingAutoConfiguration.class, RSocketServerAutoConfiguration.class, + GraphQlAutoConfiguration.class, GraphQlRSocketAutoConfiguration.class)) + .withInitializer(new ServerPortInfoApplicationContextInitializer()) + .withUserConfiguration(DataFetchersConfiguration.class, NettyServerConfiguration.class) + .withPropertyValues("spring.main.web-application-type=reactive", "server.port=0", + "spring.graphql.rsocket.mapping=graphql", "spring.rsocket.server.transport=websocket", + "spring.rsocket.server.mapping-path=/rsocket"); contextRunner.run((context) -> { String serverPort = context.getEnvironment().getProperty("local.server.port"); RSocketGraphQlClient client = RSocketGraphQlClient.builder() - .webSocket(URI.create("ws://localhost:" + serverPort + "/rsocket")).route("graphql").build(); + .webSocket(URI.create("ws://localhost:" + serverPort + "/rsocket")) + .route("graphql") + .build(); consumer.accept(client); }); } @@ -141,8 +148,8 @@ class GraphQlRSocketAutoConfigurationTests { @Bean RuntimeWiringConfigurer bookDataFetcher() { - return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query").dataFetcher("bookById", - GraphQlTestDataFetchers.getBookByIdDataFetcher())); + return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query") + .dataFetcher("bookById", GraphQlTestDataFetchers.getBookByIdDataFetcher())); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/rsocket/RSocketGraphQlClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/rsocket/RSocketGraphQlClientAutoConfigurationTests.java index f46a2d25d5..e320690455 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/rsocket/RSocketGraphQlClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/rsocket/RSocketGraphQlClientAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,8 @@ class RSocketGraphQlClientAutoConfigurationTests { private static final RSocketGraphQlClient.Builder builderInstance = RSocketGraphQlClient.builder(); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RSocketStrategiesAutoConfiguration.class, - RSocketRequesterAutoConfiguration.class, RSocketGraphQlClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RSocketStrategiesAutoConfiguration.class, + RSocketRequesterAutoConfiguration.class, RSocketGraphQlClientAutoConfiguration.class)); @Test void shouldCreateBuilder() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/security/GraphQlWebFluxSecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/security/GraphQlWebFluxSecurityAutoConfigurationTests.java index 30ded29aed..f388ac3541 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/security/GraphQlWebFluxSecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/security/GraphQlWebFluxSecurityAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2022 the original author or authors. + * Copyright 2020-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,26 +64,34 @@ class GraphQlWebFluxSecurityAutoConfigurationTests { private static final String BASE_URL = "https://spring.example.org/graphql"; private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, - CodecsAutoConfiguration.class, JacksonAutoConfiguration.class, GraphQlAutoConfiguration.class, - GraphQlWebFluxAutoConfiguration.class, GraphQlWebFluxSecurityAutoConfiguration.class, - ReactiveSecurityAutoConfiguration.class)) - .withUserConfiguration(DataFetchersConfiguration.class, SecurityConfig.class) - .withPropertyValues("spring.main.web-application-type=reactive"); + .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, + CodecsAutoConfiguration.class, JacksonAutoConfiguration.class, GraphQlAutoConfiguration.class, + GraphQlWebFluxAutoConfiguration.class, GraphQlWebFluxSecurityAutoConfiguration.class, + ReactiveSecurityAutoConfiguration.class)) + .withUserConfiguration(DataFetchersConfiguration.class, SecurityConfig.class) + .withPropertyValues("spring.main.web-application-type=reactive"); @Test void contributesExceptionResolver() { - this.contextRunner.run( - (context) -> assertThat(context).hasSingleBean(ReactiveSecurityDataFetcherExceptionResolver.class)); + this.contextRunner + .run((context) -> assertThat(context).hasSingleBean(ReactiveSecurityDataFetcherExceptionResolver.class)); } @Test void anonymousUserShouldBeUnauthorized() { testWithWebClient((client) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author }}"; - client.post().uri("").bodyValue("{ \"query\": \"" + query + "\"}").exchange().expectStatus().isOk() - .expectBody().jsonPath("data.bookById.name").doesNotExist() - .jsonPath("errors[0].extensions.classification").isEqualTo(ErrorType.UNAUTHORIZED.toString()); + client.post() + .uri("") + .bodyValue("{ \"query\": \"" + query + "\"}") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("data.bookById.name") + .doesNotExist() + .jsonPath("errors[0].extensions.classification") + .isEqualTo(ErrorType.UNAUTHORIZED.toString()); }); } @@ -91,20 +99,31 @@ class GraphQlWebFluxSecurityAutoConfigurationTests { void authenticatedUserShouldGetData() { testWithWebClient((client) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author }}"; - client.post().uri("").headers((headers) -> headers.setBasicAuth("rob", "rob")) - .bodyValue("{ \"query\": \"" + query + "\"}").exchange().expectStatus().isOk().expectBody() - .jsonPath("data.bookById.name").isEqualTo("GraphQL for beginners") - .jsonPath("errors[0].extensions.classification").doesNotExist(); + client.post() + .uri("") + .headers((headers) -> headers.setBasicAuth("rob", "rob")) + .bodyValue("{ \"query\": \"" + query + "\"}") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("data.bookById.name") + .isEqualTo("GraphQL for beginners") + .jsonPath("errors[0].extensions.classification") + .doesNotExist(); }); } private void testWithWebClient(Consumer consumer) { this.contextRunner.run((context) -> { - WebTestClient client = WebTestClient.bindToApplicationContext(context).configureClient() - .defaultHeaders((headers) -> { - headers.setContentType(MediaType.APPLICATION_JSON); - headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); - }).baseUrl(BASE_URL).build(); + WebTestClient client = WebTestClient.bindToApplicationContext(context) + .configureClient() + .defaultHeaders((headers) -> { + headers.setContentType(MediaType.APPLICATION_JSON); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + }) + .baseUrl(BASE_URL) + .build(); consumer.accept(client); }); } @@ -114,8 +133,8 @@ class GraphQlWebFluxSecurityAutoConfigurationTests { @Bean RuntimeWiringConfigurer bookDataFetcher(BookService bookService) { - return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query").dataFetcher("bookById", - (env) -> bookService.getBookdById(env.getArgument("id")))); + return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query") + .dataFetcher("bookById", (env) -> bookService.getBookdById(env.getArgument("id")))); } @Bean @@ -143,10 +162,11 @@ class GraphQlWebFluxSecurityAutoConfigurationTests { @Bean SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) { return http.csrf((spec) -> spec.disable()) - // Demonstrate that method security works - // Best practice to use both for defense in depth - .authorizeExchange((requests) -> requests.anyExchange().permitAll()).httpBasic(withDefaults()) - .build(); + // Demonstrate that method security works + // Best practice to use both for defense in depth + .authorizeExchange((requests) -> requests.anyExchange().permitAll()) + .httpBasic(withDefaults()) + .build(); } @Bean diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/security/GraphQlWebMvcSecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/security/GraphQlWebMvcSecurityAutoConfigurationTests.java index fa33b55439..10d2db27fa 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/security/GraphQlWebMvcSecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/security/GraphQlWebMvcSecurityAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2022 the original author or authors. + * Copyright 2020-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,13 +68,12 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. class GraphQlWebMvcSecurityAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, JacksonAutoConfiguration.class, - GraphQlAutoConfiguration.class, GraphQlWebMvcAutoConfiguration.class, - GraphQlWebMvcSecurityAutoConfiguration.class, SecurityAutoConfiguration.class)) - .withUserConfiguration(DataFetchersConfiguration.class, SecurityConfig.class) - .withPropertyValues("spring.main.web-application-type=servlet"); + .withConfiguration(AutoConfigurations.of(DispatcherServletAutoConfiguration.class, + WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + JacksonAutoConfiguration.class, GraphQlAutoConfiguration.class, GraphQlWebMvcAutoConfiguration.class, + GraphQlWebMvcSecurityAutoConfiguration.class, SecurityAutoConfiguration.class)) + .withUserConfiguration(DataFetchersConfiguration.class, SecurityConfig.class) + .withPropertyValues("spring.main.web-application-type=servlet"); @Test void contributesSecurityComponents() { @@ -89,10 +88,11 @@ class GraphQlWebMvcSecurityAutoConfigurationTests { testWith((mockMvc) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author }}"; MvcResult result = mockMvc.perform(post("/graphql").content("{\"query\": \"" + query + "\"}")).andReturn(); - mockMvc.perform(asyncDispatch(result)).andExpect(status().isOk()) - .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("data.bookById.name").doesNotExist()).andExpect( - jsonPath("errors[0].extensions.classification").value(ErrorType.UNAUTHORIZED.toString())); + mockMvc.perform(asyncDispatch(result)) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("data.bookById.name").doesNotExist()) + .andExpect(jsonPath("errors[0].extensions.classification").value(ErrorType.UNAUTHORIZED.toString())); }); } @@ -101,11 +101,13 @@ class GraphQlWebMvcSecurityAutoConfigurationTests { testWith((mockMvc) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author }}"; MvcResult result = mockMvc - .perform(post("/graphql").content("{\"query\": \"" + query + "\"}").with(user("rob"))).andReturn(); - mockMvc.perform(asyncDispatch(result)).andExpect(status().isOk()) - .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("data.bookById.name").value("GraphQL for beginners")) - .andExpect(jsonPath("errors").doesNotExist()); + .perform(post("/graphql").content("{\"query\": \"" + query + "\"}").with(user("rob"))) + .andReturn(); + mockMvc.perform(asyncDispatch(result)) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("data.bookById.name").value("GraphQL for beginners")) + .andExpect(jsonPath("errors").doesNotExist()); }); } @@ -114,8 +116,9 @@ class GraphQlWebMvcSecurityAutoConfigurationTests { this.contextRunner.run((context) -> { MediaType mediaType = MediaType.APPLICATION_JSON; MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context) - .defaultRequest(post("/graphql").contentType(mediaType).accept(mediaType)).apply(springSecurity()) - .build(); + .defaultRequest(post("/graphql").contentType(mediaType).accept(mediaType)) + .apply(springSecurity()) + .build(); mockMvcConsumer.accept(mockMvc); }); } @@ -131,8 +134,8 @@ class GraphQlWebMvcSecurityAutoConfigurationTests { @Bean RuntimeWiringConfigurer bookDataFetcher(BookService bookService) { - return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query").dataFetcher("bookById", - (env) -> bookService.getBookdById(env.getArgument("id")))); + return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query") + .dataFetcher("bookById", (env) -> bookService.getBookdById(env.getArgument("id")))); } @Bean @@ -161,10 +164,11 @@ class GraphQlWebMvcSecurityAutoConfigurationTests { @Bean DefaultSecurityFilterChain springWebFilterChain(HttpSecurity http) throws Exception { return http.csrf((c) -> c.disable()) - // Demonstrate that method security works - // Best practice to use both for defense in depth - .authorizeRequests((requests) -> requests.anyRequest().permitAll()).httpBasic(withDefaults()) - .build(); + // Demonstrate that method security works + // Best practice to use both for defense in depth + .authorizeRequests((requests) -> requests.anyRequest().permitAll()) + .httpBasic(withDefaults()) + .build(); } @Bean diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/servlet/GraphQlWebMvcAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/servlet/GraphQlWebMvcAutoConfigurationTests.java index d75f6be455..d975d44052 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/servlet/GraphQlWebMvcAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/servlet/GraphQlWebMvcAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,20 +63,19 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. class GraphQlWebMvcAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, JacksonAutoConfiguration.class, - GraphQlAutoConfiguration.class, GraphQlWebMvcAutoConfiguration.class)) - .withUserConfiguration(DataFetchersConfiguration.class, CustomWebInterceptor.class) - .withPropertyValues("spring.main.web-application-type=servlet", "spring.graphql.graphiql.enabled=true", - "spring.graphql.schema.printer.enabled=true", - "spring.graphql.cors.allowed-origins=https://example.com", - "spring.graphql.cors.allowed-methods=POST", "spring.graphql.cors.allow-credentials=true"); + .withConfiguration(AutoConfigurations.of(DispatcherServletAutoConfiguration.class, + WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + JacksonAutoConfiguration.class, GraphQlAutoConfiguration.class, GraphQlWebMvcAutoConfiguration.class)) + .withUserConfiguration(DataFetchersConfiguration.class, CustomWebInterceptor.class) + .withPropertyValues("spring.main.web-application-type=servlet", "spring.graphql.graphiql.enabled=true", + "spring.graphql.schema.printer.enabled=true", "spring.graphql.cors.allowed-origins=https://example.com", + "spring.graphql.cors.allowed-methods=POST", "spring.graphql.cors.allow-credentials=true"); @Test void shouldContributeDefaultBeans() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(GraphQlHttpHandler.class) - .hasSingleBean(WebGraphQlHandler.class).doesNotHaveBean(GraphQlWebSocketHandler.class)); + .hasSingleBean(WebGraphQlHandler.class) + .doesNotHaveBean(GraphQlWebSocketHandler.class)); } @Test @@ -84,9 +83,10 @@ class GraphQlWebMvcAutoConfigurationTests { testWith((mockMvc) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author } }"; MvcResult result = mockMvc.perform(post("/graphql").content("{\"query\": \"" + query + "\"}")).andReturn(); - mockMvc.perform(asyncDispatch(result)).andExpect(status().isOk()) - .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_GRAPHQL)) - .andExpect(jsonPath("data.bookById.name").value("GraphQL for beginners")); + mockMvc.perform(asyncDispatch(result)) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_GRAPHQL)) + .andExpect(jsonPath("data.bookById.name").value("GraphQL for beginners")); }); } @@ -95,7 +95,8 @@ class GraphQlWebMvcAutoConfigurationTests { testWith((mockMvc) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author } }"; mockMvc.perform(get("/graphql?query={query}", "{\"query\": \"" + query + "\"}")) - .andExpect(status().isMethodNotAllowed()).andExpect(header().string("Allow", "POST")); + .andExpect(status().isMethodNotAllowed()) + .andExpect(header().string("Allow", "POST")); }); } @@ -114,25 +115,29 @@ class GraphQlWebMvcAutoConfigurationTests { testWith((mockMvc) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author } }"; MvcResult result = mockMvc.perform(post("/graphql").content("{\"query\": \"" + query + "\"}")).andReturn(); - mockMvc.perform(asyncDispatch(result)).andExpect(status().isOk()) - .andExpect(header().string("X-Custom-Header", "42")); + mockMvc.perform(asyncDispatch(result)) + .andExpect(status().isOk()) + .andExpect(header().string("X-Custom-Header", "42")); }); } @Test void shouldExposeSchemaEndpoint() { - testWith((mockMvc) -> mockMvc.perform(get("/graphql/schema")).andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.TEXT_PLAIN)) - .andExpect(content().string(Matchers.containsString("type Book")))); + testWith((mockMvc) -> mockMvc.perform(get("/graphql/schema")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.TEXT_PLAIN)) + .andExpect(content().string(Matchers.containsString("type Book")))); } @Test void shouldExposeGraphiqlEndpoint() { testWith((mockMvc) -> { - mockMvc.perform(get("/graphiql")).andExpect(status().is3xxRedirection()) - .andExpect(redirectedUrl("http://localhost/graphiql?path=/graphql")); - mockMvc.perform(get("/graphiql?path=/graphql")).andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.TEXT_HTML)); + mockMvc.perform(get("/graphiql")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl("http://localhost/graphiql?path=/graphql")); + mockMvc.perform(get("/graphiql?path=/graphql")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.TEXT_HTML)); }); } @@ -141,20 +146,22 @@ class GraphQlWebMvcAutoConfigurationTests { testWith((mockMvc) -> { String query = "{" + " bookById(id: \\\"book-1\\\"){ " + " id" + " name" + " pageCount" + " author" + " }" + "}"; - MvcResult result = mockMvc.perform(post("/graphql") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST") - .header(HttpHeaders.ORIGIN, "https://example.com").content("{\"query\": \"" + query + "\"}")) - .andReturn(); - mockMvc.perform(asyncDispatch(result)).andExpect(status().isOk()) - .andExpect(header().stringValues(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "https://example.com")) - .andExpect(header().stringValues(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")); + MvcResult result = mockMvc + .perform(post("/graphql").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST") + .header(HttpHeaders.ORIGIN, "https://example.com") + .content("{\"query\": \"" + query + "\"}")) + .andReturn(); + mockMvc.perform(asyncDispatch(result)) + .andExpect(status().isOk()) + .andExpect(header().stringValues(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "https://example.com")) + .andExpect(header().stringValues(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")); }); } @Test void shouldConfigureWebSocketBeans() { this.contextRunner.withPropertyValues("spring.graphql.websocket.path=/ws") - .run((context) -> assertThat(context).hasSingleBean(GraphQlWebSocketHandler.class)); + .run((context) -> assertThat(context).hasSingleBean(GraphQlWebSocketHandler.class)); } @Test @@ -170,9 +177,10 @@ class GraphQlWebMvcAutoConfigurationTests { private void testWith(MockMvcConsumer mockMvcConsumer) { this.contextRunner.run((context) -> { - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).defaultRequest( - post("/graphql").contentType(MediaType.APPLICATION_GRAPHQL).accept(MediaType.APPLICATION_GRAPHQL)) - .build(); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context) + .defaultRequest(post("/graphql").contentType(MediaType.APPLICATION_GRAPHQL) + .accept(MediaType.APPLICATION_GRAPHQL)) + .build(); mockMvcConsumer.accept(mockMvc); }); } @@ -188,8 +196,8 @@ class GraphQlWebMvcAutoConfigurationTests { @Bean RuntimeWiringConfigurer bookDataFetcher() { - return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query").dataFetcher("bookById", - GraphQlTestDataFetchers.getBookByIdDataFetcher())); + return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query") + .dataFetcher("bookById", GraphQlTestDataFetchers.getBookByIdDataFetcher())); } } @@ -200,7 +208,7 @@ class GraphQlWebMvcAutoConfigurationTests { @Bean WebGraphQlInterceptor customWebGraphQlInterceptor() { return (webInput, interceptorChain) -> interceptorChain.next(webInput) - .doOnNext((output) -> output.getResponseHeaders().add("X-Custom-Header", "42")); + .doOnNext((output) -> output.getResponseHeaders().add("X-Custom-Header", "42")); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java index 46811b2af9..c2ce4f5a21 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -163,7 +163,8 @@ class GroovyTemplateAutoConfigurationTests { MarkupTemplateEngine engine = config.getTemplateEngine(); Writer writer = new StringWriter(); engine.createTemplate(new ClassPathResource("templates/message.tpl").getFile()) - .make(new HashMap(Collections.singletonMap("greeting", "Hello World"))).writeTo(writer); + .make(new HashMap(Collections.singletonMap("greeting", "Hello World"))) + .writeTo(writer); assertThat(writer.toString()).contains("Hello World"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java index 026c93d4e1..b2c7331bc2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,41 +41,47 @@ class GroovyTemplateAvailabilityProviderTests { @Test void availabilityOfTemplateInDefaultLocation() { assertThat(this.provider.isTemplateAvailable("home", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateThatDoesNotExist() { assertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isFalse(); + this.resourceLoader)) + .isFalse(); } @Test void availabilityOfTemplateWithCustomLoaderPath() { this.environment.setProperty("spring.groovy.template.resource-loader-path", "classpath:/custom-templates/"); assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateWithCustomLoaderPathConfiguredAsAList() { this.environment.setProperty("spring.groovy.template.resource-loader-path[0]", "classpath:/custom-templates/"); assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.groovy.template.prefix", "prefix/"); assertThat(this.provider.isTemplateAvailable("prefixed", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.groovy.template.suffix", ".groovytemplate"); assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java index 6e1f0e0aa5..b20ae63b23 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ import static org.assertj.core.api.Assertions.assertThat; class GsonAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class)); @Test void gsonRegistration() { @@ -70,10 +70,10 @@ class GsonAutoConfigurationTests { @Test void excludeFieldsWithoutExposeAnnotation() { this.contextRunner.withPropertyValues("spring.gson.exclude-fields-without-expose-annotation:true") - .run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson.toJson(new DataObject())).isEqualTo("{}"); - }); + .run((context) -> { + Gson gson = context.getBean(Gson.class); + assertThat(gson.toJson(new DataObject())).isEqualTo("{}"); + }); } @Test @@ -95,12 +95,12 @@ class GsonAutoConfigurationTests { @Test void enableComplexMapKeySerialization() { this.contextRunner.withPropertyValues("spring.gson.enable-complex-map-key-serialization:true") - .run((context) -> { - Gson gson = context.getBean(Gson.class); - Map original = new LinkedHashMap<>(); - original.put(new DataObject(), "a"); - assertThat(gson.toJson(original)).isEqualTo("[[{\"data\":1},\"a\"]]"); - }); + .run((context) -> { + Gson gson = context.getBean(Gson.class); + Map original = new LinkedHashMap<>(); + original.put(new DataObject(), "a"); + assertThat(gson.toJson(original)).isEqualTo("[[{\"data\":1},\"a\"]]"); + }); } @Test @@ -124,10 +124,10 @@ class GsonAutoConfigurationTests { @Test void withLongSerializationPolicy() { this.contextRunner.withPropertyValues("spring.gson.long-serialization-policy:" + LongSerializationPolicy.STRING) - .run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson.toJson(new DataObject())).isEqualTo("{\"data\":\"1\"}"); - }); + .run((context) -> { + Gson gson = context.getBean(Gson.class); + assertThat(gson.toJson(new DataObject())).isEqualTo("{\"data\":\"1\"}"); + }); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java index 6553477b2e..039befe419 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ import static org.mockito.Mockito.mock; class H2ConsoleAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(H2ConsoleAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(H2ConsoleAutoConfiguration.class)); @Test void consoleIsDisabledByDefault() { @@ -75,65 +75,68 @@ class H2ConsoleAutoConfigurationTests { @Test void customPathMustBeginWithASlash() { this.contextRunner.withPropertyValues("spring.h2.console.enabled=true", "spring.h2.console.path=custom") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()).isInstanceOf(BeanCreationException.class) - .hasMessageContaining("Failed to bind properties under 'spring.h2.console'"); - }); + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()).isInstanceOf(BeanCreationException.class) + .hasMessageContaining("Failed to bind properties under 'spring.h2.console'"); + }); } @Test void customPathWithTrailingSlash() { this.contextRunner.withPropertyValues("spring.h2.console.enabled=true", "spring.h2.console.path=/custom/") - .run((context) -> { - assertThat(context).hasSingleBean(ServletRegistrationBean.class); - ServletRegistrationBean registrationBean = context.getBean(ServletRegistrationBean.class); - assertThat(registrationBean.getUrlMappings()).contains("/custom/*"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ServletRegistrationBean.class); + ServletRegistrationBean registrationBean = context.getBean(ServletRegistrationBean.class); + assertThat(registrationBean.getUrlMappings()).contains("/custom/*"); + }); } @Test void customPath() { this.contextRunner.withPropertyValues("spring.h2.console.enabled=true", "spring.h2.console.path=/custom") - .run((context) -> { - assertThat(context).hasSingleBean(ServletRegistrationBean.class); - ServletRegistrationBean registrationBean = context.getBean(ServletRegistrationBean.class); - assertThat(registrationBean.getUrlMappings()).contains("/custom/*"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ServletRegistrationBean.class); + ServletRegistrationBean registrationBean = context.getBean(ServletRegistrationBean.class); + assertThat(registrationBean.getUrlMappings()).contains("/custom/*"); + }); } @Test void customInitParameters() { - this.contextRunner.withPropertyValues("spring.h2.console.enabled=true", "spring.h2.console.settings.trace=true", - "spring.h2.console.settings.web-allow-others=true", - "spring.h2.console.settings.web-admin-password=abcd").run((context) -> { - assertThat(context).hasSingleBean(ServletRegistrationBean.class); - ServletRegistrationBean registrationBean = context.getBean(ServletRegistrationBean.class); - assertThat(registrationBean.getUrlMappings()).contains("/h2-console/*"); - assertThat(registrationBean.getInitParameters()).containsEntry("trace", ""); - assertThat(registrationBean.getInitParameters()).containsEntry("webAllowOthers", ""); - assertThat(registrationBean.getInitParameters()).containsEntry("webAdminPassword", "abcd"); - }); + this.contextRunner + .withPropertyValues("spring.h2.console.enabled=true", "spring.h2.console.settings.trace=true", + "spring.h2.console.settings.web-allow-others=true", + "spring.h2.console.settings.web-admin-password=abcd") + .run((context) -> { + assertThat(context).hasSingleBean(ServletRegistrationBean.class); + ServletRegistrationBean registrationBean = context.getBean(ServletRegistrationBean.class); + assertThat(registrationBean.getUrlMappings()).contains("/h2-console/*"); + assertThat(registrationBean.getInitParameters()).containsEntry("trace", ""); + assertThat(registrationBean.getInitParameters()).containsEntry("webAllowOthers", ""); + assertThat(registrationBean.getInitParameters()).containsEntry("webAdminPassword", "abcd"); + }); } @Test @ExtendWith(OutputCaptureExtension.class) void singleDataSourceUrlIsLoggedWhenOnlyOneAvailable(CapturedOutput output) { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.h2.console.enabled=true").run((context) -> { - try (Connection connection = context.getBean(DataSource.class).getConnection()) { - assertThat(output).contains("H2 console available at '/h2-console'. Database available at '" - + connection.getMetaData().getURL() + "'"); - } - }); + .withPropertyValues("spring.h2.console.enabled=true") + .run((context) -> { + try (Connection connection = context.getBean(DataSource.class).getConnection()) { + assertThat(output).contains("H2 console available at '/h2-console'. Database available at '" + + connection.getMetaData().getURL() + "'"); + } + }); } @Test @ExtendWith(OutputCaptureExtension.class) void noDataSourceIsLoggedWhenNoneAvailable(CapturedOutput output) { this.contextRunner.withUserConfiguration(FailingDataSourceConfiguration.class) - .withPropertyValues("spring.h2.console.enabled=true") - .run((context) -> assertThat(output).doesNotContain("H2 console available")); + .withPropertyValues("spring.h2.console.enabled=true") + .run((context) -> assertThat(output).doesNotContain("H2 console available")); } @Test @@ -141,16 +144,17 @@ class H2ConsoleAutoConfigurationTests { void allDataSourceUrlsAreLoggedWhenMultipleAvailable(CapturedOutput output) { ClassLoader webAppClassLoader = new URLClassLoader(new URL[0]); this.contextRunner.withClassLoader(webAppClassLoader) - .withUserConfiguration(FailingDataSourceConfiguration.class, MultiDataSourceConfiguration.class) - .withPropertyValues("spring.h2.console.enabled=true").run((context) -> assertThat(output).contains( - "H2 console available at '/h2-console'. Databases available at 'someJdbcUrl', 'anotherJdbcUrl'")); + .withUserConfiguration(FailingDataSourceConfiguration.class, MultiDataSourceConfiguration.class) + .withPropertyValues("spring.h2.console.enabled=true") + .run((context) -> assertThat(output).contains( + "H2 console available at '/h2-console'. Databases available at 'someJdbcUrl', 'anotherJdbcUrl'")); } @Test void h2ConsoleShouldNotFailIfDatabaseConnectionFails() { this.contextRunner.withUserConfiguration(FailingDataSourceConfiguration.class) - .withPropertyValues("spring.h2.console.enabled=true") - .run((context) -> assertThat(context.isRunning()).isTrue()); + .withPropertyValues("spring.h2.console.enabled=true") + .run((context) -> assertThat(context.isRunning()).isTrue()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java index ddcd6e1145..e60e6abcfa 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,21 +31,21 @@ class H2ConsolePropertiesTests { void pathMustNotBeEmpty() { H2ConsoleProperties properties = new H2ConsoleProperties(); assertThatIllegalArgumentException().isThrownBy(() -> properties.setPath("")) - .withMessageContaining("Path must have length greater than 1"); + .withMessageContaining("Path must have length greater than 1"); } @Test void pathMustHaveLengthGreaterThanOne() { H2ConsoleProperties properties = new H2ConsoleProperties(); assertThatIllegalArgumentException().isThrownBy(() -> properties.setPath("/")) - .withMessageContaining("Path must have length greater than 1"); + .withMessageContaining("Path must have length greater than 1"); } @Test void customPathMustBeginWithASlash() { H2ConsoleProperties properties = new H2ConsoleProperties(); assertThatIllegalArgumentException().isThrownBy(() -> properties.setPath("custom")) - .withMessageContaining("Path must start with '/'"); + .withMessageContaining("Path must start with '/'"); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java index 9931093c1d..139a5e8845 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,12 +54,12 @@ import static org.assertj.core.api.Assertions.assertThat; class HypermediaAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withUserConfiguration(BaseConfig.class); + .withUserConfiguration(BaseConfig.class); @Test void autoConfigurationWhenSpringMvcNotOnClasspathShouldBackOff() { this.contextRunner.withClassLoader(new FilteredClassLoader(RequestMappingHandlerAdapter.class)) - .run((context) -> assertThat(context.getBeansOfType(HypermediaConfiguration.class)).isEmpty()); + .run((context) -> assertThat(context.getBeansOfType(HypermediaConfiguration.class)).isEmpty()); } @Test @@ -83,34 +83,39 @@ class HypermediaAutoConfigurationTests { @Test void doesBackOffIfEnableHypermediaSupportIsDeclaredManually() { this.contextRunner.withUserConfiguration(EnableHypermediaSupportConfig.class) - .withPropertyValues("spring.jackson.serialization.INDENT_OUTPUT:true") - .run((context) -> assertThat(context.getBeansOfType(HypermediaConfiguration.class)).isEmpty()); + .withPropertyValues("spring.jackson.serialization.INDENT_OUTPUT:true") + .run((context) -> assertThat(context.getBeansOfType(HypermediaConfiguration.class)).isEmpty()); } @Test void whenUsingTheDefaultConfigurationThenMappingJacksonConverterCanWriteHateoasTypeAsApplicationJson() { this.contextRunner.run((context) -> { RequestMappingHandlerAdapter handlerAdapter = context.getBean(RequestMappingHandlerAdapter.class); - Optional> mappingJacksonConverter = handlerAdapter.getMessageConverters().stream() - .filter(MappingJackson2HttpMessageConverter.class::isInstance).findFirst(); - assertThat(mappingJacksonConverter).isPresent().hasValueSatisfying( - (converter) -> assertThat(converter.canWrite(RepresentationModel.class, MediaType.APPLICATION_JSON)) - .isTrue()); + Optional> mappingJacksonConverter = handlerAdapter.getMessageConverters() + .stream() + .filter(MappingJackson2HttpMessageConverter.class::isInstance) + .findFirst(); + assertThat(mappingJacksonConverter).isPresent() + .hasValueSatisfying((converter) -> assertThat( + converter.canWrite(RepresentationModel.class, MediaType.APPLICATION_JSON)) + .isTrue()); }); } @Test void whenHalIsNotTheDefaultJsonMediaTypeThenMappingJacksonConverterCannotWriteHateoasTypeAsApplicationJson() { this.contextRunner.withPropertyValues("spring.hateoas.use-hal-as-default-json-media-type:false") - .run((context) -> { - RequestMappingHandlerAdapter handlerAdapter = context.getBean(RequestMappingHandlerAdapter.class); - Optional> mappingJacksonConverter = handlerAdapter.getMessageConverters() - .stream().filter(MappingJackson2HttpMessageConverter.class::isInstance).findFirst(); - assertThat(mappingJacksonConverter).isPresent() - .hasValueSatisfying((converter) -> assertThat( - converter.canWrite(RepresentationModel.class, MediaType.APPLICATION_JSON)) - .isFalse()); - }); + .run((context) -> { + RequestMappingHandlerAdapter handlerAdapter = context.getBean(RequestMappingHandlerAdapter.class); + Optional> mappingJacksonConverter = handlerAdapter.getMessageConverters() + .stream() + .filter(MappingJackson2HttpMessageConverter.class::isInstance) + .findFirst(); + assertThat(mappingJacksonConverter).isPresent() + .hasValueSatisfying((converter) -> assertThat( + converter.canWrite(RepresentationModel.class, MediaType.APPLICATION_JSON)) + .isFalse()); + }); } @ImportAutoConfiguration({ HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/Hazelcast4AutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/Hazelcast4AutoConfigurationTests.java index e1b15687c2..1acb578e18 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/Hazelcast4AutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/Hazelcast4AutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,16 +44,17 @@ import static org.assertj.core.api.Assertions.assertThat; class Hazelcast4AutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); @Test void serverConfig() { - this.contextRunner.withPropertyValues( - "spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/hazelcast-4-server.xml") - .run((context) -> { - Config config = context.getBean(HazelcastInstance.class).getConfig(); - assertThat(config.getInstanceName()).isEqualTo("explicit-server"); - }); + this.contextRunner + .withPropertyValues( + "spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/hazelcast-4-server.xml") + .run((context) -> { + Config config = context.getBean(HazelcastInstance.class).getConfig(); + assertThat(config.getInstanceName()).isEqualTo("explicit-server"); + }); } @Test @@ -65,9 +66,9 @@ class Hazelcast4AutoConfigurationTests { HazelcastInstance hazelcastServer = Hazelcast.newHazelcastInstance(config); try { this.contextRunner - .withPropertyValues("spring.hazelcast.config=" - + "org/springframework/boot/autoconfigure/hazelcast/hazelcast-4-client.xml") - .run(assertSpecificHazelcastClient("explicit-client")); + .withPropertyValues("spring.hazelcast.config=" + + "org/springframework/boot/autoconfigure/hazelcast/hazelcast-4-client.xml") + .run(assertSpecificHazelcastClient("explicit-client")); } finally { hazelcastServer.shutdown(); @@ -76,22 +77,26 @@ class Hazelcast4AutoConfigurationTests { @Test void autoConfiguredConfigUsesSpringManagedContext() { - this.contextRunner.withPropertyValues( - "spring.hazelcast.config=" + "org/springframework/boot/autoconfigure/hazelcast/hazelcast-4-server.xml") - .run((context) -> { - Config config = context.getBean(HazelcastInstance.class).getConfig(); - assertThat(config.getManagedContext()).isInstanceOf(SpringManagedContext.class); - }); + this.contextRunner + .withPropertyValues("spring.hazelcast.config=" + + "org/springframework/boot/autoconfigure/hazelcast/hazelcast-4-server.xml") + .run((context) -> { + Config config = context.getBean(HazelcastInstance.class).getConfig(); + assertThat(config.getManagedContext()).isInstanceOf(SpringManagedContext.class); + }); } private ContextConsumer assertSpecificHazelcastClient(String label) { - return (context) -> assertThat(context).getBean(HazelcastInstance.class).isInstanceOf(HazelcastInstance.class) - .has(labelEqualTo(label)); + return (context) -> assertThat(context).getBean(HazelcastInstance.class) + .isInstanceOf(HazelcastInstance.class) + .has(labelEqualTo(label)); } private static Condition labelEqualTo(String label) { - return new Condition<>((o) -> ((HazelcastClientProxy) o).getClientConfig().getLabels().stream() - .anyMatch((e) -> e.equals(label)), "Label equals to " + label); + return new Condition<>((o) -> ((HazelcastClientProxy) o).getClientConfig() + .getLabels() + .stream() + .anyMatch((e) -> e.equals(label)), "Label equals to " + label); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java index c1cd46fdd6..dbe06a3501 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,120 +63,132 @@ class HazelcastAutoConfigurationClientTests { } private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); @Test void systemPropertyWithXml() { this.contextRunner - .withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY - + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-client-specific.xml") - .run(assertSpecificHazelcastClient("explicit-xml")); + .withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY + + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-client-specific.xml") + .run(assertSpecificHazelcastClient("explicit-xml")); } @Test void systemPropertyWithYaml() { this.contextRunner - .withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY - + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-client-specific.yaml") - .run(assertSpecificHazelcastClient("explicit-yaml")); + .withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY + + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-client-specific.yaml") + .run(assertSpecificHazelcastClient("explicit-yaml")); } @Test void systemPropertyWithYml() { this.contextRunner - .withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY - + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-client-specific.yml") - .run(assertSpecificHazelcastClient("explicit-yml")); + .withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY + + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-client-specific.yml") + .run(assertSpecificHazelcastClient("explicit-yml")); } @Test void explicitConfigFileWithXml() { - this.contextRunner.withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" - + "hazelcast/hazelcast-client-specific.xml").run(assertSpecificHazelcastClient("explicit-xml")); + this.contextRunner + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" + + "hazelcast/hazelcast-client-specific.xml") + .run(assertSpecificHazelcastClient("explicit-xml")); } @Test void explicitConfigFileWithYaml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" - + "hazelcast/hazelcast-client-specific.yaml") - .run(assertSpecificHazelcastClient("explicit-yaml")); + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" + + "hazelcast/hazelcast-client-specific.yaml") + .run(assertSpecificHazelcastClient("explicit-yaml")); } @Test void explicitConfigFileWithYml() { - this.contextRunner.withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" - + "hazelcast/hazelcast-client-specific.yml").run(assertSpecificHazelcastClient("explicit-yml")); + this.contextRunner + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" + + "hazelcast/hazelcast-client-specific.yml") + .run(assertSpecificHazelcastClient("explicit-yml")); } @Test void explicitConfigUrlWithXml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" - + "boot/autoconfigure/hazelcast/hazelcast-client-specific.xml") - .run(assertSpecificHazelcastClient("explicit-xml")); + .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + + "boot/autoconfigure/hazelcast/hazelcast-client-specific.xml") + .run(assertSpecificHazelcastClient("explicit-xml")); } @Test void explicitConfigUrlWithYaml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" - + "boot/autoconfigure/hazelcast/hazelcast-client-specific.yaml") - .run(assertSpecificHazelcastClient("explicit-yaml")); + .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + + "boot/autoconfigure/hazelcast/hazelcast-client-specific.yaml") + .run(assertSpecificHazelcastClient("explicit-yaml")); } @Test void explicitConfigUrlWithYml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" - + "boot/autoconfigure/hazelcast/hazelcast-client-specific.yml") - .run(assertSpecificHazelcastClient("explicit-yml")); + .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + + "boot/autoconfigure/hazelcast/hazelcast-client-specific.yml") + .run(assertSpecificHazelcastClient("explicit-yml")); } @Test void unknownConfigFile() { this.contextRunner.withPropertyValues("spring.hazelcast.config=foo/bar/unknown.xml") - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("foo/bar/unknown.xml")); + .run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("foo/bar/unknown.xml")); } @Test void clientConfigTakesPrecedence() { this.contextRunner.withUserConfiguration(HazelcastServerAndClientConfig.class) - .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml").run((context) -> assertThat(context) - .getBean(HazelcastInstance.class).isInstanceOf(HazelcastClientProxy.class)); + .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml") + .run((context) -> assertThat(context).getBean(HazelcastInstance.class) + .isInstanceOf(HazelcastClientProxy.class)); } @Test void clientConfigWithInstanceNameCreatesClientIfNecessary() { assertThat(HazelcastClient.getHazelcastClientByName("spring-boot")).isNull(); this.contextRunner - .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" - + "boot/autoconfigure/hazelcast/hazelcast-client-instance.xml") - .run((context) -> assertThat(context).getBean(HazelcastInstance.class) - .extracting(HazelcastInstance::getName).isEqualTo("spring-boot")); + .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + + "boot/autoconfigure/hazelcast/hazelcast-client-instance.xml") + .run((context) -> assertThat(context).getBean(HazelcastInstance.class) + .extracting(HazelcastInstance::getName) + .isEqualTo("spring-boot")); } @Test void autoConfiguredClientConfigUsesApplicationClassLoader() { - this.contextRunner.withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" - + "hazelcast/hazelcast-client-specific.xml").run((context) -> { - HazelcastInstance hazelcast = context.getBean(HazelcastInstance.class); - assertThat(hazelcast).isInstanceOf(HazelcastClientProxy.class); - ClientConfig clientConfig = ((HazelcastClientProxy) hazelcast).getClientConfig(); - assertThat(clientConfig.getClassLoader()) - .isSameAs(context.getSourceApplicationContext().getClassLoader()); - }); + this.contextRunner + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" + + "hazelcast/hazelcast-client-specific.xml") + .run((context) -> { + HazelcastInstance hazelcast = context.getBean(HazelcastInstance.class); + assertThat(hazelcast).isInstanceOf(HazelcastClientProxy.class); + ClientConfig clientConfig = ((HazelcastClientProxy) hazelcast).getClientConfig(); + assertThat(clientConfig.getClassLoader()) + .isSameAs(context.getSourceApplicationContext().getClassLoader()); + }); } private ContextConsumer assertSpecificHazelcastClient(String label) { - return (context) -> assertThat(context).getBean(HazelcastInstance.class).isInstanceOf(HazelcastInstance.class) - .has(labelEqualTo(label)); + return (context) -> assertThat(context).getBean(HazelcastInstance.class) + .isInstanceOf(HazelcastInstance.class) + .has(labelEqualTo(label)); } private static Condition labelEqualTo(String label) { - return new Condition<>((o) -> ((HazelcastClientProxy) o).getClientConfig().getLabels().stream() - .anyMatch((e) -> e.equals(label)), "Label equals to " + label); + return new Condition<>((o) -> ((HazelcastClientProxy) o).getClientConfig() + .getLabels() + .stream() + .anyMatch((e) -> e.equals(label)), "Label equals to " + label); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java index c9bc6388f9..9a533d108c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ import static org.assertj.core.api.Assertions.assertThat; class HazelcastAutoConfigurationServerTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); @Test void defaultConfigFile() { @@ -68,88 +68,88 @@ class HazelcastAutoConfigurationServerTests { @Test void systemPropertyWithXml() { this.contextRunner - .withSystemProperties(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY - + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml") - .run((context) -> { - Config config = context.getBean(HazelcastInstance.class).getConfig(); - assertThat(config.getMapConfigs().keySet()).containsOnly("foobar"); - }); + .withSystemProperties(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY + + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml") + .run((context) -> { + Config config = context.getBean(HazelcastInstance.class).getConfig(); + assertThat(config.getMapConfigs().keySet()).containsOnly("foobar"); + }); } @Test void systemPropertyWithYaml() { this.contextRunner - .withSystemProperties(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY - + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yaml") - .run((context) -> { - Config config = context.getBean(HazelcastInstance.class).getConfig(); - assertThat(config.getMapConfigs().keySet()).containsOnly("foobar"); - }); + .withSystemProperties(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY + + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yaml") + .run((context) -> { + Config config = context.getBean(HazelcastInstance.class).getConfig(); + assertThat(config.getMapConfigs().keySet()).containsOnly("foobar"); + }); } @Test void systemPropertyWithYml() { this.contextRunner - .withSystemProperties(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY - + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yml") - .run((context) -> { - Config config = context.getBean(HazelcastInstance.class).getConfig(); - assertThat(config.getMapConfigs().keySet()).containsOnly("foobar"); - }); + .withSystemProperties(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY + + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yml") + .run((context) -> { + Config config = context.getBean(HazelcastInstance.class).getConfig(); + assertThat(config.getMapConfigs().keySet()).containsOnly("foobar"); + }); } @Test void explicitConfigFileWithXml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" - + "hazelcast-specific.xml") - .run(assertSpecificHazelcastServer( - "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml")); + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" + + "hazelcast-specific.xml") + .run(assertSpecificHazelcastServer( + "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml")); } @Test void explicitConfigFileWithYaml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" - + "hazelcast-specific.yaml") - .run(assertSpecificHazelcastServer( - "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yaml")); + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" + + "hazelcast-specific.yaml") + .run(assertSpecificHazelcastServer( + "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yaml")); } @Test void explicitConfigFileWithYml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" - + "hazelcast-specific.yml") - .run(assertSpecificHazelcastServer( - "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yml")); + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" + + "hazelcast-specific.yml") + .run(assertSpecificHazelcastServer( + "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yml")); } @Test void explicitConfigUrlWithXml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" - + "boot/autoconfigure/hazelcast/hazelcast-specific.xml") - .run(assertSpecificHazelcastServer( - "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml")); + .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + + "boot/autoconfigure/hazelcast/hazelcast-specific.xml") + .run(assertSpecificHazelcastServer( + "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml")); } @Test void explicitConfigUrlWithYaml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" - + "boot/autoconfigure/hazelcast/hazelcast-specific.yaml") - .run(assertSpecificHazelcastServer( - "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yaml")); + .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + + "boot/autoconfigure/hazelcast/hazelcast-specific.yaml") + .run(assertSpecificHazelcastServer( + "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yaml")); } @Test void explicitConfigUrlWithYml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" - + "boot/autoconfigure/hazelcast/hazelcast-specific.yml") - .run(assertSpecificHazelcastServer( - "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yml")); + .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + + "boot/autoconfigure/hazelcast/hazelcast-specific.yml") + .run(assertSpecificHazelcastServer( + "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yml")); } private ContextConsumer assertSpecificHazelcastServer(String location) { @@ -162,8 +162,9 @@ class HazelcastAutoConfigurationServerTests { @Test void unknownConfigFile() { this.contextRunner.withPropertyValues("spring.hazelcast.config=foo/bar/unknown.xml") - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("foo/bar/unknown.xml")); + .run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("foo/bar/unknown.xml")); } @Test @@ -172,12 +173,13 @@ class HazelcastAutoConfigurationServerTests { HazelcastInstance existing = Hazelcast.newHazelcastInstance(config); try { this.contextRunner.withUserConfiguration(HazelcastConfigWithName.class) - .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml").run((context) -> { - HazelcastInstance hazelcast = context.getBean(HazelcastInstance.class); - assertThat(hazelcast.getConfig().getInstanceName()).isEqualTo("my-test-instance"); - // Should reuse any existing instance by default. - assertThat(hazelcast).isEqualTo(existing); - }); + .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml") + .run((context) -> { + HazelcastInstance hazelcast = context.getBean(HazelcastInstance.class); + assertThat(hazelcast.getConfig().getInstanceName()).isEqualTo("my-test-instance"); + // Should reuse any existing instance by default. + assertThat(hazelcast).isEqualTo(existing); + }); } finally { existing.shutdown(); @@ -187,11 +189,12 @@ class HazelcastAutoConfigurationServerTests { @Test void configInstanceWithoutName() { this.contextRunner.withUserConfiguration(HazelcastConfigNoName.class) - .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml").run((context) -> { - Config config = context.getBean(HazelcastInstance.class).getConfig(); - Map queueConfigs = config.getQueueConfigs(); - assertThat(queueConfigs.keySet()).containsOnly("another-queue"); - }); + .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml") + .run((context) -> { + Config config = context.getBean(HazelcastInstance.class).getConfig(); + Map queueConfigs = config.getQueueConfigs(); + assertThat(queueConfigs.keySet()).containsOnly("another-queue"); + }); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java index a1bafc7fec..ca4209b3e4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat; class HazelcastAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); @Test void defaultConfigFile() { @@ -55,7 +55,7 @@ class HazelcastAutoConfigurationTests { @Test void hazelcastInstanceNotCreatedWhenJetIsPresent() { this.contextRunner.withClassLoader(new JetConfigClassLoader()) - .run((context) -> assertThat(context).doesNotHaveBean(HazelcastInstance.class)); + .run((context) -> assertThat(context).doesNotHaveBean(HazelcastInstance.class)); } /** diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java index c50db4119d..d1c1928114 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,12 +46,12 @@ import static org.mockito.Mockito.mock; class HazelcastJpaDependencyAutoConfigurationTests { private static final String POST_PROCESSOR_BEAN_NAME = HazelcastInstanceEntityManagerFactoryDependsOnPostProcessor.class - .getName(); + .getName(); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class, HazelcastJpaDependencyAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true"); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, + HazelcastJpaDependencyAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test void registrationIfHazelcastInstanceHasRegularBeanName() { @@ -80,8 +80,8 @@ class HazelcastJpaDependencyAutoConfigurationTests { @Test void noRegistrationWithNoEntityManagerFactory() { new ApplicationContextRunner().withUserConfiguration(HazelcastConfiguration.class) - .withConfiguration(AutoConfigurations.of(HazelcastJpaDependencyAutoConfiguration.class)) - .run((context) -> assertThat(postProcessors(context)).doesNotContainKey(POST_PROCESSOR_BEAN_NAME)); + .withConfiguration(AutoConfigurations.of(HazelcastJpaDependencyAutoConfiguration.class)) + .run((context) -> assertThat(postProcessors(context)).doesNotContainKey(POST_PROCESSOR_BEAN_NAME)); } private Map postProcessors( @@ -91,7 +91,8 @@ class HazelcastJpaDependencyAutoConfigurationTests { private List entityManagerFactoryDependencies(AssertableApplicationContext context) { String[] dependsOn = ((BeanDefinitionRegistry) context.getSourceApplicationContext()) - .getBeanDefinition("entityManagerFactory").getDependsOn(); + .getBeanDefinition("entityManagerFactory") + .getDependsOn(); return (dependsOn != null) ? Arrays.asList(dependsOn) : Collections.emptyList(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationTests.java index 7851b1a0d4..aecba1744f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,7 +66,7 @@ import static org.assertj.core.api.Assertions.assertThat; class HttpMessageConvertersAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)); @Test void jacksonNotAvailable() { @@ -80,25 +80,26 @@ class HttpMessageConvertersAutoConfigurationTests { @Test void jacksonDefaultConverter() { this.contextRunner.withUserConfiguration(JacksonObjectMapperConfig.class) - .run(assertConverter(MappingJackson2HttpMessageConverter.class, "mappingJackson2HttpMessageConverter")); + .run(assertConverter(MappingJackson2HttpMessageConverter.class, "mappingJackson2HttpMessageConverter")); } @Test void jacksonConverterWithBuilder() { this.contextRunner.withUserConfiguration(JacksonObjectMapperBuilderConfig.class) - .run(assertConverter(MappingJackson2HttpMessageConverter.class, "mappingJackson2HttpMessageConverter")); + .run(assertConverter(MappingJackson2HttpMessageConverter.class, "mappingJackson2HttpMessageConverter")); } @Test void jacksonXmlConverterWithBuilder() { - this.contextRunner.withUserConfiguration(JacksonObjectMapperBuilderConfig.class).run(assertConverter( - MappingJackson2XmlHttpMessageConverter.class, "mappingJackson2XmlHttpMessageConverter")); + this.contextRunner.withUserConfiguration(JacksonObjectMapperBuilderConfig.class) + .run(assertConverter(MappingJackson2XmlHttpMessageConverter.class, + "mappingJackson2XmlHttpMessageConverter")); } @Test void jacksonCustomConverter() { this.contextRunner.withUserConfiguration(JacksonObjectMapperConfig.class, JacksonConverterConfig.class) - .run(assertConverter(MappingJackson2HttpMessageConverter.class, "customJacksonMessageConverter")); + .run(assertConverter(MappingJackson2HttpMessageConverter.class, "customJacksonMessageConverter")); } @Test @@ -112,14 +113,14 @@ class HttpMessageConvertersAutoConfigurationTests { @Test void gsonDefaultConverter() { this.contextRunner.withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class)) - .run(assertConverter(GsonHttpMessageConverter.class, "gsonHttpMessageConverter")); + .run(assertConverter(GsonHttpMessageConverter.class, "gsonHttpMessageConverter")); } @Test void gsonCustomConverter() { this.contextRunner.withUserConfiguration(GsonConverterConfig.class) - .withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class)) - .run(assertConverter(GsonHttpMessageConverter.class, "customGsonMessageConverter")); + .withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class)) + .run(assertConverter(GsonHttpMessageConverter.class, "customGsonMessageConverter")); } @Test @@ -143,14 +144,14 @@ class HttpMessageConvertersAutoConfigurationTests { @Test void jsonbDefaultConverter() { this.contextRunner.withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)) - .run(assertConverter(JsonbHttpMessageConverter.class, "jsonbHttpMessageConverter")); + .run(assertConverter(JsonbHttpMessageConverter.class, "jsonbHttpMessageConverter")); } @Test void jsonbCustomConverter() { this.contextRunner.withUserConfiguration(JsonbConverterConfig.class) - .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)) - .run(assertConverter(JsonbHttpMessageConverter.class, "customJsonbMessageConverter")); + .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)) + .run(assertConverter(JsonbHttpMessageConverter.class, "customJsonbMessageConverter")); } @Test @@ -171,30 +172,31 @@ class HttpMessageConvertersAutoConfigurationTests { @Test void stringCustomConverter() { this.contextRunner.withUserConfiguration(StringConverterConfig.class) - .run(assertConverter(StringHttpMessageConverter.class, "customStringMessageConverter")); + .run(assertConverter(StringHttpMessageConverter.class, "customStringMessageConverter")); } @Test void typeConstrainedConverterDoesNotPreventAutoConfigurationOfJacksonConverter() { - this.contextRunner.withUserConfiguration(JacksonObjectMapperBuilderConfig.class, - TypeConstrainedConverterConfiguration.class).run((context) -> { - BeanDefinition beanDefinition = ((GenericApplicationContext) context.getSourceApplicationContext()) - .getBeanDefinition("mappingJackson2HttpMessageConverter"); - assertThat(beanDefinition.getFactoryBeanName()) - .isEqualTo(MappingJackson2HttpMessageConverterConfiguration.class.getName()); - }); + this.contextRunner + .withUserConfiguration(JacksonObjectMapperBuilderConfig.class, TypeConstrainedConverterConfiguration.class) + .run((context) -> { + BeanDefinition beanDefinition = ((GenericApplicationContext) context.getSourceApplicationContext()) + .getBeanDefinition("mappingJackson2HttpMessageConverter"); + assertThat(beanDefinition.getFactoryBeanName()) + .isEqualTo(MappingJackson2HttpMessageConverterConfiguration.class.getName()); + }); } @Test void typeConstrainedConverterFromSpringDataDoesNotPreventAutoConfigurationOfJacksonConverter() { this.contextRunner - .withUserConfiguration(JacksonObjectMapperBuilderConfig.class, RepositoryRestMvcConfiguration.class) - .run((context) -> { - BeanDefinition beanDefinition = ((GenericApplicationContext) context.getSourceApplicationContext()) - .getBeanDefinition("mappingJackson2HttpMessageConverter"); - assertThat(beanDefinition.getFactoryBeanName()) - .isEqualTo(MappingJackson2HttpMessageConverterConfiguration.class.getName()); - }); + .withUserConfiguration(JacksonObjectMapperBuilderConfig.class, RepositoryRestMvcConfiguration.class) + .run((context) -> { + BeanDefinition beanDefinition = ((GenericApplicationContext) context.getSourceApplicationContext()) + .getBeanDefinition("mappingJackson2HttpMessageConverter"); + assertThat(beanDefinition.getFactoryBeanName()) + .isEqualTo(MappingJackson2HttpMessageConverterConfiguration.class.getName()); + }); } @Test @@ -211,65 +213,66 @@ class HttpMessageConvertersAutoConfigurationTests { @Test void gsonIsPreferredIfJacksonIsNotAvailable() { allOptionsRunner().withClassLoader(new FilteredClassLoader(ObjectMapper.class.getPackage().getName())) - .run((context) -> { - assertConverterBeanExists(context, GsonHttpMessageConverter.class, "gsonHttpMessageConverter"); - assertConverterBeanRegisteredWithHttpMessageConverters(context, GsonHttpMessageConverter.class); - assertThat(context).doesNotHaveBean(JsonbHttpMessageConverter.class); - }); + .run((context) -> { + assertConverterBeanExists(context, GsonHttpMessageConverter.class, "gsonHttpMessageConverter"); + assertConverterBeanRegisteredWithHttpMessageConverters(context, GsonHttpMessageConverter.class); + assertThat(context).doesNotHaveBean(JsonbHttpMessageConverter.class); + }); } @Test void jsonbIsPreferredIfJacksonAndGsonAreNotAvailable() { allOptionsRunner() - .withClassLoader(new FilteredClassLoader(ObjectMapper.class.getPackage().getName(), - Gson.class.getPackage().getName())) - .run(assertConverter(JsonbHttpMessageConverter.class, "jsonbHttpMessageConverter")); + .withClassLoader(new FilteredClassLoader(ObjectMapper.class.getPackage().getName(), + Gson.class.getPackage().getName())) + .run(assertConverter(JsonbHttpMessageConverter.class, "jsonbHttpMessageConverter")); } @Test void whenServletWebApplicationHttpMessageConvertersIsConfigured() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(HttpMessageConverters.class)); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(HttpMessageConverters.class)); } @Test void whenReactiveWebApplicationHttpMessageConvertersIsNotConfigured() { new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(HttpMessageConverters.class)); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(HttpMessageConverters.class)); } @Test void whenEncodingCharsetIsNotConfiguredThenStringMessageConverterUsesUtf8() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) - .run((context) -> { - assertThat(context).hasSingleBean(StringHttpMessageConverter.class); - assertThat(context.getBean(StringHttpMessageConverter.class).getDefaultCharset()) - .isEqualTo(StandardCharsets.UTF_8); - }); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasSingleBean(StringHttpMessageConverter.class); + assertThat(context.getBean(StringHttpMessageConverter.class).getDefaultCharset()) + .isEqualTo(StandardCharsets.UTF_8); + }); } @Test void whenEncodingCharsetIsConfiguredThenStringMessageConverterUsesSpecificCharset() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) - .withPropertyValues("server.servlet.encoding.charset=UTF-16").run((context) -> { - assertThat(context).hasSingleBean(StringHttpMessageConverter.class); - assertThat(context.getBean(StringHttpMessageConverter.class).getDefaultCharset()) - .isEqualTo(StandardCharsets.UTF_16); - }); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) + .withPropertyValues("server.servlet.encoding.charset=UTF-16") + .run((context) -> { + assertThat(context).hasSingleBean(StringHttpMessageConverter.class); + assertThat(context.getBean(StringHttpMessageConverter.class).getDefaultCharset()) + .isEqualTo(StandardCharsets.UTF_16); + }); } @Test // gh-21789 void whenAutoConfigurationIsActiveThenServerPropertiesConfigurationPropertiesAreNotEnabled() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) - .run((context) -> { - assertThat(context).hasSingleBean(HttpMessageConverters.class); - assertThat(context).doesNotHaveBean(ServerProperties.class); - }); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasSingleBean(HttpMessageConverters.class); + assertThat(context).doesNotHaveBean(ServerProperties.class); + }); } private ApplicationContextRunner allOptionsRunner() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java index 0a907eaff7..edb4cb1463 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat; class HttpMessageConvertersAutoConfigurationWithoutJacksonTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)); @Test void autoConfigurationWorksWithSpringHateoasButWithoutJackson() { 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..3adf397c88 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -86,8 +86,10 @@ class HttpMessageConvertersTests { void addBeforeExistingEquivalentConverter() { GsonHttpMessageConverter converter1 = new GsonHttpMessageConverter(); HttpMessageConverters converters = new HttpMessageConverters(converter1); - List> converterClasses = converters.getConverters().stream().map(HttpMessageConverter::getClass) - .collect(Collectors.toList()); + List> converterClasses = converters.getConverters() + .stream() + .map(HttpMessageConverter::getClass) + .collect(Collectors.toList()); assertThat(converterClasses).containsSequence(GsonHttpMessageConverter.class, MappingJackson2HttpMessageConverter.class); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfigurationTests.java index cb8ac25521..2d914cb817 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ import static org.assertj.core.api.Assertions.assertThat; class CodecsAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CodecsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(CodecsAutoConfiguration.class)); @Test void autoConfigShouldProvideALoggingRequestDetailsCustomizer() { @@ -86,17 +86,17 @@ class CodecsAutoConfigurationTests { @Test void jacksonCodecCustomizerIsAutoConfiguredWhenObjectMapperIsPresent() { this.contextRunner.withUserConfiguration(ObjectMapperConfiguration.class) - .run((context) -> assertThat(context).hasBean("jacksonCodecCustomizer")); + .run((context) -> assertThat(context).hasBean("jacksonCodecCustomizer")); } @Test void userProvidedCustomizerCanOverrideJacksonCodecCustomizer() { this.contextRunner.withUserConfiguration(ObjectMapperConfiguration.class, CodecCustomizerConfiguration.class) - .run((context) -> { - List codecCustomizers = context.getBean(CodecCustomizers.class).codecCustomizers; - assertThat(codecCustomizers).hasSize(3); - assertThat(codecCustomizers.get(2)).isInstanceOf(TestCodecCustomizer.class); - }); + .run((context) -> { + List codecCustomizers = context.getBean(CodecCustomizers.class).codecCustomizers; + assertThat(codecCustomizers).hasSize(3); + assertThat(codecCustomizers.get(2)).isInstanceOf(TestCodecCustomizer.class); + }); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfigurationTests.java index 34033cd669..2bed18e3f7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; class InfluxDbAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(InfluxDbAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(InfluxDbAutoConfiguration.class)); @Test void influxDbRequiresUrl() { @@ -52,9 +52,9 @@ class InfluxDbAutoConfigurationTests { @Test void influxDbCanBeCustomized() { this.contextRunner - .withPropertyValues("spring.influx.url=http://localhost", "spring.influx.user=user", - "spring.influx.password=password") - .run((context) -> assertThat(context).hasSingleBean(InfluxDB.class)); + .withPropertyValues("spring.influx.url=http://localhost", "spring.influx.user=user", + "spring.influx.password=password") + .run((context) -> assertThat(context).hasSingleBean(InfluxDB.class)); } @Test @@ -69,21 +69,23 @@ class InfluxDbAutoConfigurationTests { @Test void influxDbWithOkHttpClientBuilderProvider() { this.contextRunner.withUserConfiguration(CustomOkHttpClientBuilderProviderConfig.class) - .withPropertyValues("spring.influx.url=http://localhost").run((context) -> { - assertThat(context).hasSingleBean(InfluxDB.class); - int readTimeout = getReadTimeoutProperty(context); - assertThat(readTimeout).isEqualTo(40_000); - }); + .withPropertyValues("spring.influx.url=http://localhost") + .run((context) -> { + assertThat(context).hasSingleBean(InfluxDB.class); + int readTimeout = getReadTimeoutProperty(context); + assertThat(readTimeout).isEqualTo(40_000); + }); } @Test void influxDbWithCustomizer() { this.contextRunner.withBean(InfluxDbCustomizer.class, () -> (influxDb) -> influxDb.setDatabase("test")) - .withPropertyValues("spring.influx.url=http://localhost").run((context) -> { - assertThat(context).hasSingleBean(InfluxDB.class); - InfluxDB influxDb = context.getBean(InfluxDB.class); - assertThat(influxDb).hasFieldOrPropertyWithValue("database", "test"); - }); + .withPropertyValues("spring.influx.url=http://localhost") + .run((context) -> { + assertThat(context).hasSingleBean(InfluxDB.class); + InfluxDB influxDb = context.getBean(InfluxDB.class); + assertThat(influxDb).hasFieldOrPropertyWithValue("database", "test"); + }); } private int getReadTimeoutProperty(AssertableApplicationContext context) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java index d4d79ed642..9d86809998 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,42 +48,45 @@ class ProjectInfoAutoConfigurationTests { @Test void gitPropertiesWithNoData() { this.contextRunner - .withPropertyValues("spring.info.git.location=" - + "classpath:/org/springframework/boot/autoconfigure/info/git-no-data.properties") - .run((context) -> { - GitProperties gitProperties = context.getBean(GitProperties.class); - assertThat(gitProperties.getBranch()).isNull(); - }); + .withPropertyValues("spring.info.git.location=" + + "classpath:/org/springframework/boot/autoconfigure/info/git-no-data.properties") + .run((context) -> { + GitProperties gitProperties = context.getBean(GitProperties.class); + assertThat(gitProperties.getBranch()).isNull(); + }); } @Test void gitPropertiesFallbackWithGitPropertiesBean() { - this.contextRunner.withUserConfiguration(CustomInfoPropertiesConfiguration.class).withPropertyValues( - "spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties") - .run((context) -> { - GitProperties gitProperties = context.getBean(GitProperties.class); - assertThat(gitProperties).isSameAs(context.getBean("customGitProperties")); - }); + this.contextRunner.withUserConfiguration(CustomInfoPropertiesConfiguration.class) + .withPropertyValues( + "spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties") + .run((context) -> { + GitProperties gitProperties = context.getBean(GitProperties.class); + assertThat(gitProperties).isSameAs(context.getBean("customGitProperties")); + }); } @Test void gitPropertiesUsesUtf8ByDefault() { - this.contextRunner.withPropertyValues( - "spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties") - .run((context) -> { - GitProperties gitProperties = context.getBean(GitProperties.class); - assertThat(gitProperties.get("commit.charset")).isEqualTo("test™"); - }); + this.contextRunner + .withPropertyValues( + "spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties") + .run((context) -> { + GitProperties gitProperties = context.getBean(GitProperties.class); + assertThat(gitProperties.get("commit.charset")).isEqualTo("test™"); + }); } @Test void gitPropertiesEncodingCanBeConfigured() { - this.contextRunner.withPropertyValues("spring.info.git.encoding=US-ASCII", - "spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties") - .run((context) -> { - GitProperties gitProperties = context.getBean(GitProperties.class); - assertThat(gitProperties.get("commit.charset")).isNotEqualTo("test™"); - }); + this.contextRunner + .withPropertyValues("spring.info.git.encoding=US-ASCII", + "spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties") + .run((context) -> { + GitProperties gitProperties = context.getBean(GitProperties.class); + assertThat(gitProperties.get("commit.charset")).isNotEqualTo("test™"); + }); } @Test @@ -101,22 +104,22 @@ class ProjectInfoAutoConfigurationTests { @Test void buildPropertiesCustomLocation() { this.contextRunner - .withPropertyValues("spring.info.build.location=" - + "classpath:/org/springframework/boot/autoconfigure/info/build-info.properties") - .run((context) -> { - BuildProperties buildProperties = context.getBean(BuildProperties.class); - assertThat(buildProperties.getGroup()).isEqualTo("com.example.acme"); - assertThat(buildProperties.getArtifact()).isEqualTo("acme"); - assertThat(buildProperties.getName()).isEqualTo("acme"); - assertThat(buildProperties.getVersion()).isEqualTo("1.0.1-SNAPSHOT"); - assertThat(buildProperties.getTime().toEpochMilli()).isEqualTo(1457088120000L); - }); + .withPropertyValues("spring.info.build.location=" + + "classpath:/org/springframework/boot/autoconfigure/info/build-info.properties") + .run((context) -> { + BuildProperties buildProperties = context.getBean(BuildProperties.class); + assertThat(buildProperties.getGroup()).isEqualTo("com.example.acme"); + assertThat(buildProperties.getArtifact()).isEqualTo("acme"); + assertThat(buildProperties.getName()).isEqualTo("acme"); + assertThat(buildProperties.getVersion()).isEqualTo("1.0.1-SNAPSHOT"); + assertThat(buildProperties.getTime().toEpochMilli()).isEqualTo(1457088120000L); + }); } @Test void buildPropertiesCustomInvalidLocation() { this.contextRunner.withPropertyValues("spring.info.build.location=classpath:/org/acme/no-build-info.properties") - .run((context) -> assertThat(context.getBeansOfType(BuildProperties.class)).hasSize(0)); + .run((context) -> assertThat(context.getBeansOfType(BuildProperties.class)).hasSize(0)); } @Test @@ -131,20 +134,20 @@ class ProjectInfoAutoConfigurationTests { void buildPropertiesUsesUtf8ByDefault() { this.contextRunner.withPropertyValues( "spring.info.build.location=classpath:/org/springframework/boot/autoconfigure/info/build-info.properties") - .run((context) -> { - BuildProperties buildProperties = context.getBean(BuildProperties.class); - assertThat(buildProperties.get("charset")).isEqualTo("test™"); - }); + .run((context) -> { + BuildProperties buildProperties = context.getBean(BuildProperties.class); + assertThat(buildProperties.get("charset")).isEqualTo("test™"); + }); } @Test void buildPropertiesEncodingCanBeConfigured() { this.contextRunner.withPropertyValues("spring.info.build.encoding=US-ASCII", "spring.info.build.location=classpath:/org/springframework/boot/autoconfigure/info/build-info.properties") - .run((context) -> { - BuildProperties buildProperties = context.getBean(BuildProperties.class); - assertThat(buildProperties.get("charset")).isNotEqualTo("test™"); - }); + .run((context) -> { + BuildProperties buildProperties = context.getBean(BuildProperties.class); + assertThat(buildProperties.get("charset")).isNotEqualTo("test™"); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java index b2d7878d75..221d78d852 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -94,7 +94,7 @@ import static org.mockito.Mockito.mock; class IntegrationAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class)); @Test void integrationIsAvailable() { @@ -115,7 +115,7 @@ class IntegrationAutoConfigurationTests { @Test void noMBeanServerAvailable() { ApplicationContextRunner contextRunnerWithoutJmx = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(IntegrationAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(IntegrationAutoConfiguration.class)); contextRunnerWithoutJmx.run((context) -> { assertThat(context).hasSingleBean(TestGateway.class); assertThat(context).hasSingleBean(IntegrationComponentScanConfiguration.class); @@ -125,8 +125,8 @@ class IntegrationAutoConfigurationTests { @Test void parentContext() { this.contextRunner.run((context) -> this.contextRunner.withParent(context) - .withPropertyValues("spring.jmx.default_domain=org.foo") - .run((child) -> assertThat(child).hasSingleBean(HeaderChannelRegistry.class))); + .withPropertyValues("spring.jmx.default_domain=org.foo") + .run((child) -> assertThat(child).hasSingleBean(HeaderChannelRegistry.class))); } @Test @@ -150,143 +150,144 @@ class IntegrationAutoConfigurationTests { @Test void customizeJmxDomain() { this.contextRunner.withPropertyValues("spring.jmx.enabled=true", "spring.jmx.default_domain=org.foo") - .run((context) -> { - MBeanServer mBeanServer = context.getBean(MBeanServer.class); - assertThat(mBeanServer.getDomains()).contains("org.foo").doesNotContain( - "org.springframework.integration", "org.springframework.integration.monitor"); - }); + .run((context) -> { + MBeanServer mBeanServer = context.getBean(MBeanServer.class); + assertThat(mBeanServer.getDomains()).contains("org.foo") + .doesNotContain("org.springframework.integration", "org.springframework.integration.monitor"); + }); } @Test void primaryExporterIsAllowed() { this.contextRunner.withPropertyValues("spring.jmx.enabled=true") - .withUserConfiguration(CustomMBeanExporter.class).run((context) -> { - assertThat(context).getBeans(MBeanExporter.class).hasSize(2); - assertThat(context.getBean(MBeanExporter.class)).isSameAs(context.getBean("myMBeanExporter")); - }); + .withUserConfiguration(CustomMBeanExporter.class) + .run((context) -> { + assertThat(context).getBeans(MBeanExporter.class).hasSize(2); + assertThat(context.getBean(MBeanExporter.class)).isSameAs(context.getBean("myMBeanExporter")); + }); } @Test void integrationJdbcDataSourceInitializerEnabled() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true", - "spring.integration.jdbc.initialize-schema=always") - .run((context) -> { - IntegrationProperties properties = context.getBean(IntegrationProperties.class); - assertThat(properties.getJdbc().getInitializeSchema()).isEqualTo(DatabaseInitializationMode.ALWAYS); - JdbcOperations jdbc = context.getBean(JdbcOperations.class); - assertThat(jdbc.queryForList("select * from INT_MESSAGE")).isEmpty(); - assertThat(jdbc.queryForList("select * from INT_GROUP_TO_MESSAGE")).isEmpty(); - assertThat(jdbc.queryForList("select * from INT_MESSAGE_GROUP")).isEmpty(); - assertThat(jdbc.queryForList("select * from INT_LOCK")).isEmpty(); - assertThat(jdbc.queryForList("select * from INT_CHANNEL_MESSAGE")).isEmpty(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true", + "spring.integration.jdbc.initialize-schema=always") + .run((context) -> { + IntegrationProperties properties = context.getBean(IntegrationProperties.class); + assertThat(properties.getJdbc().getInitializeSchema()).isEqualTo(DatabaseInitializationMode.ALWAYS); + JdbcOperations jdbc = context.getBean(JdbcOperations.class); + assertThat(jdbc.queryForList("select * from INT_MESSAGE")).isEmpty(); + assertThat(jdbc.queryForList("select * from INT_GROUP_TO_MESSAGE")).isEmpty(); + assertThat(jdbc.queryForList("select * from INT_MESSAGE_GROUP")).isEmpty(); + assertThat(jdbc.queryForList("select * from INT_LOCK")).isEmpty(); + assertThat(jdbc.queryForList("select * from INT_CHANNEL_MESSAGE")).isEmpty(); + }); } @Test void whenIntegrationJdbcDataSourceInitializerIsEnabledThenFlywayCanBeUsed() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class, - FlywayAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true", - "spring.integration.jdbc.initialize-schema=always") - .run((context) -> { - IntegrationProperties properties = context.getBean(IntegrationProperties.class); - assertThat(properties.getJdbc().getInitializeSchema()).isEqualTo(DatabaseInitializationMode.ALWAYS); - JdbcOperations jdbc = context.getBean(JdbcOperations.class); - assertThat(jdbc.queryForList("select * from INT_MESSAGE")).isEmpty(); - assertThat(jdbc.queryForList("select * from INT_GROUP_TO_MESSAGE")).isEmpty(); - assertThat(jdbc.queryForList("select * from INT_MESSAGE_GROUP")).isEmpty(); - assertThat(jdbc.queryForList("select * from INT_LOCK")).isEmpty(); - assertThat(jdbc.queryForList("select * from INT_CHANNEL_MESSAGE")).isEmpty(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class, + FlywayAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true", + "spring.integration.jdbc.initialize-schema=always") + .run((context) -> { + IntegrationProperties properties = context.getBean(IntegrationProperties.class); + assertThat(properties.getJdbc().getInitializeSchema()).isEqualTo(DatabaseInitializationMode.ALWAYS); + JdbcOperations jdbc = context.getBean(JdbcOperations.class); + assertThat(jdbc.queryForList("select * from INT_MESSAGE")).isEmpty(); + assertThat(jdbc.queryForList("select * from INT_GROUP_TO_MESSAGE")).isEmpty(); + assertThat(jdbc.queryForList("select * from INT_MESSAGE_GROUP")).isEmpty(); + assertThat(jdbc.queryForList("select * from INT_LOCK")).isEmpty(); + assertThat(jdbc.queryForList("select * from INT_CHANNEL_MESSAGE")).isEmpty(); + }); } @Test void integrationJdbcDataSourceInitializerDisabled() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true", - "spring.integration.jdbc.initialize-schema=never") - .run((context) -> { - assertThat(context).doesNotHaveBean(IntegrationDataSourceScriptDatabaseInitializer.class); - IntegrationProperties properties = context.getBean(IntegrationProperties.class); - assertThat(properties.getJdbc().getInitializeSchema()).isEqualTo(DatabaseInitializationMode.NEVER); - JdbcOperations jdbc = context.getBean(JdbcOperations.class); - assertThatExceptionOfType(BadSqlGrammarException.class) - .isThrownBy(() -> jdbc.queryForList("select * from INT_MESSAGE")); - }); + .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true", + "spring.integration.jdbc.initialize-schema=never") + .run((context) -> { + assertThat(context).doesNotHaveBean(IntegrationDataSourceScriptDatabaseInitializer.class); + IntegrationProperties properties = context.getBean(IntegrationProperties.class); + assertThat(properties.getJdbc().getInitializeSchema()).isEqualTo(DatabaseInitializationMode.NEVER); + JdbcOperations jdbc = context.getBean(JdbcOperations.class); + assertThatExceptionOfType(BadSqlGrammarException.class) + .isThrownBy(() -> jdbc.queryForList("select * from INT_MESSAGE")); + }); } @Test void integrationJdbcDataSourceInitializerEnabledByDefaultWithEmbeddedDb() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true").run((context) -> { - IntegrationProperties properties = context.getBean(IntegrationProperties.class); - assertThat(properties.getJdbc().getInitializeSchema()) - .isEqualTo(DatabaseInitializationMode.EMBEDDED); - JdbcOperations jdbc = context.getBean(JdbcOperations.class); - assertThat(jdbc.queryForList("select * from INT_MESSAGE")).isEmpty(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true") + .run((context) -> { + IntegrationProperties properties = context.getBean(IntegrationProperties.class); + assertThat(properties.getJdbc().getInitializeSchema()).isEqualTo(DatabaseInitializationMode.EMBEDDED); + JdbcOperations jdbc = context.getBean(JdbcOperations.class); + assertThat(jdbc.queryForList("select * from INT_MESSAGE")).isEmpty(); + }); } @Test void rsocketSupportEnabled() { this.contextRunner.withUserConfiguration(RSocketServerConfiguration.class) - .withConfiguration(AutoConfigurations.of(RSocketServerAutoConfiguration.class, - RSocketStrategiesAutoConfiguration.class, RSocketMessagingAutoConfiguration.class, - RSocketRequesterAutoConfiguration.class, IntegrationAutoConfiguration.class)) - .withPropertyValues("spring.rsocket.server.port=0", "spring.integration.rsocket.client.port=0", - "spring.integration.rsocket.client.host=localhost", - "spring.integration.rsocket.server.message-mapping-enabled=true") - .run((context) -> { - assertThat(context).hasSingleBean(ClientRSocketConnector.class).hasBean("clientRSocketConnector") - .hasSingleBean(ServerRSocketConnector.class) - .hasSingleBean(ServerRSocketMessageHandler.class) - .hasSingleBean(RSocketMessageHandler.class); - - ServerRSocketMessageHandler serverRSocketMessageHandler = context - .getBean(ServerRSocketMessageHandler.class); - assertThat(context).getBean(RSocketMessageHandler.class).isSameAs(serverRSocketMessageHandler); - - ClientRSocketConnector clientRSocketConnector = context.getBean(ClientRSocketConnector.class); - ClientTransport clientTransport = (ClientTransport) new DirectFieldAccessor(clientRSocketConnector) - .getPropertyValue("clientTransport"); - - assertThat(clientTransport).isInstanceOf(TcpClientTransport.class); - }); + .withConfiguration(AutoConfigurations.of(RSocketServerAutoConfiguration.class, + RSocketStrategiesAutoConfiguration.class, RSocketMessagingAutoConfiguration.class, + RSocketRequesterAutoConfiguration.class, IntegrationAutoConfiguration.class)) + .withPropertyValues("spring.rsocket.server.port=0", "spring.integration.rsocket.client.port=0", + "spring.integration.rsocket.client.host=localhost", + "spring.integration.rsocket.server.message-mapping-enabled=true") + .run((context) -> { + assertThat(context).hasSingleBean(ClientRSocketConnector.class) + .hasBean("clientRSocketConnector") + .hasSingleBean(ServerRSocketConnector.class) + .hasSingleBean(ServerRSocketMessageHandler.class) + .hasSingleBean(RSocketMessageHandler.class); + + ServerRSocketMessageHandler serverRSocketMessageHandler = context + .getBean(ServerRSocketMessageHandler.class); + assertThat(context).getBean(RSocketMessageHandler.class).isSameAs(serverRSocketMessageHandler); + + ClientRSocketConnector clientRSocketConnector = context.getBean(ClientRSocketConnector.class); + ClientTransport clientTransport = (ClientTransport) new DirectFieldAccessor(clientRSocketConnector) + .getPropertyValue("clientTransport"); + + assertThat(clientTransport).isInstanceOf(TcpClientTransport.class); + }); } @Test void taskSchedulerIsNotOverridden() { this.contextRunner.withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) - .withPropertyValues("spring.task.scheduling.thread-name-prefix=integration-scheduling-", - "spring.task.scheduling.pool.size=3") - .run((context) -> { - assertThat(context).hasSingleBean(TaskScheduler.class); - assertThat(context).getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class) - .hasFieldOrPropertyWithValue("threadNamePrefix", "integration-scheduling-") - .hasFieldOrPropertyWithValue("scheduledExecutor.corePoolSize", 3); - }); + .withPropertyValues("spring.task.scheduling.thread-name-prefix=integration-scheduling-", + "spring.task.scheduling.pool.size=3") + .run((context) -> { + assertThat(context).hasSingleBean(TaskScheduler.class); + assertThat(context).getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class) + .hasFieldOrPropertyWithValue("threadNamePrefix", "integration-scheduling-") + .hasFieldOrPropertyWithValue("scheduledExecutor.corePoolSize", 3); + }); } @Test void taskSchedulerCanBeCustomized() { TaskScheduler customTaskScheduler = mock(TaskScheduler.class); this.contextRunner.withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) - .withBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class, - () -> customTaskScheduler) - .run((context) -> { - assertThat(context).hasSingleBean(TaskScheduler.class); - assertThat(context).getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME) - .isSameAs(customTaskScheduler); - }); + .withBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class, () -> customTaskScheduler) + .run((context) -> { + assertThat(context).hasSingleBean(TaskScheduler.class); + assertThat(context).getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME) + .isSameAs(customTaskScheduler); + }); } @Test @@ -298,21 +299,20 @@ class IntegrationAutoConfigurationTests { "spring.integration.endpoint.throw-exception-on-late-reply=true", "spring.integration.endpoint.read-only-headers=ignoredHeader", "spring.integration.endpoint.no-auto-startup=notStartedEndpoint,_org.springframework.integration.errorLogger") - .run((context) -> { - assertThat(context) - .hasSingleBean(org.springframework.integration.context.IntegrationProperties.class); - org.springframework.integration.context.IntegrationProperties integrationProperties = context - .getBean(org.springframework.integration.context.IntegrationProperties.class); - assertThat(integrationProperties.isChannelsAutoCreate()).isFalse(); - assertThat(integrationProperties.getChannelsMaxUnicastSubscribers()).isEqualTo(2); - assertThat(integrationProperties.getChannelsMaxBroadcastSubscribers()).isEqualTo(3); - assertThat(integrationProperties.isErrorChannelRequireSubscribers()).isFalse(); - assertThat(integrationProperties.isErrorChannelIgnoreFailures()).isFalse(); - assertThat(integrationProperties.isMessagingTemplateThrowExceptionOnLateReply()).isTrue(); - assertThat(integrationProperties.getReadOnlyHeaders()).containsOnly("ignoredHeader"); - assertThat(integrationProperties.getNoAutoStartupEndpoints()).containsOnly("notStartedEndpoint", - "_org.springframework.integration.errorLogger"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(org.springframework.integration.context.IntegrationProperties.class); + org.springframework.integration.context.IntegrationProperties integrationProperties = context + .getBean(org.springframework.integration.context.IntegrationProperties.class); + assertThat(integrationProperties.isChannelsAutoCreate()).isFalse(); + assertThat(integrationProperties.getChannelsMaxUnicastSubscribers()).isEqualTo(2); + assertThat(integrationProperties.getChannelsMaxBroadcastSubscribers()).isEqualTo(3); + assertThat(integrationProperties.isErrorChannelRequireSubscribers()).isFalse(); + assertThat(integrationProperties.isErrorChannelIgnoreFailures()).isFalse(); + assertThat(integrationProperties.isMessagingTemplateThrowExceptionOnLateReply()).isTrue(); + assertThat(integrationProperties.getReadOnlyHeaders()).containsOnly("ignoredHeader"); + assertThat(integrationProperties.getNoAutoStartupEndpoints()).containsOnly("notStartedEndpoint", + "_org.springframework.integration.errorLogger"); + }); } @Test @@ -321,23 +321,23 @@ class IntegrationAutoConfigurationTests { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(org.springframework.integration.context.IntegrationProperties.class); org.springframework.integration.context.IntegrationProperties integrationProperties = context - .getBean(org.springframework.integration.context.IntegrationProperties.class); + .getBean(org.springframework.integration.context.IntegrationProperties.class); assertThat(integrationProperties.isChannelsAutoCreate()) - .isEqualTo(defaultIntegrationProperties.isChannelsAutoCreate()); + .isEqualTo(defaultIntegrationProperties.isChannelsAutoCreate()); assertThat(integrationProperties.getChannelsMaxUnicastSubscribers()) - .isEqualTo(defaultIntegrationProperties.getChannelsMaxBroadcastSubscribers()); + .isEqualTo(defaultIntegrationProperties.getChannelsMaxBroadcastSubscribers()); assertThat(integrationProperties.getChannelsMaxBroadcastSubscribers()) - .isEqualTo(defaultIntegrationProperties.getChannelsMaxBroadcastSubscribers()); + .isEqualTo(defaultIntegrationProperties.getChannelsMaxBroadcastSubscribers()); assertThat(integrationProperties.isErrorChannelRequireSubscribers()) - .isEqualTo(defaultIntegrationProperties.isErrorChannelIgnoreFailures()); + .isEqualTo(defaultIntegrationProperties.isErrorChannelIgnoreFailures()); assertThat(integrationProperties.isErrorChannelIgnoreFailures()) - .isEqualTo(defaultIntegrationProperties.isErrorChannelIgnoreFailures()); + .isEqualTo(defaultIntegrationProperties.isErrorChannelIgnoreFailures()); assertThat(integrationProperties.isMessagingTemplateThrowExceptionOnLateReply()) - .isEqualTo(defaultIntegrationProperties.isMessagingTemplateThrowExceptionOnLateReply()); + .isEqualTo(defaultIntegrationProperties.isMessagingTemplateThrowExceptionOnLateReply()); assertThat(integrationProperties.getReadOnlyHeaders()) - .isEqualTo(defaultIntegrationProperties.getReadOnlyHeaders()); + .isEqualTo(defaultIntegrationProperties.getReadOnlyHeaders()); assertThat(integrationProperties.getNoAutoStartupEndpoints()) - .isEqualTo(defaultIntegrationProperties.getNoAutoStartupEndpoints()); + .isEqualTo(defaultIntegrationProperties.getNoAutoStartupEndpoints()); }); } @@ -345,45 +345,42 @@ class IntegrationAutoConfigurationTests { void integrationGlobalPropertiesUserBeanOverridesAutoConfiguration() { org.springframework.integration.context.IntegrationProperties userIntegrationProperties = new org.springframework.integration.context.IntegrationProperties(); this.contextRunner.withPropertyValues() - .withBean(IntegrationContextUtils.INTEGRATION_GLOBAL_PROPERTIES_BEAN_NAME, - org.springframework.integration.context.IntegrationProperties.class, - () -> userIntegrationProperties) - .run((context) -> { - assertThat(context) - .hasSingleBean(org.springframework.integration.context.IntegrationProperties.class); - assertThat(context.getBean(org.springframework.integration.context.IntegrationProperties.class)) - .isSameAs(userIntegrationProperties); - }); + .withBean(IntegrationContextUtils.INTEGRATION_GLOBAL_PROPERTIES_BEAN_NAME, + org.springframework.integration.context.IntegrationProperties.class, + () -> userIntegrationProperties) + .run((context) -> { + assertThat(context).hasSingleBean(org.springframework.integration.context.IntegrationProperties.class); + assertThat(context.getBean(org.springframework.integration.context.IntegrationProperties.class)) + .isSameAs(userIntegrationProperties); + }); } @Test void integrationGlobalPropertiesFromSpringIntegrationPropertiesFile() { this.contextRunner - .withPropertyValues("spring.integration.channel.auto-create=false", - "spring.integration.endpoint.read-only-headers=ignoredHeader") - .withInitializer((applicationContext) -> new IntegrationPropertiesEnvironmentPostProcessor() - .postProcessEnvironment(applicationContext.getEnvironment(), null)) - .run((context) -> { - assertThat(context) - .hasSingleBean(org.springframework.integration.context.IntegrationProperties.class); - org.springframework.integration.context.IntegrationProperties integrationProperties = context - .getBean(org.springframework.integration.context.IntegrationProperties.class); - assertThat(integrationProperties.isChannelsAutoCreate()).isFalse(); - assertThat(integrationProperties.getReadOnlyHeaders()).containsOnly("ignoredHeader"); - // See META-INF/spring.integration.properties - assertThat(integrationProperties.getNoAutoStartupEndpoints()).containsOnly("testService*"); - }); + .withPropertyValues("spring.integration.channel.auto-create=false", + "spring.integration.endpoint.read-only-headers=ignoredHeader") + .withInitializer((applicationContext) -> new IntegrationPropertiesEnvironmentPostProcessor() + .postProcessEnvironment(applicationContext.getEnvironment(), null)) + .run((context) -> { + assertThat(context).hasSingleBean(org.springframework.integration.context.IntegrationProperties.class); + org.springframework.integration.context.IntegrationProperties integrationProperties = context + .getBean(org.springframework.integration.context.IntegrationProperties.class); + assertThat(integrationProperties.isChannelsAutoCreate()).isFalse(); + assertThat(integrationProperties.getReadOnlyHeaders()).containsOnly("ignoredHeader"); + // See META-INF/spring.integration.properties + assertThat(integrationProperties.getNoAutoStartupEndpoints()).containsOnly("testService*"); + }); } @Test void whenTheUserDefinesTheirOwnIntegrationDatabaseInitializerThenTheAutoConfiguredInitializerBacksOff() { this.contextRunner.withUserConfiguration(CustomIntegrationDatabaseInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .run((context) -> assertThat(context) - .hasSingleBean(IntegrationDataSourceScriptDatabaseInitializer.class) - .doesNotHaveBean("integrationDataSourceScriptDatabaseInitializer") - .hasBean("customInitializer")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(IntegrationDataSourceScriptDatabaseInitializer.class) + .doesNotHaveBean("integrationDataSourceScriptDatabaseInitializer") + .hasBean("customInitializer")); } @Test @@ -391,21 +388,20 @@ class IntegrationAutoConfigurationTests { @SuppressWarnings("deprecation") void whenTheUserDefinesTheirOwnIntegrationDataSourceInitializerThenTheAutoConfiguredInitializerBacksOff() { this.contextRunner.withUserConfiguration(CustomIntegrationDataSourceInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .run((context) -> assertThat(context) - .doesNotHaveBean(IntegrationDataSourceScriptDatabaseInitializer.class) - .hasSingleBean(IntegrationDataSourceInitializer.class).hasBean("customInitializer")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(IntegrationDataSourceScriptDatabaseInitializer.class) + .hasSingleBean(IntegrationDataSourceInitializer.class) + .hasBean("customInitializer")); } @Test void whenTheUserDefinesTheirOwnDatabaseInitializerThenTheAutoConfiguredIntegrationInitializerRemains() { this.contextRunner.withUserConfiguration(CustomDatabaseInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .run((context) -> assertThat(context) - .hasSingleBean(IntegrationDataSourceScriptDatabaseInitializer.class) - .hasBean("customInitializer")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(IntegrationDataSourceScriptDatabaseInitializer.class) + .hasBean("customInitializer")); } @Test @@ -426,80 +422,84 @@ class IntegrationAutoConfigurationTests { @Test void whenCustomPollerPropertiesAreSetThenTheyAreReflectedInPollerMetadata() { this.contextRunner.withUserConfiguration(PollingConsumerConfiguration.class) - .withPropertyValues("spring.integration.poller.cron=* * * ? * *", - "spring.integration.poller.max-messages-per-poll=1", - "spring.integration.poller.receive-timeout=10s") - .run((context) -> { - assertThat(context).hasSingleBean(PollerMetadata.class); - PollerMetadata metadata = context.getBean(PollerMetadata.DEFAULT_POLLER, PollerMetadata.class); - assertThat(metadata.getMaxMessagesPerPoll()).isEqualTo(1L); - assertThat(metadata.getReceiveTimeout()).isEqualTo(10000L); - assertThat(metadata.getTrigger()).asInstanceOf(InstanceOfAssertFactories.type(CronTrigger.class)) - .satisfies((trigger) -> assertThat(trigger.getExpression()).isEqualTo("* * * ? * *")); - }); + .withPropertyValues("spring.integration.poller.cron=* * * ? * *", + "spring.integration.poller.max-messages-per-poll=1", + "spring.integration.poller.receive-timeout=10s") + .run((context) -> { + assertThat(context).hasSingleBean(PollerMetadata.class); + PollerMetadata metadata = context.getBean(PollerMetadata.DEFAULT_POLLER, PollerMetadata.class); + assertThat(metadata.getMaxMessagesPerPoll()).isEqualTo(1L); + assertThat(metadata.getReceiveTimeout()).isEqualTo(10000L); + assertThat(metadata.getTrigger()).asInstanceOf(InstanceOfAssertFactories.type(CronTrigger.class)) + .satisfies((trigger) -> assertThat(trigger.getExpression()).isEqualTo("* * * ? * *")); + }); } @Test void whenPollerPropertiesForMultipleTriggerTypesAreSetThenRefreshFails() { this.contextRunner - .withPropertyValues("spring.integration.poller.cron=* * * ? * *", - "spring.integration.poller.fixed-delay=1s") - .run((context) -> assertThat(context).hasFailed().getFailure() - .hasRootCauseExactlyInstanceOf(MutuallyExclusiveConfigurationPropertiesException.class) - .getRootCause() - .asInstanceOf( - InstanceOfAssertFactories.type(MutuallyExclusiveConfigurationPropertiesException.class)) - .satisfies((ex) -> { - assertThat(ex.getConfiguredNames()).containsExactlyInAnyOrder( - "spring.integration.poller.cron", "spring.integration.poller.fixed-delay"); - assertThat(ex.getMutuallyExclusiveNames()).containsExactlyInAnyOrder( - "spring.integration.poller.cron", "spring.integration.poller.fixed-delay", - "spring.integration.poller.fixed-rate"); - })); + .withPropertyValues("spring.integration.poller.cron=* * * ? * *", + "spring.integration.poller.fixed-delay=1s") + .run((context) -> assertThat(context).hasFailed() + .getFailure() + .hasRootCauseExactlyInstanceOf(MutuallyExclusiveConfigurationPropertiesException.class) + .getRootCause() + .asInstanceOf(InstanceOfAssertFactories.type(MutuallyExclusiveConfigurationPropertiesException.class)) + .satisfies((ex) -> { + assertThat(ex.getConfiguredNames()).containsExactlyInAnyOrder("spring.integration.poller.cron", + "spring.integration.poller.fixed-delay"); + assertThat(ex.getMutuallyExclusiveNames()).containsExactlyInAnyOrder( + "spring.integration.poller.cron", "spring.integration.poller.fixed-delay", + "spring.integration.poller.fixed-rate"); + })); } @Test void whenFixedDelayPollerPropertyIsSetThenItIsReflectedAsFixedDelayPropertyOfPeriodicTrigger() { this.contextRunner.withUserConfiguration(PollingConsumerConfiguration.class) - .withPropertyValues("spring.integration.poller.fixed-delay=5000").run((context) -> { - assertThat(context).hasSingleBean(PollerMetadata.class); - PollerMetadata metadata = context.getBean(PollerMetadata.DEFAULT_POLLER, PollerMetadata.class); - assertThat(metadata.getTrigger()) - .asInstanceOf(InstanceOfAssertFactories.type(PeriodicTrigger.class)) - .satisfies((trigger) -> { - assertThat(trigger.getPeriod()).isEqualTo(5000L); - assertThat(trigger.isFixedRate()).isFalse(); - }); - }); + .withPropertyValues("spring.integration.poller.fixed-delay=5000") + .run((context) -> { + assertThat(context).hasSingleBean(PollerMetadata.class); + PollerMetadata metadata = context.getBean(PollerMetadata.DEFAULT_POLLER, PollerMetadata.class); + assertThat(metadata.getTrigger()).asInstanceOf(InstanceOfAssertFactories.type(PeriodicTrigger.class)) + .satisfies((trigger) -> { + assertThat(trigger.getPeriod()).isEqualTo(5000L); + assertThat(trigger.isFixedRate()).isFalse(); + }); + }); } @Test void whenFixedRatePollerPropertyIsSetThenItIsReflectedAsFixedRatePropertyOfPeriodicTrigger() { this.contextRunner.withUserConfiguration(PollingConsumerConfiguration.class) - .withPropertyValues("spring.integration.poller.fixed-rate=5000").run((context) -> { - assertThat(context).hasSingleBean(PollerMetadata.class); - PollerMetadata metadata = context.getBean(PollerMetadata.DEFAULT_POLLER, PollerMetadata.class); - assertThat(metadata.getTrigger()) - .asInstanceOf(InstanceOfAssertFactories.type(PeriodicTrigger.class)) - .satisfies((trigger) -> { - assertThat(trigger.getPeriod()).isEqualTo(5000L); - assertThat(trigger.isFixedRate()).isTrue(); - }); - }); + .withPropertyValues("spring.integration.poller.fixed-rate=5000") + .run((context) -> { + assertThat(context).hasSingleBean(PollerMetadata.class); + PollerMetadata metadata = context.getBean(PollerMetadata.DEFAULT_POLLER, PollerMetadata.class); + assertThat(metadata.getTrigger()).asInstanceOf(InstanceOfAssertFactories.type(PeriodicTrigger.class)) + .satisfies((trigger) -> { + assertThat(trigger.getPeriod()).isEqualTo(5000L); + assertThat(trigger.isFixedRate()).isTrue(); + }); + }); } @Test void integrationManagementLoggingIsEnabledByDefault() { - this.contextRunner.withBean(DirectChannel.class, DirectChannel::new).run((context) -> assertThat(context) - .getBean(DirectChannel.class).extracting(DirectChannel::isLoggingEnabled).isEqualTo(true)); + this.contextRunner.withBean(DirectChannel.class, DirectChannel::new) + .run((context) -> assertThat(context).getBean(DirectChannel.class) + .extracting(DirectChannel::isLoggingEnabled) + .isEqualTo(true)); } @Test void integrationManagementLoggingCanBeDisabled() { this.contextRunner.withPropertyValues("spring.integration.management.defaultLoggingEnabled=false") - .withBean(DirectChannel.class, DirectChannel::new).run((context) -> assertThat(context) - .getBean(DirectChannel.class).extracting(DirectChannel::isLoggingEnabled).isEqualTo(false)); + .withBean(DirectChannel.class, DirectChannel::new) + .run((context) -> assertThat(context).getBean(DirectChannel.class) + .extracting(DirectChannel::isLoggingEnabled) + .isEqualTo(false)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationDataSourceScriptDatabaseInitializerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationDataSourceScriptDatabaseInitializerTests.java index 8ee28ad832..20e89e4741 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationDataSourceScriptDatabaseInitializerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationDataSourceScriptDatabaseInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ class IntegrationDataSourceScriptDatabaseInitializerTests { DatabaseInitializationSettings settings = IntegrationDataSourceScriptDatabaseInitializer.getSettings(dataSource, properties.getJdbc()); assertThat(settings.getSchemaLocations()) - .containsOnly("classpath:org/springframework/integration/jdbc/schema-test.sql"); + .containsOnly("classpath:org/springframework/integration/jdbc/schema-test.sql"); then(dataSource).shouldHaveNoInteractions(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationPropertiesEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationPropertiesEnvironmentPostProcessorTests.java index d5961921ec..292163108e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationPropertiesEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationPropertiesEnvironmentPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,8 +56,9 @@ class IntegrationPropertiesEnvironmentPostProcessorTests { @Test void postProcessEnvironmentAddPropertySourceLast() { ConfigurableEnvironment environment = new StandardEnvironment(); - environment.getPropertySources().addLast(new MapPropertySource("test", - Collections.singletonMap("spring.integration.endpoint.no-auto-startup", "another*"))); + environment.getPropertySources() + .addLast(new MapPropertySource("test", + Collections.singletonMap("spring.integration.endpoint.no-auto-startup", "another*"))); new IntegrationPropertiesEnvironmentPostProcessor().postProcessEnvironment(environment, mock(SpringApplication.class)); assertThat(environment.getPropertySources().contains("META-INF/spring.integration.properties")).isTrue(); @@ -69,9 +70,10 @@ class IntegrationPropertiesEnvironmentPostProcessorTests { ConfigurableEnvironment environment = new StandardEnvironment(); ClassPathResource unknown = new ClassPathResource("does-not-exist.properties", getClass()); assertThatThrownBy(() -> new IntegrationPropertiesEnvironmentPostProcessor() - .registerIntegrationPropertiesPropertySource(environment, unknown)) - .isInstanceOf(IllegalStateException.class).hasCauseInstanceOf(FileNotFoundException.class) - .hasMessageContaining(unknown.toString()); + .registerIntegrationPropertiesPropertySource(environment, unknown)) + .isInstanceOf(IllegalStateException.class) + .hasCauseInstanceOf(FileNotFoundException.class) + .hasMessageContaining(unknown.toString()); } @Test @@ -81,17 +83,17 @@ class IntegrationPropertiesEnvironmentPostProcessorTests { new ClassPathResource("spring.integration.properties", getClass())); assertThat(environment.getProperty("spring.integration.channel.auto-create", Boolean.class)).isFalse(); assertThat(environment.getProperty("spring.integration.channel.max-unicast-subscribers", Integer.class)) - .isEqualTo(4); + .isEqualTo(4); assertThat(environment.getProperty("spring.integration.channel.max-broadcast-subscribers", Integer.class)) - .isEqualTo(6); + .isEqualTo(6); assertThat(environment.getProperty("spring.integration.error.require-subscribers", Boolean.class)).isFalse(); assertThat(environment.getProperty("spring.integration.error.ignore-failures", Boolean.class)).isFalse(); assertThat(environment.getProperty("spring.integration.endpoint.throw-exception-on-late-reply", Boolean.class)) - .isTrue(); + .isTrue(); assertThat(environment.getProperty("spring.integration.endpoint.read-only-headers", String.class)) - .isEqualTo("header1,header2"); + .isEqualTo("header1,header2"); assertThat(environment.getProperty("spring.integration.endpoint.no-auto-startup", String.class)) - .isEqualTo("testService,anotherService"); + .isEqualTo("testService,anotherService"); } @Test @@ -105,11 +107,11 @@ class IntegrationPropertiesEnvironmentPostProcessorTests { assertThat(ps).isNotNull().isInstanceOf(OriginLookup.class); OriginLookup originLookup = (OriginLookup) ps; assertThat(originLookup.getOrigin("spring.integration.channel.auto-create")) - .satisfies(textOrigin(resource, 0, 39)); + .satisfies(textOrigin(resource, 0, 39)); assertThat(originLookup.getOrigin("spring.integration.channel.max-unicast-subscribers")) - .satisfies(textOrigin(resource, 1, 50)); + .satisfies(textOrigin(resource, 1, 50)); assertThat(originLookup.getOrigin("spring.integration.channel.max-broadcast-subscribers")) - .satisfies(textOrigin(resource, 2, 52)); + .satisfies(textOrigin(resource, 2, 52)); } private Consumer textOrigin(Resource resource, int line, int column) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/Jackson211AutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/Jackson211AutoConfigurationTests.java index 1abae5786a..4b4105476e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/Jackson211AutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/Jackson211AutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,10 +48,10 @@ class Jackson211AutoConfigurationTests extends JacksonAutoConfigurationTests { void customPropertyNamingStrategyClass() { this.contextRunner.withPropertyValues( "spring.jackson.property-naming-strategy:com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(mapper.getPropertyNamingStrategy().getClass().getName()).isEqualTo(STRATEGY_CLASS_NAME); - }); + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(mapper.getPropertyNamingStrategy().getClass().getName()).isEqualTo(STRATEGY_CLASS_NAME); + }); } // ConstructorDetector only available as of Jackson 2.12 diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java index 894583bb14..f6c5f149b2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,16 +81,16 @@ import static org.mockito.Mockito.mock; class JacksonAutoConfigurationTests { protected final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)); @Test void doubleModuleRegistration() { this.contextRunner.withUserConfiguration(DoubleModulesConfig.class) - .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(mapper.writeValueAsString(new Foo())).isEqualTo("{\"foo\":\"bar\"}"); - }); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(mapper.writeValueAsString(new Foo())).isEqualTo("{\"foo\":\"bar\"}"); + }); } @Test @@ -99,7 +99,7 @@ class JacksonAutoConfigurationTests { assertThat(context).hasSingleBean(JsonMixinModule.class); JsonMixinModule module = context.getBean(JsonMixinModule.class); assertThat(module).extracting("basePackages", InstanceOfAssertFactories.list(String.class)) - .containsExactly(MixinConfiguration.class.getPackage().getName()); + .containsExactly(MixinConfiguration.class.getPackage().getName()); }); } @@ -125,10 +125,10 @@ class JacksonAutoConfigurationTests { void customDateFormatClass() { this.contextRunner.withPropertyValues( "spring.jackson.date-format:org.springframework.boot.autoconfigure.jackson.JacksonAutoConfigurationTests.MyDateFormat") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class); - }); + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class); + }); } @Test @@ -151,10 +151,10 @@ class JacksonAutoConfigurationTests { void customPropertyNamingStrategyClass() { this.contextRunner.withPropertyValues( "spring.jackson.property-naming-strategy:com.fasterxml.jackson.databind.PropertyNamingStrategies.SnakeCaseStrategy") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(mapper.getPropertyNamingStrategy()).isInstanceOf(SnakeCaseStrategy.class); - }); + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(mapper.getPropertyNamingStrategy()).isInstanceOf(SnakeCaseStrategy.class); + }); } @Test @@ -163,58 +163,55 @@ class JacksonAutoConfigurationTests { ObjectMapper mapper = context.getBean(ObjectMapper.class); assertThat(SerializationFeature.INDENT_OUTPUT.enabledByDefault()).isFalse(); assertThat(mapper.getSerializationConfig() - .hasSerializationFeatures(SerializationFeature.INDENT_OUTPUT.getMask())).isTrue(); + .hasSerializationFeatures(SerializationFeature.INDENT_OUTPUT.getMask())).isTrue(); }); } @Test void disableSerializationFeature() { this.contextRunner.withPropertyValues("spring.jackson.serialization.write_dates_as_timestamps:false") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.enabledByDefault()).isTrue(); - assertThat(mapper.getSerializationConfig() - .hasSerializationFeatures(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.getMask())) - .isFalse(); - }); + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.enabledByDefault()).isTrue(); + assertThat(mapper.getSerializationConfig() + .hasSerializationFeatures(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.getMask())).isFalse(); + }); } @Test void enableDeserializationFeature() { this.contextRunner.withPropertyValues("spring.jackson.deserialization.use_big_decimal_for_floats:true") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.enabledByDefault()).isFalse(); - assertThat(mapper.getDeserializationConfig() - .hasDeserializationFeatures(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.getMask())) - .isTrue(); - }); + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.enabledByDefault()).isFalse(); + assertThat(mapper.getDeserializationConfig() + .hasDeserializationFeatures(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.getMask())).isTrue(); + }); } @Test void disableDeserializationFeature() { this.contextRunner.withPropertyValues("spring.jackson.deserialization.fail-on-unknown-properties:false") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()).isTrue(); - assertThat(mapper.getDeserializationConfig() - .hasDeserializationFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.getMask())) - .isFalse(); - }); + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()).isTrue(); + assertThat(mapper.getDeserializationConfig() + .hasDeserializationFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.getMask())).isFalse(); + }); } @Test void enableMapperFeature() { this.contextRunner.withPropertyValues("spring.jackson.mapper.require_setters_for_getters:true") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.enabledByDefault()).isFalse(); - - assertThat(mapper.getSerializationConfig().isEnabled(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS)) - .isTrue(); - assertThat(mapper.getDeserializationConfig().isEnabled(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS)) - .isTrue(); - }); + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.enabledByDefault()).isFalse(); + + assertThat(mapper.getSerializationConfig().isEnabled(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS)) + .isTrue(); + assertThat(mapper.getDeserializationConfig().isEnabled(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS)) + .isTrue(); + }); } @Test @@ -248,12 +245,12 @@ class JacksonAutoConfigurationTests { @Test void enableGeneratorFeature() { this.contextRunner.withPropertyValues("spring.jackson.generator.strict_duplicate_detection:true") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - JsonGenerator.Feature feature = JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION; - assertThat(feature.enabledByDefault()).isFalse(); - assertThat(mapper.getFactory().isEnabled(feature)).isTrue(); - }); + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + JsonGenerator.Feature feature = JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION; + assertThat(feature.enabledByDefault()).isFalse(); + assertThat(mapper.getFactory().isEnabled(feature)).isTrue(); + }); } @Test @@ -277,7 +274,7 @@ class JacksonAutoConfigurationTests { assertThat(mapper.getSerializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()).isTrue(); assertThat(mapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) - .isFalse(); + .isFalse(); }); } @@ -295,7 +292,7 @@ class JacksonAutoConfigurationTests { this.contextRunner.run((context) -> { ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class).build(); assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion().getValueInclusion()) - .isEqualTo(JsonInclude.Include.USE_DEFAULTS); + .isEqualTo(JsonInclude.Include.USE_DEFAULTS); }); } @@ -304,18 +301,18 @@ class JacksonAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.jackson.default-property-inclusion:non_null").run((context) -> { ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class).build(); assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion().getValueInclusion()) - .isEqualTo(JsonInclude.Include.NON_NULL); + .isEqualTo(JsonInclude.Include.NON_NULL); }); } @Test void customTimeZoneFormattingADate() { this.contextRunner.withPropertyValues("spring.jackson.time-zone:GMT+10", "spring.jackson.date-format:z") - .run((context) -> { - ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class).build(); - Date date = new Date(1436966242231L); - assertThat(objectMapper.writeValueAsString(date)).isEqualTo("\"GMT+10:00\""); - }); + .run((context) -> { + ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class).build(); + Date date = new Date(1436966242231L); + assertThat(objectMapper.writeValueAsString(date)).isEqualTo("\"GMT+10:00\""); + }); } @Test @@ -332,8 +329,9 @@ class JacksonAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.jackson.default-leniency:false").run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); assertThatThrownBy(() -> mapper.readValue("{\"birthDate\": \"2010-12-30\"}", Person.class)) - .isInstanceOf(InvalidFormatException.class).hasMessageContaining("expected format") - .hasMessageContaining("yyyyMMdd"); + .isInstanceOf(InvalidFormatException.class) + .hasMessageContaining("expected format") + .hasMessageContaining("yyyyMMdd"); }); } @@ -362,13 +360,13 @@ class JacksonAutoConfigurationTests { @Test void constructorDetectorWithUsePropertiesBasedStrategy() { this.contextRunner.withPropertyValues("spring.jackson.constructor-detector=use-properties-based") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - ConstructorDetector cd = mapper.getDeserializationConfig().getConstructorDetector(); - assertThat(cd.singleArgMode()).isEqualTo(SingleArgConstructor.PROPERTIES); - assertThat(cd.requireCtorAnnotation()).isFalse(); - assertThat(cd.allowJDKTypeConstructors()).isFalse(); - }); + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + ConstructorDetector cd = mapper.getDeserializationConfig().getConstructorDetector(); + assertThat(cd.singleArgMode()).isEqualTo(SingleArgConstructor.PROPERTIES); + assertThat(cd.requireCtorAnnotation()).isFalse(); + assertThat(cd.allowJDKTypeConstructors()).isFalse(); + }); } @Test @@ -424,14 +422,14 @@ class JacksonAutoConfigurationTests { @Test void writeWithVisibility() { this.contextRunner - .withPropertyValues("spring.jackson.visibility.getter:none", "spring.jackson.visibility.field:any") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - String json = mapper.writeValueAsString(new VisibilityBean()); - assertThat(json).contains("property1"); - assertThat(json).contains("property2"); - assertThat(json).doesNotContain("property3"); - }); + .withPropertyValues("spring.jackson.visibility.getter:none", "spring.jackson.visibility.field:any") + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + String json = mapper.writeValueAsString(new VisibilityBean()); + assertThat(json).contains("property1"); + assertThat(json).contains("property2"); + assertThat(json).doesNotContain("property3"); + }); } @Test @@ -447,9 +445,11 @@ class JacksonAutoConfigurationTests { private void assertParameterNamesModuleCreatorBinding(Mode expectedMode, Class... configClasses) { this.contextRunner.withUserConfiguration(configClasses).run((context) -> { DeserializationConfig deserializationConfig = context.getBean(ObjectMapper.class) - .getDeserializationConfig(); + .getDeserializationConfig(); AnnotationIntrospector annotationIntrospector = deserializationConfig.getAnnotationIntrospector() - .allIntrospectors().iterator().next(); + .allIntrospectors() + .iterator() + .next(); assertThat(annotationIntrospector).hasFieldOrPropertyWithValue("creatorBinding", expectedMode); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java index c94f25503d..181eab518d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,8 +64,8 @@ import static org.mockito.Mockito.mock; class DataSourceAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:testdb-" + new Random().nextInt()); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:testdb-" + new Random().nextInt()); @Test void testDefaultDataSourceExists() { @@ -84,21 +84,22 @@ class DataSourceAutoConfigurationTests { @Test void testBadUrl() { this.contextRunner.withPropertyValues("spring.datasource.url:jdbc:not-going-to-work") - .withClassLoader(new DisableEmbeddedDatabaseClassLoader()) - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); + .withClassLoader(new DisableEmbeddedDatabaseClassLoader()) + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); } @Test void testBadDriverClass() { this.contextRunner.withPropertyValues("spring.datasource.driverClassName:org.none.jdbcDriver") - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("org.none.jdbcDriver")); + .run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("org.none.jdbcDriver")); } @Test void datasourceWhenConnectionFactoryPresentIsNotAutoConfigured() { this.contextRunner.withBean(ConnectionFactory.class, () -> mock(ConnectionFactory.class)) - .run((context) -> assertThat(context).doesNotHaveBean(DataSource.class)); + .run((context) -> assertThat(context).doesNotHaveBean(DataSource.class)); } @Test @@ -159,20 +160,22 @@ class DataSourceAutoConfigurationTests { @Test @SuppressWarnings("resource") void testEmbeddedTypeDefaultsUsername() { - this.contextRunner.withPropertyValues("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", - "spring.datasource.url:jdbc:hsqldb:mem:testdb").run((context) -> { - DataSource bean = context.getBean(DataSource.class); - HikariDataSource pool = (HikariDataSource) bean; - assertThat(pool.getDriverClassName()).isEqualTo("org.hsqldb.jdbcDriver"); - assertThat(pool.getUsername()).isEqualTo("sa"); - }); + this.contextRunner + .withPropertyValues("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", + "spring.datasource.url:jdbc:hsqldb:mem:testdb") + .run((context) -> { + DataSource bean = context.getBean(DataSource.class); + HikariDataSource pool = (HikariDataSource) bean; + assertThat(pool.getDriverClassName()).isEqualTo("org.hsqldb.jdbcDriver"); + assertThat(pool.getUsername()).isEqualTo("sa"); + }); } @Test void dataSourceWhenNoConnectionPoolsAreAvailableWithUrlDoesNotCreateDataSource() { this.contextRunner.with(hideConnectionPools()) - .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:testdb") - .run((context) -> assertThat(context).doesNotHaveBean(DataSource.class)); + .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:testdb") + .run((context) -> assertThat(context).doesNotHaveBean(DataSource.class)); } /** @@ -182,19 +185,19 @@ class DataSourceAutoConfigurationTests { @Test void dataSourceWhenNoConnectionPoolsAreAvailableWithUrlAndTypeCreatesDataSource() { this.contextRunner.with(hideConnectionPools()) - .withPropertyValues("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", - "spring.datasource.url:jdbc:hsqldb:mem:testdb", - "spring.datasource.type:" + SimpleDriverDataSource.class.getName()) - .run(this::containsOnlySimpleDriverDataSource); + .withPropertyValues("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", + "spring.datasource.url:jdbc:hsqldb:mem:testdb", + "spring.datasource.type:" + SimpleDriverDataSource.class.getName()) + .run(this::containsOnlySimpleDriverDataSource); } @Test void explicitTypeSupportedDataSource() { this.contextRunner - .withPropertyValues("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", - "spring.datasource.url:jdbc:hsqldb:mem:testdb", - "spring.datasource.type:" + SimpleDriverDataSource.class.getName()) - .run(this::containsOnlySimpleDriverDataSource); + .withPropertyValues("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", + "spring.datasource.url:jdbc:hsqldb:mem:testdb", + "spring.datasource.type:" + SimpleDriverDataSource.class.getName()) + .run(this::containsOnlySimpleDriverDataSource); } private void containsOnlySimpleDriverDataSource(AssertableApplicationContext context) { @@ -204,38 +207,41 @@ class DataSourceAutoConfigurationTests { @Test void testExplicitDriverClassClearsUsername() { - this.contextRunner.withPropertyValues("spring.datasource.driverClassName:" + DatabaseTestDriver.class.getName(), - "spring.datasource.url:jdbc:foo://localhost").run((context) -> { - assertThat(context).hasSingleBean(DataSource.class); - HikariDataSource dataSource = context.getBean(HikariDataSource.class); - assertThat(dataSource.getDriverClassName()).isEqualTo(DatabaseTestDriver.class.getName()); - assertThat(dataSource.getUsername()).isNull(); - }); + this.contextRunner + .withPropertyValues("spring.datasource.driverClassName:" + DatabaseTestDriver.class.getName(), + "spring.datasource.url:jdbc:foo://localhost") + .run((context) -> { + assertThat(context).hasSingleBean(DataSource.class); + HikariDataSource dataSource = context.getBean(HikariDataSource.class); + assertThat(dataSource.getDriverClassName()).isEqualTo(DatabaseTestDriver.class.getName()); + assertThat(dataSource.getUsername()).isNull(); + }); } @Test void testDefaultDataSourceCanBeOverridden() { this.contextRunner.withUserConfiguration(TestDataSourceConfiguration.class) - .run((context) -> assertThat(context).getBean(DataSource.class).isInstanceOf(BasicDataSource.class)); + .run((context) -> assertThat(context).getBean(DataSource.class).isInstanceOf(BasicDataSource.class)); } @Test void whenThereIsAUserProvidedDataSourceAnUnresolvablePlaceholderDoesNotCauseAProblem() { this.contextRunner.withUserConfiguration(TestDataSourceConfiguration.class) - .withPropertyValues("spring.datasource.url:${UNRESOLVABLE_PLACEHOLDER}") - .run((context) -> assertThat(context).getBean(DataSource.class).isInstanceOf(BasicDataSource.class)); + .withPropertyValues("spring.datasource.url:${UNRESOLVABLE_PLACEHOLDER}") + .run((context) -> assertThat(context).getBean(DataSource.class).isInstanceOf(BasicDataSource.class)); } @Test void whenThereIsAnEmptyUserProvidedDataSource() { - this.contextRunner.with(hideConnectionPools()).withPropertyValues("spring.datasource.url:") - .run((context) -> assertThat(context).getBean(DataSource.class).isInstanceOf(EmbeddedDatabase.class)); + this.contextRunner.with(hideConnectionPools()) + .withPropertyValues("spring.datasource.url:") + .run((context) -> assertThat(context).getBean(DataSource.class).isInstanceOf(EmbeddedDatabase.class)); } @Test void whenNoInitializationRelatedSpringDataSourcePropertiesAreConfiguredThenInitializationBacksOff() { this.contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(DataSourceScriptDatabaseInitializer.class)); + .run((context) -> assertThat(context).doesNotHaveBean(DataSourceScriptDatabaseInitializer.class)); } private static Function hideConnectionPools() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfigurationTests.java index 175925fa10..1c90553c98 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,26 +51,25 @@ import static org.assertj.core.api.Assertions.assertThat; class DataSourceJmxConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withPropertyValues("spring.datasource.url=jdbc:hsqldb:mem:test-" + UUID.randomUUID()) - .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, DataSourceAutoConfiguration.class)); + .withPropertyValues("spring.datasource.url=jdbc:hsqldb:mem:test-" + UUID.randomUUID()) + .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, DataSourceAutoConfiguration.class)); @Test void hikariAutoConfiguredCanUseRegisterMBeans() { String poolName = UUID.randomUUID().toString(); this.contextRunner - .withPropertyValues("spring.jmx.enabled=true", - "spring.datasource.type=" + HikariDataSource.class.getName(), - "spring.datasource.name=" + poolName, "spring.datasource.hikari.register-mbeans=true") - .run((context) -> { - assertThat(context).hasSingleBean(HikariDataSource.class); - HikariDataSource hikariDataSource = context.getBean(HikariDataSource.class); - assertThat(hikariDataSource.isRegisterMbeans()).isTrue(); - // Ensure that the pool has been initialized, triggering MBean - // registration - hikariDataSource.getConnection().close(); - MBeanServer mBeanServer = context.getBean(MBeanServer.class); - validateHikariMBeansRegistration(mBeanServer, poolName, true); - }); + .withPropertyValues("spring.jmx.enabled=true", "spring.datasource.type=" + HikariDataSource.class.getName(), + "spring.datasource.name=" + poolName, "spring.datasource.hikari.register-mbeans=true") + .run((context) -> { + assertThat(context).hasSingleBean(HikariDataSource.class); + HikariDataSource hikariDataSource = context.getBean(HikariDataSource.class); + assertThat(hikariDataSource.isRegisterMbeans()).isTrue(); + // Ensure that the pool has been initialized, triggering MBean + // registration + hikariDataSource.getConnection().close(); + MBeanServer mBeanServer = context.getBean(MBeanServer.class); + validateHikariMBeansRegistration(mBeanServer, poolName, true); + }); } @Test @@ -78,103 +77,108 @@ class DataSourceJmxConfigurationTests { MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); Set existingInstances = mBeanServer.queryMBeans(new ObjectName("com.zaxxer.hikari:type=*"), null); - this.contextRunner.withPropertyValues("spring.datasource.type=" + HikariDataSource.class.getName(), - "spring.datasource.hikari.register-mbeans=true").run((context) -> { - assertThat(context).hasSingleBean(HikariDataSource.class); - HikariDataSource hikariDataSource = context.getBean(HikariDataSource.class); - assertThat(hikariDataSource.isRegisterMbeans()).isTrue(); - // Ensure that the pool has been initialized, triggering MBean - // registration - hikariDataSource.getConnection().close(); - // We can't rely on the number of MBeans so we're checking that the - // pool and pool config MBeans were registered - assertThat(mBeanServer.queryMBeans(new ObjectName("com.zaxxer.hikari:type=*"), null).size()) - .isEqualTo(existingInstances.size() + 2); - }); + this.contextRunner + .withPropertyValues("spring.datasource.type=" + HikariDataSource.class.getName(), + "spring.datasource.hikari.register-mbeans=true") + .run((context) -> { + assertThat(context).hasSingleBean(HikariDataSource.class); + HikariDataSource hikariDataSource = context.getBean(HikariDataSource.class); + assertThat(hikariDataSource.isRegisterMbeans()).isTrue(); + // Ensure that the pool has been initialized, triggering MBean + // registration + hikariDataSource.getConnection().close(); + // We can't rely on the number of MBeans so we're checking that the + // pool and pool config MBeans were registered + assertThat(mBeanServer.queryMBeans(new ObjectName("com.zaxxer.hikari:type=*"), null).size()) + .isEqualTo(existingInstances.size() + 2); + }); } @Test void hikariAutoConfiguredUsesJmxFlag() { String poolName = UUID.randomUUID().toString(); - this.contextRunner.withPropertyValues("spring.datasource.type=" + HikariDataSource.class.getName(), - "spring.jmx.enabled=false", "spring.datasource.name=" + poolName, - "spring.datasource.hikari.register-mbeans=true").run((context) -> { - assertThat(context).hasSingleBean(HikariDataSource.class); - HikariDataSource hikariDataSource = context.getBean(HikariDataSource.class); - assertThat(hikariDataSource.isRegisterMbeans()).isTrue(); - // Ensure that the pool has been initialized, triggering MBean - // registration - hikariDataSource.getConnection().close(); - // Hikari can still register mBeans - validateHikariMBeansRegistration(ManagementFactory.getPlatformMBeanServer(), poolName, true); - }); + this.contextRunner + .withPropertyValues("spring.datasource.type=" + HikariDataSource.class.getName(), + "spring.jmx.enabled=false", "spring.datasource.name=" + poolName, + "spring.datasource.hikari.register-mbeans=true") + .run((context) -> { + assertThat(context).hasSingleBean(HikariDataSource.class); + HikariDataSource hikariDataSource = context.getBean(HikariDataSource.class); + assertThat(hikariDataSource.isRegisterMbeans()).isTrue(); + // Ensure that the pool has been initialized, triggering MBean + // registration + hikariDataSource.getConnection().close(); + // Hikari can still register mBeans + validateHikariMBeansRegistration(ManagementFactory.getPlatformMBeanServer(), poolName, true); + }); } @Test void hikariProxiedCanUseRegisterMBeans() { String poolName = UUID.randomUUID().toString(); this.contextRunner.withUserConfiguration(DataSourceProxyConfiguration.class) - .withPropertyValues("spring.jmx.enabled=true", - "spring.datasource.type=" + HikariDataSource.class.getName(), - "spring.datasource.name=" + poolName, "spring.datasource.hikari.register-mbeans=true") - .run((context) -> { - assertThat(context).hasSingleBean(javax.sql.DataSource.class); - HikariDataSource hikariDataSource = context.getBean(javax.sql.DataSource.class) - .unwrap(HikariDataSource.class); - assertThat(hikariDataSource.isRegisterMbeans()).isTrue(); - // Ensure that the pool has been initialized, triggering MBean - // registration - hikariDataSource.getConnection().close(); - MBeanServer mBeanServer = context.getBean(MBeanServer.class); - validateHikariMBeansRegistration(mBeanServer, poolName, true); - }); + .withPropertyValues("spring.jmx.enabled=true", "spring.datasource.type=" + HikariDataSource.class.getName(), + "spring.datasource.name=" + poolName, "spring.datasource.hikari.register-mbeans=true") + .run((context) -> { + assertThat(context).hasSingleBean(javax.sql.DataSource.class); + HikariDataSource hikariDataSource = context.getBean(javax.sql.DataSource.class) + .unwrap(HikariDataSource.class); + assertThat(hikariDataSource.isRegisterMbeans()).isTrue(); + // Ensure that the pool has been initialized, triggering MBean + // registration + hikariDataSource.getConnection().close(); + MBeanServer mBeanServer = context.getBean(MBeanServer.class); + validateHikariMBeansRegistration(mBeanServer, poolName, true); + }); } private void validateHikariMBeansRegistration(MBeanServer mBeanServer, String poolName, boolean expected) throws MalformedObjectNameException { assertThat(mBeanServer.isRegistered(new ObjectName("com.zaxxer.hikari:type=Pool (" + poolName + ")"))) - .isEqualTo(expected); + .isEqualTo(expected); assertThat(mBeanServer.isRegistered(new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + poolName + ")"))) - .isEqualTo(expected); + .isEqualTo(expected); } @Test void tomcatDoesNotExposeMBeanPoolByDefault() { this.contextRunner.withPropertyValues("spring.datasource.type=" + DataSource.class.getName()) - .run((context) -> assertThat(context).doesNotHaveBean(ConnectionPool.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ConnectionPool.class)); } @Test void tomcatAutoConfiguredCanExposeMBeanPool() { - this.contextRunner.withPropertyValues("spring.datasource.type=" + DataSource.class.getName(), - "spring.datasource.tomcat.jmx-enabled=true").run((context) -> { - assertThat(context).hasBean("dataSourceMBean"); - assertThat(context).hasSingleBean(ConnectionPool.class); - assertThat(context.getBean(DataSourceProxy.class).createPool().getJmxPool()) - .isSameAs(context.getBean(ConnectionPool.class)); - }); + this.contextRunner + .withPropertyValues("spring.datasource.type=" + DataSource.class.getName(), + "spring.datasource.tomcat.jmx-enabled=true") + .run((context) -> { + assertThat(context).hasBean("dataSourceMBean"); + assertThat(context).hasSingleBean(ConnectionPool.class); + assertThat(context.getBean(DataSourceProxy.class).createPool().getJmxPool()) + .isSameAs(context.getBean(ConnectionPool.class)); + }); } @Test void tomcatProxiedCanExposeMBeanPool() { this.contextRunner.withUserConfiguration(DataSourceProxyConfiguration.class) - .withPropertyValues("spring.datasource.type=" + DataSource.class.getName(), - "spring.datasource.tomcat.jmx-enabled=true") - .run((context) -> { - assertThat(context).hasBean("dataSourceMBean"); - assertThat(context).getBean("dataSourceMBean").isInstanceOf(ConnectionPool.class); - }); + .withPropertyValues("spring.datasource.type=" + DataSource.class.getName(), + "spring.datasource.tomcat.jmx-enabled=true") + .run((context) -> { + assertThat(context).hasBean("dataSourceMBean"); + assertThat(context).getBean("dataSourceMBean").isInstanceOf(ConnectionPool.class); + }); } @Test void tomcatDelegateCanExposeMBeanPool() { this.contextRunner.withUserConfiguration(DataSourceDelegateConfiguration.class) - .withPropertyValues("spring.datasource.type=" + DataSource.class.getName(), - "spring.datasource.tomcat.jmx-enabled=true") - .run((context) -> { - assertThat(context).hasBean("dataSourceMBean"); - assertThat(context).getBean("dataSourceMBean").isInstanceOf(ConnectionPool.class); - }); + .withPropertyValues("spring.datasource.type=" + DataSource.class.getName(), + "spring.datasource.tomcat.jmx-enabled=true") + .run((context) -> { + assertThat(context).hasBean("dataSourceMBean"); + assertThat(context).getBean("dataSourceMBean").isInstanceOf(ConnectionPool.class); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java index 84a1de85af..b1e5406663 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,7 +56,7 @@ class DataSourceJsonSerializationTests { void serializerFactory() throws Exception { DataSource dataSource = new DataSource(); SerializerFactory factory = BeanSerializerFactory.instance - .withSerializerModifier(new GenericSerializerModifier()); + .withSerializerModifier(new GenericSerializerModifier()); ObjectMapper mapper = new ObjectMapper(); mapper.setSerializerFactory(factory); String value = mapper.writeValueAsString(dataSource); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java index 8df12bedf6..e05f54892e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,7 +66,8 @@ class DataSourcePropertiesTests { properties.setBeanClassLoader(new FilteredClassLoader("org.h2", "org.apache.derby", "org.hsqldb")); properties.afterPropertiesSet(); assertThatExceptionOfType(DataSourceProperties.DataSourceBeanCreationException.class) - .isThrownBy(properties::determineUrl).withMessageContaining("Failed to determine suitable jdbc url"); + .isThrownBy(properties::determineUrl) + .withMessageContaining("Failed to determine suitable jdbc url"); } @Test @@ -84,7 +85,8 @@ class DataSourcePropertiesTests { properties.setGenerateUniqueName(false); properties.setEmbeddedDatabaseConnection(EmbeddedDatabaseConnection.NONE); assertThatExceptionOfType(DataSourceProperties.DataSourceBeanCreationException.class) - .isThrownBy(properties::determineUrl).withMessageContaining("Failed to determine suitable jdbc url"); + .isThrownBy(properties::determineUrl) + .withMessageContaining("Failed to determine suitable jdbc url"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java index 9d9d42e25f..a469c0495a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,9 +42,9 @@ import static org.mockito.Mockito.mock; class DataSourceTransactionManagerAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(TransactionAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:test-" + UUID.randomUUID()); + .withConfiguration(AutoConfigurations.of(TransactionAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:test-" + UUID.randomUUID()); @Test void transactionManagerWithoutDataSourceIsNotConfigured() { @@ -54,63 +54,61 @@ class DataSourceTransactionManagerAutoConfigurationTests { @Test void transactionManagerWithExistingDataSourceIsConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .run((context) -> { - assertThat(context).hasSingleBean(TransactionManager.class) - .hasSingleBean(JdbcTransactionManager.class); - assertThat(context.getBean(JdbcTransactionManager.class).getDataSource()) - .isSameAs(context.getBean(DataSource.class)); - }); + .run((context) -> { + assertThat(context).hasSingleBean(TransactionManager.class).hasSingleBean(JdbcTransactionManager.class); + assertThat(context.getBean(JdbcTransactionManager.class).getDataSource()) + .isSameAs(context.getBean(DataSource.class)); + }); } @Test void transactionManagerWithCustomizationIsConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.transaction.default-timeout=1m", - "spring.transaction.rollback-on-commit-failure=true") - .run((context) -> { - assertThat(context).hasSingleBean(TransactionManager.class) - .hasSingleBean(JdbcTransactionManager.class); - JdbcTransactionManager transactionManager = context.getBean(JdbcTransactionManager.class); - assertThat(transactionManager.getDefaultTimeout()).isEqualTo(60); - assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); - }); + .withPropertyValues("spring.transaction.default-timeout=1m", + "spring.transaction.rollback-on-commit-failure=true") + .run((context) -> { + assertThat(context).hasSingleBean(TransactionManager.class).hasSingleBean(JdbcTransactionManager.class); + JdbcTransactionManager transactionManager = context.getBean(JdbcTransactionManager.class); + assertThat(transactionManager.getDefaultTimeout()).isEqualTo(60); + assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); + }); } @Test void transactionManagerWithExistingTransactionManagerIsNotOverridden() { this.contextRunner - .withBean("myTransactionManager", TransactionManager.class, () -> mock(TransactionManager.class)) - .run((context) -> assertThat(context).hasSingleBean(TransactionManager.class) - .hasBean("myTransactionManager")); + .withBean("myTransactionManager", TransactionManager.class, () -> mock(TransactionManager.class)) + .run((context) -> assertThat(context).hasSingleBean(TransactionManager.class) + .hasBean("myTransactionManager")); } @Test // gh-24321 void transactionManagerWithDaoExceptionTranslationDisabled() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.dao.exceptiontranslation.enabled=false") - .run((context) -> assertThat(context.getBean(TransactionManager.class)) - .isExactlyInstanceOf(DataSourceTransactionManager.class)); + .withPropertyValues("spring.dao.exceptiontranslation.enabled=false") + .run((context) -> assertThat(context.getBean(TransactionManager.class)) + .isExactlyInstanceOf(DataSourceTransactionManager.class)); } @Test // gh-24321 void transactionManagerWithDaoExceptionTranslationEnabled() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.dao.exceptiontranslation.enabled=true") - .run((context) -> assertThat(context.getBean(TransactionManager.class)) - .isExactlyInstanceOf(JdbcTransactionManager.class)); + .withPropertyValues("spring.dao.exceptiontranslation.enabled=true") + .run((context) -> assertThat(context.getBean(TransactionManager.class)) + .isExactlyInstanceOf(JdbcTransactionManager.class)); } @Test // gh-24321 void transactionManagerWithDaoExceptionTranslationDefault() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .run((context) -> assertThat(context.getBean(TransactionManager.class)) - .isExactlyInstanceOf(JdbcTransactionManager.class)); + .run((context) -> assertThat(context.getBean(TransactionManager.class)) + .isExactlyInstanceOf(JdbcTransactionManager.class)); } @Test void transactionWithMultipleDataSourcesIsNotConfigured() { this.contextRunner.withUserConfiguration(MultiDataSourceConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(TransactionManager.class)); + .run((context) -> assertThat(context).doesNotHaveBean(TransactionManager.class)); } @Test @@ -118,7 +116,7 @@ class DataSourceTransactionManagerAutoConfigurationTests { this.contextRunner.withUserConfiguration(MultiDataSourceUsingPrimaryConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(TransactionManager.class).hasSingleBean(JdbcTransactionManager.class); assertThat(context.getBean(JdbcTransactionManager.class).getDataSource()) - .isSameAs(context.getBean("test1DataSource")); + .isSameAs(context.getBean("test1DataSource")); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java index ebd28e9cfb..e308663eb3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,8 @@ import static org.assertj.core.api.Assertions.assertThat; class HikariDataSourceConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.datasource.type=" + HikariDataSource.class.getName()); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.datasource.type=" + HikariDataSource.class.getName()); @Test void testDataSourceExists() { @@ -48,25 +48,27 @@ class HikariDataSourceConfigurationTests { @Test void testDataSourcePropertiesOverridden() { - this.contextRunner.withPropertyValues("spring.datasource.hikari.jdbc-url=jdbc:foo//bar/spam", - "spring.datasource.hikari.max-lifetime=1234").run((context) -> { - HikariDataSource ds = context.getBean(HikariDataSource.class); - assertThat(ds.getJdbcUrl()).isEqualTo("jdbc:foo//bar/spam"); - assertThat(ds.getMaxLifetime()).isEqualTo(1234); - }); + this.contextRunner + .withPropertyValues("spring.datasource.hikari.jdbc-url=jdbc:foo//bar/spam", + "spring.datasource.hikari.max-lifetime=1234") + .run((context) -> { + HikariDataSource ds = context.getBean(HikariDataSource.class); + assertThat(ds.getJdbcUrl()).isEqualTo("jdbc:foo//bar/spam"); + assertThat(ds.getMaxLifetime()).isEqualTo(1234); + }); } @Test void testDataSourceGenericPropertiesOverridden() { this.contextRunner - .withPropertyValues( - "spring.datasource.hikari.data-source-properties.dataSourceClassName=org.h2.JDBCDataSource") - .run((context) -> { - HikariDataSource ds = context.getBean(HikariDataSource.class); - assertThat(ds.getDataSourceProperties().getProperty("dataSourceClassName")) - .isEqualTo("org.h2.JDBCDataSource"); - - }); + .withPropertyValues( + "spring.datasource.hikari.data-source-properties.dataSourceClassName=org.h2.JDBCDataSource") + .run((context) -> { + HikariDataSource ds = context.getBean(HikariDataSource.class); + assertThat(ds.getDataSourceProperties().getProperty("dataSourceClassName")) + .isEqualTo("org.h2.JDBCDataSource"); + + }); } @Test @@ -89,11 +91,11 @@ class HikariDataSourceConfigurationTests { @Test void poolNameTakesPrecedenceOverName() { this.contextRunner - .withPropertyValues("spring.datasource.name=myDS", "spring.datasource.hikari.pool-name=myHikariDS") - .run((context) -> { - HikariDataSource ds = context.getBean(HikariDataSource.class); - assertThat(ds.getPoolName()).isEqualTo("myHikariDS"); - }); + .withPropertyValues("spring.datasource.name=myDS", "spring.datasource.hikari.pool-name=myHikariDS") + .run((context) -> { + HikariDataSource ds = context.getBean(HikariDataSource.class); + assertThat(ds.getPoolName()).isEqualTo("myHikariDS"); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java index 0937cdfbb3..9dafdc04b7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,15 +40,15 @@ class HikariDriverConfigurationFailureAnalyzerTests { void failureAnalysisIsPerformed() { FailureAnalysis failureAnalysis = performAnalysis(TestConfiguration.class); assertThat(failureAnalysis).isNotNull(); - assertThat(failureAnalysis.getDescription()).isEqualTo( - "Configuration of the Hikari connection pool failed: 'dataSourceClassName' is not supported."); + assertThat(failureAnalysis.getDescription()) + .isEqualTo("Configuration of the Hikari connection pool failed: 'dataSourceClassName' is not supported."); assertThat(failureAnalysis.getAction()).contains("Spring Boot auto-configures only a driver"); } @Test void unrelatedIllegalStateExceptionIsSkipped() { FailureAnalysis failureAnalysis = new HikariDriverConfigurationFailureAnalyzer() - .analyze(new RuntimeException("foo", new IllegalStateException("bar"))); + .analyze(new RuntimeException("foo", new IllegalStateException("bar"))); assertThat(failureAnalysis).isNull(); } @@ -60,9 +60,10 @@ class HikariDriverConfigurationFailureAnalyzerTests { private BeanCreationException createFailure(Class configuration) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.datasource.type=" + HikariDataSource.class.getName(), - "spring.datasource.hikari.data-source-class-name=com.example.Foo", "spring.sql.init.mode=always") - .applyTo(context); + TestPropertyValues + .of("spring.datasource.type=" + HikariDataSource.class.getName(), + "spring.datasource.hikari.data-source-class-name=com.example.Foo", "spring.sql.init.mode=always") + .applyTo(context); context.register(configuration); try { context.refresh(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java index fb4a14d9cd..1c6f3fbb2a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,9 @@ import static org.mockito.Mockito.mock; class JdbcTemplateAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withPropertyValues("spring.datasource.generate-unique-name=true").withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class)); + .withPropertyValues("spring.datasource.generate-unique-name=true") + .withConfiguration( + AutoConfigurations.of(DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class)); @Test void testJdbcTemplateExists() { @@ -66,15 +67,17 @@ class JdbcTemplateAutoConfigurationTests { @Test void testJdbcTemplateWithCustomProperties() { - this.contextRunner.withPropertyValues("spring.jdbc.template.fetch-size:100", - "spring.jdbc.template.query-timeout:60", "spring.jdbc.template.max-rows:1000").run((context) -> { - assertThat(context).hasSingleBean(JdbcOperations.class); - JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class); - assertThat(jdbcTemplate.getDataSource()).isNotNull(); - assertThat(jdbcTemplate.getFetchSize()).isEqualTo(100); - assertThat(jdbcTemplate.getQueryTimeout()).isEqualTo(60); - assertThat(jdbcTemplate.getMaxRows()).isEqualTo(1000); - }); + this.contextRunner + .withPropertyValues("spring.jdbc.template.fetch-size:100", "spring.jdbc.template.query-timeout:60", + "spring.jdbc.template.max-rows:1000") + .run((context) -> { + assertThat(context).hasSingleBean(JdbcOperations.class); + JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class); + assertThat(jdbcTemplate.getDataSource()).isNotNull(); + assertThat(jdbcTemplate.getFetchSize()).isEqualTo(100); + assertThat(jdbcTemplate.getQueryTimeout()).isEqualTo(60); + assertThat(jdbcTemplate.getMaxRows()).isEqualTo(1000); + }); } @Test @@ -106,7 +109,7 @@ class JdbcTemplateAutoConfigurationTests { @Test void testMultiJdbcTemplate() { this.contextRunner.withUserConfiguration(MultiJdbcTemplateConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(NamedParameterJdbcOperations.class)); + .run((context) -> assertThat(context).doesNotHaveBean(NamedParameterJdbcOperations.class)); } @Test @@ -115,7 +118,7 @@ class JdbcTemplateAutoConfigurationTests { assertThat(context).hasSingleBean(JdbcOperations.class); assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); assertThat(context.getBean(JdbcTemplate.class).getDataSource()) - .isEqualTo(context.getBean("test1DataSource")); + .isEqualTo(context.getBean("test1DataSource")); }); } @@ -124,7 +127,7 @@ class JdbcTemplateAutoConfigurationTests { this.contextRunner.withUserConfiguration(MultiJdbcTemplateUsingPrimaryConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); assertThat(context.getBean(NamedParameterJdbcTemplate.class).getJdbcOperations()) - .isEqualTo(context.getBean("test1Template")); + .isEqualTo(context.getBean("test1Template")); }); } @@ -141,59 +144,64 @@ class JdbcTemplateAutoConfigurationTests { this.contextRunner.withUserConfiguration(CustomConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); assertThat(context.getBean(NamedParameterJdbcOperations.class)) - .isEqualTo(context.getBean("customNamedParameterJdbcOperations")); + .isEqualTo(context.getBean("customNamedParameterJdbcOperations")); }); } @Test void testDependencyToScriptBasedDataSourceInitialization() { this.contextRunner.withConfiguration(AutoConfigurations.of(SqlInitializationAutoConfiguration.class)) - .withUserConfiguration(DataSourceInitializationValidator.class).run((context) -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBean(DataSourceInitializationValidator.class).count).isEqualTo(1); - }); + .withUserConfiguration(DataSourceInitializationValidator.class) + .run((context) -> { + assertThat(context).hasNotFailed(); + assertThat(context.getBean(DataSourceInitializationValidator.class).count).isEqualTo(1); + }); } @Test void testDependencyToFlyway() { this.contextRunner.withUserConfiguration(DataSourceMigrationValidator.class) - .withPropertyValues("spring.flyway.locations:classpath:db/city") - .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)).run((context) -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBean(DataSourceMigrationValidator.class).count).isEqualTo(0); - }); + .withPropertyValues("spring.flyway.locations:classpath:db/city") + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasNotFailed(); + assertThat(context.getBean(DataSourceMigrationValidator.class).count).isEqualTo(0); + }); } @Test void testDependencyToFlywayWithJdbcTemplateMixed() { this.contextRunner.withUserConfiguration(NamedParameterDataSourceMigrationValidator.class) - .withPropertyValues("spring.flyway.locations:classpath:db/city") - .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)).run((context) -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBean(JdbcTemplate.class)).isNotNull(); - assertThat(context.getBean(NamedParameterDataSourceMigrationValidator.class).count).isEqualTo(0); - }); + .withPropertyValues("spring.flyway.locations:classpath:db/city") + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasNotFailed(); + assertThat(context.getBean(JdbcTemplate.class)).isNotNull(); + assertThat(context.getBean(NamedParameterDataSourceMigrationValidator.class).count).isEqualTo(0); + }); } @Test void testDependencyToLiquibase() { this.contextRunner.withUserConfiguration(DataSourceMigrationValidator.class) - .withPropertyValues("spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml") - .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)).run((context) -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBean(DataSourceMigrationValidator.class).count).isEqualTo(0); - }); + .withPropertyValues("spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml") + .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasNotFailed(); + assertThat(context.getBean(DataSourceMigrationValidator.class).count).isEqualTo(0); + }); } @Test void testDependencyToLiquibaseWithJdbcTemplateMixed() { this.contextRunner.withUserConfiguration(NamedParameterDataSourceMigrationValidator.class) - .withPropertyValues("spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml") - .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)).run((context) -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBean(JdbcTemplate.class)).isNotNull(); - assertThat(context.getBean(NamedParameterDataSourceMigrationValidator.class).count).isEqualTo(0); - }); + .withPropertyValues("spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml") + .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasNotFailed(); + assertThat(context.getBean(JdbcTemplate.class)).isNotNull(); + assertThat(context.getBean(NamedParameterDataSourceMigrationValidator.class).count).isEqualTo(0); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/OracleUcpDataSourceConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/OracleUcpDataSourceConfigurationTests.java index 353b2777d8..6d044e5848 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/OracleUcpDataSourceConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/OracleUcpDataSourceConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat; class OracleUcpDataSourceConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.datasource.type=" + PoolDataSource.class.getName()); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.datasource.type=" + PoolDataSource.class.getName()); @Test void testDataSourceExists() { @@ -54,21 +54,23 @@ class OracleUcpDataSourceConfigurationTests { @Test void testDataSourcePropertiesOverridden() { - this.contextRunner.withPropertyValues("spring.datasource.oracleucp.url=jdbc:foo//bar/spam", - "spring.datasource.oracleucp.max-idle-time=1234").run((context) -> { - PoolDataSourceImpl ds = context.getBean(PoolDataSourceImpl.class); - assertThat(ds.getURL()).isEqualTo("jdbc:foo//bar/spam"); - assertThat(ds.getMaxIdleTime()).isEqualTo(1234); - }); + this.contextRunner + .withPropertyValues("spring.datasource.oracleucp.url=jdbc:foo//bar/spam", + "spring.datasource.oracleucp.max-idle-time=1234") + .run((context) -> { + PoolDataSourceImpl ds = context.getBean(PoolDataSourceImpl.class); + assertThat(ds.getURL()).isEqualTo("jdbc:foo//bar/spam"); + assertThat(ds.getMaxIdleTime()).isEqualTo(1234); + }); } @Test void testDataSourceConnectionPropertiesOverridden() { this.contextRunner.withPropertyValues("spring.datasource.oracleucp.connection-properties.autoCommit=false") - .run((context) -> { - PoolDataSourceImpl ds = context.getBean(PoolDataSourceImpl.class); - assertThat(ds.getConnectionProperty("autoCommit")).isEqualTo("false"); - }); + .run((context) -> { + PoolDataSourceImpl ds = context.getBean(PoolDataSourceImpl.class); + assertThat(ds.getConnectionProperty("autoCommit")).isEqualTo("false"); + }); } @Test @@ -97,11 +99,13 @@ class OracleUcpDataSourceConfigurationTests { @Test void poolNameTakesPrecedenceOverName() { - this.contextRunner.withPropertyValues("spring.datasource.name=myDS", - "spring.datasource.oracleucp.connection-pool-name=myOracleUcpDS").run((context) -> { - PoolDataSourceImpl ds = context.getBean(PoolDataSourceImpl.class); - assertThat(ds.getConnectionPoolName()).isEqualTo("myOracleUcpDS"); - }); + this.contextRunner + .withPropertyValues("spring.datasource.name=myDS", + "spring.datasource.oracleucp.connection-pool-name=myOracleUcpDS") + .run((context) -> { + PoolDataSourceImpl ds = context.getBean(PoolDataSourceImpl.class); + assertThat(ds.getConnectionPoolName()).isEqualTo("myOracleUcpDS"); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java index 5c0028b218..ff19386891 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,11 +66,11 @@ class TomcatDataSourceConfigurationTests { void testDataSourcePropertiesOverridden() throws Exception { this.context.register(TomcatDataSourceConfiguration.class); TestPropertyValues - .of(PREFIX + "url:jdbc:h2:mem:testdb", PREFIX + "testWhileIdle:true", PREFIX + "testOnBorrow:true", - PREFIX + "testOnReturn:true", PREFIX + "timeBetweenEvictionRunsMillis:10000", - PREFIX + "minEvictableIdleTimeMillis:12345", PREFIX + "maxWait:1234", - PREFIX + "jdbcInterceptors:SlowQueryReport", PREFIX + "validationInterval:9999") - .applyTo(this.context); + .of(PREFIX + "url:jdbc:h2:mem:testdb", PREFIX + "testWhileIdle:true", PREFIX + "testOnBorrow:true", + PREFIX + "testOnReturn:true", PREFIX + "timeBetweenEvictionRunsMillis:10000", + PREFIX + "minEvictableIdleTimeMillis:12345", PREFIX + "maxWait:1234", + PREFIX + "jdbcInterceptors:SlowQueryReport", PREFIX + "validationInterval:9999") + .applyTo(this.context); this.context.refresh(); org.apache.tomcat.jdbc.pool.DataSource ds = this.context.getBean(org.apache.tomcat.jdbc.pool.DataSource.class); assertThat(ds.getUrl()).isEqualTo("jdbc:h2:mem:testdb"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java index 336de2b14e..54ff0354f3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,15 +67,15 @@ class XADataSourceAutoConfigurationTests { @Test void createNonEmbeddedFromXAProperties() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(XADataSourceAutoConfiguration.class)) - .withUserConfiguration(FromProperties.class) - .withClassLoader(new FilteredClassLoader("org.h2.Driver", "org.hsqldb.jdbcDriver")) - .withPropertyValues("spring.datasource.xa.data-source-class-name:com.ibm.db2.jcc.DB2XADataSource", - "spring.datasource.xa.properties.user:test", "spring.datasource.xa.properties.password:secret") - .run((context) -> { - MockXADataSourceWrapper wrapper = context.getBean(MockXADataSourceWrapper.class); - XADataSource xaDataSource = wrapper.getXaDataSource(); - assertThat(xaDataSource).isInstanceOf(DB2XADataSource.class); - }); + .withUserConfiguration(FromProperties.class) + .withClassLoader(new FilteredClassLoader("org.h2.Driver", "org.hsqldb.jdbcDriver")) + .withPropertyValues("spring.datasource.xa.data-source-class-name:com.ibm.db2.jcc.DB2XADataSource", + "spring.datasource.xa.properties.user:test", "spring.datasource.xa.properties.password:secret") + .run((context) -> { + MockXADataSourceWrapper wrapper = context.getBean(MockXADataSourceWrapper.class); + XADataSource xaDataSource = wrapper.getXaDataSource(); + assertThat(xaDataSource).isInstanceOf(DB2XADataSource.class); + }); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationTests.java index 4ac47266e1..98dccc7c25 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,8 @@ import static org.assertj.core.api.Assertions.assertThat; class JerseyAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JerseyAutoConfiguration.class)) - .withUserConfiguration(ResourceConfigConfiguration.class); + .withConfiguration(AutoConfigurations.of(JerseyAutoConfiguration.class)) + .withUserConfiguration(ResourceConfigConfiguration.class); @Test void requestContextFilterRegistrationIsAutoConfigured() { @@ -72,29 +72,40 @@ class JerseyAutoConfigurationTests { void whenJaxbIsAvailableTheObjectMapperIsCustomizedWithAnAnnotationIntrospector() { this.contextRunner.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)).run((context) -> { ObjectMapper objectMapper = context.getBean(ObjectMapper.class); - assertThat(objectMapper.getSerializationConfig().getAnnotationIntrospector().allIntrospectors().stream() - .filter(JaxbAnnotationIntrospector.class::isInstance)).hasSize(1); + assertThat(objectMapper.getSerializationConfig() + .getAnnotationIntrospector() + .allIntrospectors() + .stream() + .filter(JaxbAnnotationIntrospector.class::isInstance)).hasSize(1); }); } @Test void whenJaxbIsNotAvailableTheObjectMapperCustomizationBacksOff() { this.contextRunner.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader("javax.xml.bind.annotation")).run((context) -> { - ObjectMapper objectMapper = context.getBean(ObjectMapper.class); - assertThat(objectMapper.getSerializationConfig().getAnnotationIntrospector().allIntrospectors() - .stream().filter(JaxbAnnotationIntrospector.class::isInstance)).isEmpty(); - }); + .withClassLoader(new FilteredClassLoader("javax.xml.bind.annotation")) + .run((context) -> { + ObjectMapper objectMapper = context.getBean(ObjectMapper.class); + assertThat(objectMapper.getSerializationConfig() + .getAnnotationIntrospector() + .allIntrospectors() + .stream() + .filter(JaxbAnnotationIntrospector.class::isInstance)).isEmpty(); + }); } @Test void whenJacksonJaxbModuleIsNotAvailableTheObjectMapperCustomizationBacksOff() { this.contextRunner.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(JaxbAnnotationIntrospector.class)).run((context) -> { - ObjectMapper objectMapper = context.getBean(ObjectMapper.class); - assertThat(objectMapper.getSerializationConfig().getAnnotationIntrospector().allIntrospectors() - .stream().filter(JaxbAnnotationIntrospector.class::isInstance)).isEmpty(); - }); + .withClassLoader(new FilteredClassLoader(JaxbAnnotationIntrospector.class)) + .run((context) -> { + ObjectMapper objectMapper = context.getBean(ObjectMapper.class); + assertThat(objectMapper.getSerializationConfig() + .getAnnotationIntrospector() + .allIntrospectors() + .stream() + .filter(JaxbAnnotationIntrospector.class::isInstance)).isEmpty(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java index fcc01eb88a..0fd4c93a5f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,7 +65,7 @@ class JmsAutoConfigurationTests { private static final String ACTIVEMQ_NETWORK_URL = "tcp://localhost:61616"; private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class, JmsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class, JmsAutoConfiguration.class)); @Test void testDefaultJmsConfiguration() { @@ -88,28 +88,28 @@ class JmsAutoConfigurationTests { @Test void testConnectionFactoryBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration2.class) - .run((context) -> assertThat(context.getBean(ActiveMQConnectionFactory.class).getBrokerURL()) - .isEqualTo("foobar")); + .run((context) -> assertThat(context.getBean(ActiveMQConnectionFactory.class).getBrokerURL()) + .isEqualTo("foobar")); } @Test void testJmsTemplateBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration3.class) - .run((context) -> assertThat(context.getBean(JmsTemplate.class).getPriority()).isEqualTo(999)); + .run((context) -> assertThat(context.getBean(JmsTemplate.class).getPriority()).isEqualTo(999)); } @Test void testJmsMessagingTemplateBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration5.class) - .run((context) -> assertThat(context.getBean(JmsMessagingTemplate.class).getDefaultDestinationName()) - .isEqualTo("fooBar")); + .run((context) -> assertThat(context.getBean(JmsMessagingTemplate.class).getDefaultDestinationName()) + .isEqualTo("fooBar")); } @Test void testJmsTemplateBackOffEverything() { this.contextRunner - .withUserConfiguration(TestConfiguration2.class, TestConfiguration3.class, TestConfiguration5.class) - .run(this::testJmsTemplateBackOffEverything); + .withUserConfiguration(TestConfiguration2.class, TestConfiguration3.class, TestConfiguration5.class) + .run(this::testJmsTemplateBackOffEverything); } private void testJmsTemplateBackOffEverything(AssertableApplicationContext loaded) { @@ -124,32 +124,32 @@ class JmsAutoConfigurationTests { @Test void testEnableJmsCreateDefaultContainerFactory() { this.contextRunner.withUserConfiguration(EnableJmsConfiguration.class) - .run((context) -> assertThat(context) - .getBean("jmsListenerContainerFactory", JmsListenerContainerFactory.class) - .isExactlyInstanceOf(DefaultJmsListenerContainerFactory.class)); + .run((context) -> assertThat(context) + .getBean("jmsListenerContainerFactory", JmsListenerContainerFactory.class) + .isExactlyInstanceOf(DefaultJmsListenerContainerFactory.class)); } @Test void testJmsListenerContainerFactoryBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration6.class, EnableJmsConfiguration.class) - .run((context) -> assertThat(context) - .getBean("jmsListenerContainerFactory", JmsListenerContainerFactory.class) - .isExactlyInstanceOf(SimpleJmsListenerContainerFactory.class)); + .run((context) -> assertThat(context) + .getBean("jmsListenerContainerFactory", JmsListenerContainerFactory.class) + .isExactlyInstanceOf(SimpleJmsListenerContainerFactory.class)); } @Test void jmsListenerContainerFactoryWhenMultipleConnectionFactoryBeansShouldBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration10.class) - .run((context) -> assertThat(context).doesNotHaveBean(JmsListenerContainerFactory.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JmsListenerContainerFactory.class)); } @Test void testJmsListenerContainerFactoryWithCustomSettings() { this.contextRunner.withUserConfiguration(EnableJmsConfiguration.class) - .withPropertyValues("spring.jms.listener.autoStartup=false", - "spring.jms.listener.acknowledgeMode=client", "spring.jms.listener.concurrency=2", - "spring.jms.listener.receiveTimeout=2s", "spring.jms.listener.maxConcurrency=10") - .run(this::testJmsListenerContainerFactoryWithCustomSettings); + .withPropertyValues("spring.jms.listener.autoStartup=false", "spring.jms.listener.acknowledgeMode=client", + "spring.jms.listener.concurrency=2", "spring.jms.listener.receiveTimeout=2s", + "spring.jms.listener.maxConcurrency=10") + .run(this::testJmsListenerContainerFactoryWithCustomSettings); } private void testJmsListenerContainerFactoryWithCustomSettings(AssertableApplicationContext loaded) { @@ -164,7 +164,7 @@ class JmsAutoConfigurationTests { @Test void testJmsListenerContainerFactoryWithDefaultSettings() { this.contextRunner.withUserConfiguration(EnableJmsConfiguration.class) - .run(this::testJmsListenerContainerFactoryWithDefaultSettings); + .run(this::testJmsListenerContainerFactoryWithDefaultSettings); } private void testJmsListenerContainerFactoryWithDefaultSettings(AssertableApplicationContext loaded) { @@ -175,22 +175,22 @@ class JmsAutoConfigurationTests { @Test void testDefaultContainerFactoryWithJtaTransactionManager() { this.contextRunner.withUserConfiguration(TestConfiguration7.class, EnableJmsConfiguration.class) - .run((context) -> { - DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); - assertThat(container.isSessionTransacted()).isFalse(); - assertThat(container).hasFieldOrPropertyWithValue("transactionManager", - context.getBean(JtaTransactionManager.class)); - }); + .run((context) -> { + DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); + assertThat(container.isSessionTransacted()).isFalse(); + assertThat(container).hasFieldOrPropertyWithValue("transactionManager", + context.getBean(JtaTransactionManager.class)); + }); } @Test void testDefaultContainerFactoryNonJtaTransactionManager() { this.contextRunner.withUserConfiguration(TestConfiguration8.class, EnableJmsConfiguration.class) - .run((context) -> { - DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); - assertThat(container.isSessionTransacted()).isTrue(); - assertThat(container).hasFieldOrPropertyWithValue("transactionManager", null); - }); + .run((context) -> { + DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); + assertThat(container.isSessionTransacted()).isTrue(); + assertThat(container).hasFieldOrPropertyWithValue("transactionManager", null); + }); } @Test @@ -205,30 +205,32 @@ class JmsAutoConfigurationTests { @Test void testDefaultContainerFactoryWithMessageConverters() { this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class, EnableJmsConfiguration.class) - .run((context) -> { - DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); - assertThat(container.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); - }); + .run((context) -> { + DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); + assertThat(container.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); + }); } @Test void testDefaultContainerFactoryWithExceptionListener() { ExceptionListener exceptionListener = mock(ExceptionListener.class); this.contextRunner.withUserConfiguration(EnableJmsConfiguration.class) - .withBean(ExceptionListener.class, () -> exceptionListener).run((context) -> { - DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); - assertThat(container.getExceptionListener()).isSameAs(exceptionListener); - }); + .withBean(ExceptionListener.class, () -> exceptionListener) + .run((context) -> { + DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); + assertThat(container.getExceptionListener()).isSameAs(exceptionListener); + }); } @Test void testCustomContainerFactoryWithConfigurer() { this.contextRunner.withUserConfiguration(TestConfiguration9.class, EnableJmsConfiguration.class) - .withPropertyValues("spring.jms.listener.autoStartup=false").run((context) -> { - DefaultMessageListenerContainer container = getContainer(context, "customListenerContainerFactory"); - assertThat(container.getCacheLevel()).isEqualTo(DefaultMessageListenerContainer.CACHE_CONSUMER); - assertThat(container.isAutoStartup()).isFalse(); - }); + .withPropertyValues("spring.jms.listener.autoStartup=false") + .run((context) -> { + DefaultMessageListenerContainer container = getContainer(context, "customListenerContainerFactory"); + assertThat(container.getCacheLevel()).isEqualTo(DefaultMessageListenerContainer.CACHE_CONSUMER); + assertThat(container.isAutoStartup()).isFalse(); + }); } private DefaultMessageListenerContainer getContainer(AssertableApplicationContext loaded, String name) { @@ -248,29 +250,29 @@ class JmsAutoConfigurationTests { @Test void testJmsTemplateWithDestinationResolver() { this.contextRunner.withUserConfiguration(DestinationResolversConfiguration.class) - .run((context) -> assertThat(context.getBean(JmsTemplate.class).getDestinationResolver()) - .isSameAs(context.getBean("myDestinationResolver"))); + .run((context) -> assertThat(context.getBean(JmsTemplate.class).getDestinationResolver()) + .isSameAs(context.getBean("myDestinationResolver"))); } @Test void testJmsTemplateFullCustomization() { this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class) - .withPropertyValues("spring.jms.template.default-destination=testQueue", - "spring.jms.template.delivery-delay=500", "spring.jms.template.delivery-mode=non-persistent", - "spring.jms.template.priority=6", "spring.jms.template.time-to-live=6000", - "spring.jms.template.receive-timeout=2000") - .run((context) -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - assertThat(jmsTemplate.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); - assertThat(jmsTemplate.isPubSubDomain()).isFalse(); - assertThat(jmsTemplate.getDefaultDestinationName()).isEqualTo("testQueue"); - assertThat(jmsTemplate.getDeliveryDelay()).isEqualTo(500); - assertThat(jmsTemplate.getDeliveryMode()).isEqualTo(1); - assertThat(jmsTemplate.getPriority()).isEqualTo(6); - assertThat(jmsTemplate.getTimeToLive()).isEqualTo(6000); - assertThat(jmsTemplate.isExplicitQosEnabled()).isTrue(); - assertThat(jmsTemplate.getReceiveTimeout()).isEqualTo(2000); - }); + .withPropertyValues("spring.jms.template.default-destination=testQueue", + "spring.jms.template.delivery-delay=500", "spring.jms.template.delivery-mode=non-persistent", + "spring.jms.template.priority=6", "spring.jms.template.time-to-live=6000", + "spring.jms.template.receive-timeout=2000") + .run((context) -> { + JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); + assertThat(jmsTemplate.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); + assertThat(jmsTemplate.isPubSubDomain()).isFalse(); + assertThat(jmsTemplate.getDefaultDestinationName()).isEqualTo("testQueue"); + assertThat(jmsTemplate.getDeliveryDelay()).isEqualTo(500); + assertThat(jmsTemplate.getDeliveryMode()).isEqualTo(1); + assertThat(jmsTemplate.getPriority()).isEqualTo(6); + assertThat(jmsTemplate.getTimeToLive()).isEqualTo(6000); + assertThat(jmsTemplate.isExplicitQosEnabled()).isTrue(); + assertThat(jmsTemplate.getReceiveTimeout()).isEqualTo(2000); + }); } @Test @@ -284,66 +286,70 @@ class JmsAutoConfigurationTests { @Test void testPubSubDisabledByDefault() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context.getBean(JmsTemplate.class).isPubSubDomain()).isFalse()); + .run((context) -> assertThat(context.getBean(JmsTemplate.class).isPubSubDomain()).isFalse()); } @Test void testJmsTemplatePostProcessedSoThatPubSubIsTrue() { this.contextRunner.withUserConfiguration(TestConfiguration4.class) - .run((context) -> assertThat(context.getBean(JmsTemplate.class).isPubSubDomain()).isTrue()); + .run((context) -> assertThat(context.getBean(JmsTemplate.class).isPubSubDomain()).isTrue()); } @Test void testPubSubDomainActive() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.jms.pubSubDomain:true").run((context) -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - DefaultMessageListenerContainer defaultMessageListenerContainer = context - .getBean(DefaultJmsListenerContainerFactory.class) - .createListenerContainer(mock(JmsListenerEndpoint.class)); - assertThat(jmsTemplate.isPubSubDomain()).isTrue(); - assertThat(defaultMessageListenerContainer.isPubSubDomain()).isTrue(); - }); + .withPropertyValues("spring.jms.pubSubDomain:true") + .run((context) -> { + JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); + DefaultMessageListenerContainer defaultMessageListenerContainer = context + .getBean(DefaultJmsListenerContainerFactory.class) + .createListenerContainer(mock(JmsListenerEndpoint.class)); + assertThat(jmsTemplate.isPubSubDomain()).isTrue(); + assertThat(defaultMessageListenerContainer.isPubSubDomain()).isTrue(); + }); } @Test void testPubSubDomainOverride() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.jms.pubSubDomain:false").run((context) -> { - assertThat(context).hasSingleBean(JmsTemplate.class); - assertThat(context).hasSingleBean(ConnectionFactory.class); - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ConnectionFactory factory = context.getBean(ConnectionFactory.class); - assertThat(jmsTemplate).isNotNull(); - assertThat(jmsTemplate.isPubSubDomain()).isFalse(); - assertThat(factory).isNotNull().isEqualTo(jmsTemplate.getConnectionFactory()); - }); + .withPropertyValues("spring.jms.pubSubDomain:false") + .run((context) -> { + assertThat(context).hasSingleBean(JmsTemplate.class); + assertThat(context).hasSingleBean(ConnectionFactory.class); + JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); + ConnectionFactory factory = context.getBean(ConnectionFactory.class); + assertThat(jmsTemplate).isNotNull(); + assertThat(jmsTemplate.isPubSubDomain()).isFalse(); + assertThat(factory).isNotNull().isEqualTo(jmsTemplate.getConnectionFactory()); + }); } @Test void testActiveMQOverriddenStandalone() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.activemq.inMemory:false").run((context) -> { - assertThat(context).hasSingleBean(JmsTemplate.class); - assertThat(context).hasSingleBean(CachingConnectionFactory.class); - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ConnectionFactory factory = context.getBean(ConnectionFactory.class); - assertThat(factory).isEqualTo(jmsTemplate.getConnectionFactory()); - assertThat(getBrokerUrl((CachingConnectionFactory) factory)).isEqualTo(ACTIVEMQ_NETWORK_URL); - }); + .withPropertyValues("spring.activemq.inMemory:false") + .run((context) -> { + assertThat(context).hasSingleBean(JmsTemplate.class); + assertThat(context).hasSingleBean(CachingConnectionFactory.class); + JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); + ConnectionFactory factory = context.getBean(ConnectionFactory.class); + assertThat(factory).isEqualTo(jmsTemplate.getConnectionFactory()); + assertThat(getBrokerUrl((CachingConnectionFactory) factory)).isEqualTo(ACTIVEMQ_NETWORK_URL); + }); } @Test void testActiveMQOverriddenRemoteHost() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.activemq.brokerUrl:tcp://remote-host:10000").run((context) -> { - assertThat(context).hasSingleBean(JmsTemplate.class); - assertThat(context).hasSingleBean(CachingConnectionFactory.class); - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ConnectionFactory factory = context.getBean(ConnectionFactory.class); - assertThat(factory).isEqualTo(jmsTemplate.getConnectionFactory()); - assertThat(getBrokerUrl((CachingConnectionFactory) factory)).isEqualTo("tcp://remote-host:10000"); - }); + .withPropertyValues("spring.activemq.brokerUrl:tcp://remote-host:10000") + .run((context) -> { + assertThat(context).hasSingleBean(JmsTemplate.class); + assertThat(context).hasSingleBean(CachingConnectionFactory.class); + JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); + ConnectionFactory factory = context.getBean(ConnectionFactory.class); + assertThat(factory).isEqualTo(jmsTemplate.getConnectionFactory()); + assertThat(getBrokerUrl((CachingConnectionFactory) factory)).isEqualTo("tcp://remote-host:10000"); + }); } private String getBrokerUrl(CachingConnectionFactory connectionFactory) { @@ -354,54 +360,55 @@ class JmsAutoConfigurationTests { @Test void testActiveMQOverriddenPool() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.activemq.pool.enabled:true").run((context) -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - JmsPoolConnectionFactory pool = context.getBean(JmsPoolConnectionFactory.class); - assertThat(jmsTemplate).isNotNull(); - assertThat(pool).isNotNull(); - assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory()); - ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool.getConnectionFactory(); - assertThat(factory.getBrokerURL()).isEqualTo(ACTIVEMQ_EMBEDDED_URL); - }); + .withPropertyValues("spring.activemq.pool.enabled:true") + .run((context) -> { + JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); + JmsPoolConnectionFactory pool = context.getBean(JmsPoolConnectionFactory.class); + assertThat(jmsTemplate).isNotNull(); + assertThat(pool).isNotNull(); + assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory()); + ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool.getConnectionFactory(); + assertThat(factory.getBrokerURL()).isEqualTo(ACTIVEMQ_EMBEDDED_URL); + }); } @Test void testActiveMQOverriddenPoolAndStandalone() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.activemq.pool.enabled:true", "spring.activemq.inMemory:false") - .run((context) -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - JmsPoolConnectionFactory pool = context.getBean(JmsPoolConnectionFactory.class); - assertThat(jmsTemplate).isNotNull(); - assertThat(pool).isNotNull(); - assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory()); - ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool.getConnectionFactory(); - assertThat(factory.getBrokerURL()).isEqualTo(ACTIVEMQ_NETWORK_URL); - }); + .withPropertyValues("spring.activemq.pool.enabled:true", "spring.activemq.inMemory:false") + .run((context) -> { + JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); + JmsPoolConnectionFactory pool = context.getBean(JmsPoolConnectionFactory.class); + assertThat(jmsTemplate).isNotNull(); + assertThat(pool).isNotNull(); + assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory()); + ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool.getConnectionFactory(); + assertThat(factory.getBrokerURL()).isEqualTo(ACTIVEMQ_NETWORK_URL); + }); } @Test void testActiveMQOverriddenPoolAndRemoteServer() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.activemq.pool.enabled:true", - "spring.activemq.brokerUrl:tcp://remote-host:10000") - .run((context) -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - JmsPoolConnectionFactory pool = context.getBean(JmsPoolConnectionFactory.class); - assertThat(jmsTemplate).isNotNull(); - assertThat(pool).isNotNull(); - assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory()); - ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool.getConnectionFactory(); - assertThat(factory.getBrokerURL()).isEqualTo("tcp://remote-host:10000"); - }); + .withPropertyValues("spring.activemq.pool.enabled:true", + "spring.activemq.brokerUrl:tcp://remote-host:10000") + .run((context) -> { + JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); + JmsPoolConnectionFactory pool = context.getBean(JmsPoolConnectionFactory.class); + assertThat(jmsTemplate).isNotNull(); + assertThat(pool).isNotNull(); + assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory()); + ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool.getConnectionFactory(); + assertThat(factory.getBrokerURL()).isEqualTo("tcp://remote-host:10000"); + }); } @Test void enableJmsAutomatically() { this.contextRunner.withUserConfiguration(NoEnableJmsConfiguration.class) - .run((context) -> assertThat(context) - .hasBean(JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) - .hasBean(JmsListenerConfigUtils.JMS_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME)); + .run((context) -> assertThat(context) + .hasBean(JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) + .hasBean(JmsListenerConfigUtils.JMS_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsPropertiesTests.java index 50b1c3df83..7ddbecd5c8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -83,7 +83,7 @@ class JmsPropertiesTests { @Test void defaultReceiveTimeoutMatchesListenerContainersDefault() { assertThat(new JmsProperties().getListener().getReceiveTimeout()) - .hasMillis(AbstractPollingMessageListenerContainer.DEFAULT_RECEIVE_TIMEOUT); + .hasMillis(AbstractPollingMessageListenerContainer.DEFAULT_RECEIVE_TIMEOUT); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java index 84f9a95543..5be3367ff8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ import static org.mockito.Mockito.mock; class JndiConnectionFactoryAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JndiConnectionFactoryAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JndiConnectionFactoryAutoConfiguration.class)); private ClassLoader threadContextClassLoader; @@ -90,22 +90,23 @@ class JndiConnectionFactoryAutoConfigurationTests { void jndiNamePropertySet() { ConnectionFactory connectionFactory = configureConnectionFactory("java:comp/env/myCF"); this.contextRunner.withPropertyValues("spring.jms.jndi-name=java:comp/env/myCF") - .run(assertConnectionFactory(connectionFactory)); + .run(assertConnectionFactory(connectionFactory)); } @Test void jndiNamePropertySetWithResourceRef() { ConnectionFactory connectionFactory = configureConnectionFactory("java:comp/env/myCF"); this.contextRunner.withPropertyValues("spring.jms.jndi-name=myCF") - .run(assertConnectionFactory(connectionFactory)); + .run(assertConnectionFactory(connectionFactory)); } @Test void jndiNamePropertySetWithWrongValue() { this.contextRunner.withPropertyValues("spring.jms.jndi-name=doesNotExistCF").run((context) -> { assertThat(context).hasFailed(); - assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("doesNotExistCF"); + assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("doesNotExistCF"); }); } @@ -113,7 +114,7 @@ class JndiConnectionFactoryAutoConfigurationTests { return (context) -> { assertThat(context).hasSingleBean(ConnectionFactory.class).hasBean("jmsConnectionFactory"); assertThat(context.getBean(ConnectionFactory.class)).isSameAs(connectionFactory) - .isSameAs(context.getBean("jmsConnectionFactory")); + .isSameAs(context.getBean("jmsConnectionFactory")); }; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java index 81457c4cd5..232cbedf09 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,7 @@ import static org.mockito.Mockito.mockingDetails; class ActiveMQAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class, JmsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class, JmsAutoConfiguration.class)); @Test void brokerIsEmbeddedByDefault() { @@ -55,21 +55,22 @@ class ActiveMQAutoConfigurationTests { assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); assertThat(connectionFactory.getTargetConnectionFactory()).isInstanceOf(ActiveMQConnectionFactory.class); assertThat(((ActiveMQConnectionFactory) connectionFactory.getTargetConnectionFactory()).getBrokerURL()) - .isEqualTo("vm://localhost?broker.persistent=false"); + .isEqualTo("vm://localhost?broker.persistent=false"); }); } @Test void configurationBacksOffWhenCustomConnectionFactoryExists() { - this.contextRunner.withUserConfiguration(CustomConnectionFactoryConfiguration.class).run( - (context) -> assertThat(mockingDetails(context.getBean(ConnectionFactory.class)).isMock()).isTrue()); + this.contextRunner.withUserConfiguration(CustomConnectionFactoryConfiguration.class) + .run((context) -> assertThat(mockingDetails(context.getBean(ConnectionFactory.class)).isMock()).isTrue()); } @Test void connectionFactoryIsCachedByDefault() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(CachingConnectionFactory.class) - .hasBean("jmsConnectionFactory"); + assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(CachingConnectionFactory.class) + .hasBean("jmsConnectionFactory"); CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); assertThat(connectionFactory.getTargetConnectionFactory()).isInstanceOf(ActiveMQConnectionFactory.class); @@ -82,144 +83,155 @@ class ActiveMQAutoConfigurationTests { @Test void connectionFactoryCachingCanBeCustomized() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.jms.cache.consumers=true", "spring.jms.cache.producers=false", - "spring.jms.cache.session-cache-size=10") - .run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class) - .hasSingleBean(CachingConnectionFactory.class).hasBean("jmsConnectionFactory"); - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); - assertThat(connectionFactory.isCacheConsumers()).isTrue(); - assertThat(connectionFactory.isCacheProducers()).isFalse(); - assertThat(connectionFactory.getSessionCacheSize()).isEqualTo(10); - }); + .withPropertyValues("spring.jms.cache.consumers=true", "spring.jms.cache.producers=false", + "spring.jms.cache.session-cache-size=10") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(CachingConnectionFactory.class) + .hasBean("jmsConnectionFactory"); + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); + assertThat(connectionFactory.isCacheConsumers()).isTrue(); + assertThat(connectionFactory.isCacheProducers()).isFalse(); + assertThat(connectionFactory.getSessionCacheSize()).isEqualTo(10); + }); } @Test void connectionFactoryCachingCanBeDisabled() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.jms.cache.enabled=false").run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class) - .hasSingleBean(ActiveMQConnectionFactory.class).hasBean("jmsConnectionFactory"); - ActiveMQConnectionFactory connectionFactory = context.getBean(ActiveMQConnectionFactory.class); - assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); - ActiveMQConnectionFactory defaultFactory = new ActiveMQConnectionFactory( - "vm://localhost?broker.persistent=false"); - assertThat(connectionFactory.getUserName()).isEqualTo(defaultFactory.getUserName()); - assertThat(connectionFactory.getPassword()).isEqualTo(defaultFactory.getPassword()); - assertThat(connectionFactory.getCloseTimeout()).isEqualTo(defaultFactory.getCloseTimeout()); - assertThat(connectionFactory.isNonBlockingRedelivery()) - .isEqualTo(defaultFactory.isNonBlockingRedelivery()); - assertThat(connectionFactory.getSendTimeout()).isEqualTo(defaultFactory.getSendTimeout()); - assertThat(connectionFactory.isTrustAllPackages()).isEqualTo(defaultFactory.isTrustAllPackages()); - assertThat(connectionFactory.getTrustedPackages()) - .containsExactly(StringUtils.toStringArray(defaultFactory.getTrustedPackages())); - }); + .withPropertyValues("spring.jms.cache.enabled=false") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(ActiveMQConnectionFactory.class) + .hasBean("jmsConnectionFactory"); + ActiveMQConnectionFactory connectionFactory = context.getBean(ActiveMQConnectionFactory.class); + assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); + ActiveMQConnectionFactory defaultFactory = new ActiveMQConnectionFactory( + "vm://localhost?broker.persistent=false"); + assertThat(connectionFactory.getUserName()).isEqualTo(defaultFactory.getUserName()); + assertThat(connectionFactory.getPassword()).isEqualTo(defaultFactory.getPassword()); + assertThat(connectionFactory.getCloseTimeout()).isEqualTo(defaultFactory.getCloseTimeout()); + assertThat(connectionFactory.isNonBlockingRedelivery()) + .isEqualTo(defaultFactory.isNonBlockingRedelivery()); + assertThat(connectionFactory.getSendTimeout()).isEqualTo(defaultFactory.getSendTimeout()); + assertThat(connectionFactory.isTrustAllPackages()).isEqualTo(defaultFactory.isTrustAllPackages()); + assertThat(connectionFactory.getTrustedPackages()) + .containsExactly(StringUtils.toStringArray(defaultFactory.getTrustedPackages())); + }); } @Test void customConnectionFactoryIsApplied() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.jms.cache.enabled=false", - "spring.activemq.brokerUrl=vm://localhost?useJmx=false&broker.persistent=false", - "spring.activemq.user=foo", "spring.activemq.password=bar", "spring.activemq.closeTimeout=500", - "spring.activemq.nonBlockingRedelivery=true", "spring.activemq.sendTimeout=1000", - "spring.activemq.packages.trust-all=false", "spring.activemq.packages.trusted=com.example.acme") - .run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class) - .hasSingleBean(ActiveMQConnectionFactory.class).hasBean("jmsConnectionFactory"); - ActiveMQConnectionFactory connectionFactory = context.getBean(ActiveMQConnectionFactory.class); - assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); - assertThat(connectionFactory.getUserName()).isEqualTo("foo"); - assertThat(connectionFactory.getPassword()).isEqualTo("bar"); - assertThat(connectionFactory.getCloseTimeout()).isEqualTo(500); - assertThat(connectionFactory.isNonBlockingRedelivery()).isTrue(); - assertThat(connectionFactory.getSendTimeout()).isEqualTo(1000); - assertThat(connectionFactory.isTrustAllPackages()).isFalse(); - assertThat(connectionFactory.getTrustedPackages()).containsExactly("com.example.acme"); - }); + .withPropertyValues("spring.jms.cache.enabled=false", + "spring.activemq.brokerUrl=vm://localhost?useJmx=false&broker.persistent=false", + "spring.activemq.user=foo", "spring.activemq.password=bar", "spring.activemq.closeTimeout=500", + "spring.activemq.nonBlockingRedelivery=true", "spring.activemq.sendTimeout=1000", + "spring.activemq.packages.trust-all=false", "spring.activemq.packages.trusted=com.example.acme") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(ActiveMQConnectionFactory.class) + .hasBean("jmsConnectionFactory"); + ActiveMQConnectionFactory connectionFactory = context.getBean(ActiveMQConnectionFactory.class); + assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); + assertThat(connectionFactory.getUserName()).isEqualTo("foo"); + assertThat(connectionFactory.getPassword()).isEqualTo("bar"); + assertThat(connectionFactory.getCloseTimeout()).isEqualTo(500); + assertThat(connectionFactory.isNonBlockingRedelivery()).isTrue(); + assertThat(connectionFactory.getSendTimeout()).isEqualTo(1000); + assertThat(connectionFactory.isTrustAllPackages()).isFalse(); + assertThat(connectionFactory.getTrustedPackages()).containsExactly("com.example.acme"); + }); } @Test void defaultPoolConnectionFactoryIsApplied() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.activemq.pool.enabled=true").run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class) - .hasSingleBean(JmsPoolConnectionFactory.class).hasBean("jmsConnectionFactory"); - JmsPoolConnectionFactory connectionFactory = context.getBean(JmsPoolConnectionFactory.class); - assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); - JmsPoolConnectionFactory defaultFactory = new JmsPoolConnectionFactory(); - assertThat(connectionFactory.isBlockIfSessionPoolIsFull()) - .isEqualTo(defaultFactory.isBlockIfSessionPoolIsFull()); - assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()) - .isEqualTo(defaultFactory.getBlockIfSessionPoolIsFullTimeout()); - assertThat(connectionFactory.getConnectionIdleTimeout()) - .isEqualTo(defaultFactory.getConnectionIdleTimeout()); - assertThat(connectionFactory.getMaxConnections()).isEqualTo(defaultFactory.getMaxConnections()); - assertThat(connectionFactory.getMaxSessionsPerConnection()) - .isEqualTo(defaultFactory.getMaxSessionsPerConnection()); - assertThat(connectionFactory.getConnectionCheckInterval()) - .isEqualTo(defaultFactory.getConnectionCheckInterval()); - assertThat(connectionFactory.isUseAnonymousProducers()) - .isEqualTo(defaultFactory.isUseAnonymousProducers()); - }); + .withPropertyValues("spring.activemq.pool.enabled=true") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(JmsPoolConnectionFactory.class) + .hasBean("jmsConnectionFactory"); + JmsPoolConnectionFactory connectionFactory = context.getBean(JmsPoolConnectionFactory.class); + assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); + JmsPoolConnectionFactory defaultFactory = new JmsPoolConnectionFactory(); + assertThat(connectionFactory.isBlockIfSessionPoolIsFull()) + .isEqualTo(defaultFactory.isBlockIfSessionPoolIsFull()); + assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()) + .isEqualTo(defaultFactory.getBlockIfSessionPoolIsFullTimeout()); + assertThat(connectionFactory.getConnectionIdleTimeout()) + .isEqualTo(defaultFactory.getConnectionIdleTimeout()); + assertThat(connectionFactory.getMaxConnections()).isEqualTo(defaultFactory.getMaxConnections()); + assertThat(connectionFactory.getMaxSessionsPerConnection()) + .isEqualTo(defaultFactory.getMaxSessionsPerConnection()); + assertThat(connectionFactory.getConnectionCheckInterval()) + .isEqualTo(defaultFactory.getConnectionCheckInterval()); + assertThat(connectionFactory.isUseAnonymousProducers()) + .isEqualTo(defaultFactory.isUseAnonymousProducers()); + }); } @Test void customPoolConnectionFactoryIsApplied() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.activemq.pool.enabled=true", "spring.activemq.pool.blockIfFull=false", - "spring.activemq.pool.blockIfFullTimeout=64", "spring.activemq.pool.idleTimeout=512", - "spring.activemq.pool.maxConnections=256", "spring.activemq.pool.maxSessionsPerConnection=1024", - "spring.activemq.pool.timeBetweenExpirationCheck=2048", - "spring.activemq.pool.useAnonymousProducers=false") - .run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class) - .hasSingleBean(JmsPoolConnectionFactory.class).hasBean("jmsConnectionFactory"); - JmsPoolConnectionFactory connectionFactory = context.getBean(JmsPoolConnectionFactory.class); - assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); - assertThat(connectionFactory.isBlockIfSessionPoolIsFull()).isFalse(); - assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()).isEqualTo(64); - assertThat(connectionFactory.getConnectionIdleTimeout()).isEqualTo(512); - assertThat(connectionFactory.getMaxConnections()).isEqualTo(256); - assertThat(connectionFactory.getMaxSessionsPerConnection()).isEqualTo(1024); - assertThat(connectionFactory.getConnectionCheckInterval()).isEqualTo(2048); - assertThat(connectionFactory.isUseAnonymousProducers()).isFalse(); - }); + .withPropertyValues("spring.activemq.pool.enabled=true", "spring.activemq.pool.blockIfFull=false", + "spring.activemq.pool.blockIfFullTimeout=64", "spring.activemq.pool.idleTimeout=512", + "spring.activemq.pool.maxConnections=256", "spring.activemq.pool.maxSessionsPerConnection=1024", + "spring.activemq.pool.timeBetweenExpirationCheck=2048", + "spring.activemq.pool.useAnonymousProducers=false") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(JmsPoolConnectionFactory.class) + .hasBean("jmsConnectionFactory"); + JmsPoolConnectionFactory connectionFactory = context.getBean(JmsPoolConnectionFactory.class); + assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); + assertThat(connectionFactory.isBlockIfSessionPoolIsFull()).isFalse(); + assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()).isEqualTo(64); + assertThat(connectionFactory.getConnectionIdleTimeout()).isEqualTo(512); + assertThat(connectionFactory.getMaxConnections()).isEqualTo(256); + assertThat(connectionFactory.getMaxSessionsPerConnection()).isEqualTo(1024); + assertThat(connectionFactory.getConnectionCheckInterval()).isEqualTo(2048); + assertThat(connectionFactory.isUseAnonymousProducers()).isFalse(); + }); } @Test void poolConnectionFactoryConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.activemq.pool.enabled:true").run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class) - .hasSingleBean(JmsPoolConnectionFactory.class).hasBean("jmsConnectionFactory"); - ConnectionFactory factory = context.getBean(ConnectionFactory.class); - assertThat(context.getBean("jmsConnectionFactory")).isSameAs(factory); - assertThat(factory).isInstanceOf(JmsPoolConnectionFactory.class); - context.getSourceApplicationContext().close(); - assertThat(factory.createConnection()).isNull(); - }); + .withPropertyValues("spring.activemq.pool.enabled:true") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(JmsPoolConnectionFactory.class) + .hasBean("jmsConnectionFactory"); + ConnectionFactory factory = context.getBean(ConnectionFactory.class); + assertThat(context.getBean("jmsConnectionFactory")).isSameAs(factory); + assertThat(factory).isInstanceOf(JmsPoolConnectionFactory.class); + context.getSourceApplicationContext().close(); + assertThat(factory.createConnection()).isNull(); + }); } @Test void cachingConnectionFactoryNotOnTheClasspathThenSimpleConnectionFactoryAutoConfigured() { this.contextRunner.withClassLoader(new FilteredClassLoader(CachingConnectionFactory.class)) - .withPropertyValues("spring.activemq.pool.enabled=false", "spring.jms.cache.enabled=false") - .run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class) - .hasSingleBean(ActiveMQConnectionFactory.class).hasBean("jmsConnectionFactory"); - ActiveMQConnectionFactory connectionFactory = context.getBean(ActiveMQConnectionFactory.class); - assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); - }); + .withPropertyValues("spring.activemq.pool.enabled=false", "spring.jms.cache.enabled=false") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(ActiveMQConnectionFactory.class) + .hasBean("jmsConnectionFactory"); + ActiveMQConnectionFactory connectionFactory = context.getBean(ActiveMQConnectionFactory.class); + assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); + }); } @Test void cachingConnectionFactoryNotOnTheClasspathAndCacheEnabledThenSimpleConnectionFactoryNotConfigured() { this.contextRunner.withClassLoader(new FilteredClassLoader(CachingConnectionFactory.class)) - .withPropertyValues("spring.activemq.pool.enabled=false", "spring.jms.cache.enabled=true") - .run((context) -> assertThat(context).doesNotHaveBean(ConnectionFactory.class) - .doesNotHaveBean(ActiveMQConnectionFactory.class).doesNotHaveBean("jmsConnectionFactory")); + .withPropertyValues("spring.activemq.pool.enabled=false", "spring.jms.cache.enabled=true") + .run((context) -> assertThat(context).doesNotHaveBean(ConnectionFactory.class) + .doesNotHaveBean(ActiveMQConnectionFactory.class) + .doesNotHaveBean("jmsConnectionFactory")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java index 14b714070c..2c0c7a546c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,7 +66,7 @@ class ActiveMQPropertiesTests { void setTrustAllPackages() { this.properties.getPackages().setTrustAll(true); assertThat(createFactory(this.properties).createConnectionFactory(ActiveMQConnectionFactory.class) - .isTrustAllPackages()).isTrue(); + .isTrustAllPackages()).isTrue(); } @Test @@ -74,7 +74,7 @@ class ActiveMQPropertiesTests { this.properties.getPackages().setTrustAll(false); this.properties.getPackages().getTrusted().add("trusted.package"); ActiveMQConnectionFactory factory = createFactory(this.properties) - .createConnectionFactory(ActiveMQConnectionFactory.class); + .createConnectionFactory(ActiveMQConnectionFactory.class); assertThat(factory.isTrustAllPackages()).isFalse(); assertThat(factory.getTrustedPackages().size()).isEqualTo(1); assertThat(factory.getTrustedPackages().get(0)).isEqualTo("trusted.package"); 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 69d2341823..7179e0bf2c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,13 +66,14 @@ import static org.assertj.core.api.Assertions.assertThat; class ArtemisAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ArtemisAutoConfiguration.class, JmsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ArtemisAutoConfiguration.class, JmsAutoConfiguration.class)); @Test void connectionFactoryIsCachedByDefault() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(CachingConnectionFactory.class) - .hasBean("jmsConnectionFactory"); + assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(CachingConnectionFactory.class) + .hasBean("jmsConnectionFactory"); CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); assertThat(connectionFactory.getTargetConnectionFactory()).isInstanceOf(ActiveMQConnectionFactory.class); @@ -85,82 +86,84 @@ class ArtemisAutoConfigurationTests { @Test void connectionFactoryCachingCanBeCustomized() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.jms.cache.consumers=true", "spring.jms.cache.producers=false", - "spring.jms.cache.session-cache-size=10") - .run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class) - .hasSingleBean(CachingConnectionFactory.class).hasBean("jmsConnectionFactory"); - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); - assertThat(connectionFactory.isCacheConsumers()).isTrue(); - assertThat(connectionFactory.isCacheProducers()).isFalse(); - assertThat(connectionFactory.getSessionCacheSize()).isEqualTo(10); - }); + .withPropertyValues("spring.jms.cache.consumers=true", "spring.jms.cache.producers=false", + "spring.jms.cache.session-cache-size=10") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(CachingConnectionFactory.class) + .hasBean("jmsConnectionFactory"); + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); + assertThat(connectionFactory.isCacheConsumers()).isTrue(); + assertThat(connectionFactory.isCacheProducers()).isFalse(); + assertThat(connectionFactory.getSessionCacheSize()).isEqualTo(10); + }); } @Test void connectionFactoryCachingCanBeDisabled() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.jms.cache.enabled=false").run((context) -> { - assertThat(context).doesNotHaveBean(CachingConnectionFactory.class); - ConnectionFactory connectionFactory = getConnectionFactory(context); - assertThat(connectionFactory).isInstanceOf(ActiveMQConnectionFactory.class); - }); + .withPropertyValues("spring.jms.cache.enabled=false") + .run((context) -> { + assertThat(context).doesNotHaveBean(CachingConnectionFactory.class); + ConnectionFactory connectionFactory = getConnectionFactory(context); + assertThat(connectionFactory).isInstanceOf(ActiveMQConnectionFactory.class); + }); } @Test void nativeConnectionFactory() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.mode:native").run((context) -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ConnectionFactory connectionFactory = getConnectionFactory(context); - assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); - ActiveMQConnectionFactory activeMQConnectionFactory = getActiveMQConnectionFactory( - connectionFactory); - assertNettyConnectionFactory(activeMQConnectionFactory, "localhost", 61616); - assertThat(activeMQConnectionFactory.getUser()).isNull(); - assertThat(activeMQConnectionFactory.getPassword()).isNull(); - }); + .withPropertyValues("spring.artemis.mode:native") + .run((context) -> { + JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); + ConnectionFactory connectionFactory = getConnectionFactory(context); + assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); + ActiveMQConnectionFactory activeMQConnectionFactory = getActiveMQConnectionFactory(connectionFactory); + assertNettyConnectionFactory(activeMQConnectionFactory, "localhost", 61616); + assertThat(activeMQConnectionFactory.getUser()).isNull(); + assertThat(activeMQConnectionFactory.getPassword()).isNull(); + }); } @Test void nativeConnectionFactoryCustomBrokerUrl() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.mode:native", "spring.artemis.broker-url:tcp://192.168.1.144:9876") - .run((context) -> assertNettyConnectionFactory( - getActiveMQConnectionFactory(getConnectionFactory(context)), "192.168.1.144", 9876)); + .withPropertyValues("spring.artemis.mode:native", "spring.artemis.broker-url:tcp://192.168.1.144:9876") + .run((context) -> assertNettyConnectionFactory(getActiveMQConnectionFactory(getConnectionFactory(context)), + "192.168.1.144", 9876)); } @Test void nativeConnectionFactoryCredentials() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.mode:native", "spring.artemis.user:user", - "spring.artemis.password:secret") - .run((context) -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ConnectionFactory connectionFactory = getConnectionFactory(context); - assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); - ActiveMQConnectionFactory activeMQConnectionFactory = getActiveMQConnectionFactory( - connectionFactory); - assertNettyConnectionFactory(activeMQConnectionFactory, "localhost", 61616); - assertThat(activeMQConnectionFactory.getUser()).isEqualTo("user"); - assertThat(activeMQConnectionFactory.getPassword()).isEqualTo("secret"); - }); + .withPropertyValues("spring.artemis.mode:native", "spring.artemis.user:user", + "spring.artemis.password:secret") + .run((context) -> { + JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); + ConnectionFactory connectionFactory = getConnectionFactory(context); + assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); + ActiveMQConnectionFactory activeMQConnectionFactory = getActiveMQConnectionFactory(connectionFactory); + assertNettyConnectionFactory(activeMQConnectionFactory, "localhost", 61616); + assertThat(activeMQConnectionFactory.getUser()).isEqualTo("user"); + assertThat(activeMQConnectionFactory.getPassword()).isEqualTo("secret"); + }); } @Test void embeddedConnectionFactory() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.mode:embedded").run((context) -> { - ArtemisProperties properties = context.getBean(ArtemisProperties.class); - assertThat(properties.getMode()).isEqualTo(ArtemisMode.EMBEDDED); - assertThat(context).hasSingleBean(EmbeddedActiveMQ.class); - org.apache.activemq.artemis.core.config.Configuration configuration = context - .getBean(org.apache.activemq.artemis.core.config.Configuration.class); - assertThat(configuration.isPersistenceEnabled()).isFalse(); - assertThat(configuration.isSecurityEnabled()).isFalse(); - assertInVmConnectionFactory(getActiveMQConnectionFactory(getConnectionFactory(context))); - }); + .withPropertyValues("spring.artemis.mode:embedded") + .run((context) -> { + ArtemisProperties properties = context.getBean(ArtemisProperties.class); + assertThat(properties.getMode()).isEqualTo(ArtemisMode.EMBEDDED); + assertThat(context).hasSingleBean(EmbeddedActiveMQ.class); + org.apache.activemq.artemis.core.config.Configuration configuration = context + .getBean(org.apache.activemq.artemis.core.config.Configuration.class); + assertThat(configuration.isPersistenceEnabled()).isFalse(); + assertThat(configuration.isSecurityEnabled()).isFalse(); + assertInVmConnectionFactory(getActiveMQConnectionFactory(getConnectionFactory(context))); + }); } @Test @@ -169,7 +172,7 @@ class ArtemisAutoConfigurationTests { this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(EmbeddedActiveMQ.class); org.apache.activemq.artemis.core.config.Configuration configuration = context - .getBean(org.apache.activemq.artemis.core.config.Configuration.class); + .getBean(org.apache.activemq.artemis.core.config.Configuration.class); assertThat(configuration.isPersistenceEnabled()).isFalse(); assertThat(configuration.isSecurityEnabled()).isFalse(); assertInVmConnectionFactory(getActiveMQConnectionFactory(getConnectionFactory(context))); @@ -180,37 +183,37 @@ class ArtemisAutoConfigurationTests { void nativeConnectionFactoryIfEmbeddedServiceDisabledExplicitly() { // No mode is specified this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.embedded.enabled:false").run((context) -> { - assertThat(context).doesNotHaveBean(ActiveMQServer.class); - assertNettyConnectionFactory(getActiveMQConnectionFactory(getConnectionFactory(context)), - "localhost", 61616); - }); + .withPropertyValues("spring.artemis.embedded.enabled:false") + .run((context) -> { + assertThat(context).doesNotHaveBean(ActiveMQServer.class); + assertNettyConnectionFactory(getActiveMQConnectionFactory(getConnectionFactory(context)), "localhost", + 61616); + }); } @Test void embeddedConnectionFactoryEvenIfEmbeddedServiceDisabled() { // No mode is specified this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.mode:embedded", "spring.artemis.embedded.enabled:false") - .run((context) -> { - assertThat(context.getBeansOfType(ActiveMQServer.class)).isEmpty(); - assertInVmConnectionFactory(getActiveMQConnectionFactory(getConnectionFactory(context))); - }); + .withPropertyValues("spring.artemis.mode:embedded", "spring.artemis.embedded.enabled:false") + .run((context) -> { + assertThat(context.getBeansOfType(ActiveMQServer.class)).isEmpty(); + assertInVmConnectionFactory(getActiveMQConnectionFactory(getConnectionFactory(context))); + }); } @Test void embeddedServerWithDestinations() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.embedded.queues=Queue1,Queue2", - "spring.artemis.embedded.topics=Topic1") - .run((context) -> { - DestinationChecker checker = new DestinationChecker(context); - checker.checkQueue("Queue1", true); - checker.checkQueue("Queue2", true); - checker.checkQueue("NonExistentQueue", false); - checker.checkTopic("Topic1", true); - checker.checkTopic("NonExistentTopic", false); - }); + .withPropertyValues("spring.artemis.embedded.queues=Queue1,Queue2", "spring.artemis.embedded.topics=Topic1") + .run((context) -> { + DestinationChecker checker = new DestinationChecker(context); + checker.checkQueue("Queue1", true); + checker.checkQueue("Queue2", true); + checker.checkQueue("NonExistentQueue", false); + checker.checkTopic("Topic1", true); + checker.checkTopic("NonExistentTopic", false); + }); } @Test @@ -226,20 +229,21 @@ class ArtemisAutoConfigurationTests { void embeddedServiceWithCustomJmsConfiguration() { // Ignored with custom config this.contextRunner.withUserConfiguration(CustomJmsConfiguration.class) - .withPropertyValues("spring.artemis.embedded.queues=Queue1,Queue2").run((context) -> { - DestinationChecker checker = new DestinationChecker(context); - checker.checkQueue("custom", true); // See CustomJmsConfiguration - checker.checkQueue("Queue1", false); - checker.checkQueue("Queue2", false); - }); + .withPropertyValues("spring.artemis.embedded.queues=Queue1,Queue2") + .run((context) -> { + DestinationChecker checker = new DestinationChecker(context); + checker.checkQueue("custom", true); // See CustomJmsConfiguration + checker.checkQueue("Queue1", false); + checker.checkQueue("Queue2", false); + }); } @Test void embeddedServiceWithCustomArtemisConfiguration() { this.contextRunner.withUserConfiguration(CustomArtemisConfiguration.class) - .run((context) -> assertThat( - context.getBean(org.apache.activemq.artemis.core.config.Configuration.class).getName()) - .isEqualTo("customFooBar")); + .run((context) -> assertThat( + context.getBean(org.apache.activemq.artemis.core.config.Configuration.class).getName()) + .isEqualTo("customFooBar")); } @Test @@ -248,57 +252,57 @@ class ArtemisAutoConfigurationTests { final String messageId = UUID.randomUUID().toString(); // Start the server and post a message to some queue this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.embedded.queues=TestQueue", - "spring.artemis.embedded.persistent:true", - "spring.artemis.embedded.dataDirectory:" + dataDirectory.getAbsolutePath()) - .run((context) -> context.getBean(JmsTemplate.class).send("TestQueue", - (session) -> session.createTextMessage(messageId))) - .run((context) -> { - // Start the server again and check if our message is still here - JmsTemplate jmsTemplate2 = context.getBean(JmsTemplate.class); - jmsTemplate2.setReceiveTimeout(1000L); - Message message = jmsTemplate2.receive("TestQueue"); - assertThat(message).isNotNull(); - assertThat(((TextMessage) message).getText()).isEqualTo(messageId); - }); + .withPropertyValues("spring.artemis.embedded.queues=TestQueue", "spring.artemis.embedded.persistent:true", + "spring.artemis.embedded.dataDirectory:" + dataDirectory.getAbsolutePath()) + .run((context) -> context.getBean(JmsTemplate.class) + .send("TestQueue", (session) -> session.createTextMessage(messageId))) + .run((context) -> { + // Start the server again and check if our message is still here + JmsTemplate jmsTemplate2 = context.getBean(JmsTemplate.class); + jmsTemplate2.setReceiveTimeout(1000L); + Message message = jmsTemplate2.receive("TestQueue"); + assertThat(message).isNotNull(); + assertThat(((TextMessage) message).getText()).isEqualTo(messageId); + }); } @Test void severalEmbeddedBrokers() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.embedded.queues=Queue1").run((first) -> { - this.contextRunner.withPropertyValues("spring.artemis.embedded.queues=Queue2").run((second) -> { - ArtemisProperties firstProperties = first.getBean(ArtemisProperties.class); - ArtemisProperties secondProperties = second.getBean(ArtemisProperties.class); - assertThat(firstProperties.getEmbedded().getServerId()) - .isLessThan(secondProperties.getEmbedded().getServerId()); - DestinationChecker firstChecker = new DestinationChecker(first); - firstChecker.checkQueue("Queue1", true); - firstChecker.checkQueue("Queue2", false); - DestinationChecker secondChecker = new DestinationChecker(second); - secondChecker.checkQueue("Queue1", false); - secondChecker.checkQueue("Queue2", true); - }); + .withPropertyValues("spring.artemis.embedded.queues=Queue1") + .run((first) -> { + this.contextRunner.withPropertyValues("spring.artemis.embedded.queues=Queue2").run((second) -> { + ArtemisProperties firstProperties = first.getBean(ArtemisProperties.class); + ArtemisProperties secondProperties = second.getBean(ArtemisProperties.class); + assertThat(firstProperties.getEmbedded().getServerId()) + .isLessThan(secondProperties.getEmbedded().getServerId()); + DestinationChecker firstChecker = new DestinationChecker(first); + firstChecker.checkQueue("Queue1", true); + firstChecker.checkQueue("Queue2", false); + DestinationChecker secondChecker = new DestinationChecker(second); + secondChecker.checkQueue("Queue1", false); + secondChecker.checkQueue("Queue2", true); }); + }); } @Test void connectToASpecificEmbeddedBroker() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.embedded.serverId=93", "spring.artemis.embedded.queues=Queue1") - .run((first) -> { - this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.mode=embedded", - // Connect to the "main" broker - "spring.artemis.embedded.serverId=93", - // Do not start a specific one - "spring.artemis.embedded.enabled=false") - .run((secondContext) -> { - first.getBean(JmsTemplate.class).convertAndSend("Queue1", "test"); - assertThat(secondContext.getBean(JmsTemplate.class).receiveAndConvert("Queue1")) - .isEqualTo("test"); - }); - }); + .withPropertyValues("spring.artemis.embedded.serverId=93", "spring.artemis.embedded.queues=Queue1") + .run((first) -> { + this.contextRunner.withUserConfiguration(EmptyConfiguration.class) + .withPropertyValues("spring.artemis.mode=embedded", + // Connect to the "main" broker + "spring.artemis.embedded.serverId=93", + // Do not start a specific one + "spring.artemis.embedded.enabled=false") + .run((secondContext) -> { + first.getBean(JmsTemplate.class).convertAndSend("Queue1", "test"); + assertThat(secondContext.getBean(JmsTemplate.class).receiveAndConvert("Queue1")) + .isEqualTo("test"); + }); + }); } @Test @@ -308,16 +312,16 @@ class ArtemisAutoConfigurationTests { JmsPoolConnectionFactory connectionFactory = context.getBean(JmsPoolConnectionFactory.class); JmsPoolConnectionFactory defaultFactory = new JmsPoolConnectionFactory(); assertThat(connectionFactory.isBlockIfSessionPoolIsFull()) - .isEqualTo(defaultFactory.isBlockIfSessionPoolIsFull()); + .isEqualTo(defaultFactory.isBlockIfSessionPoolIsFull()); assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()) - .isEqualTo(defaultFactory.getBlockIfSessionPoolIsFullTimeout()); + .isEqualTo(defaultFactory.getBlockIfSessionPoolIsFullTimeout()); assertThat(connectionFactory.getConnectionIdleTimeout()) - .isEqualTo(defaultFactory.getConnectionIdleTimeout()); + .isEqualTo(defaultFactory.getConnectionIdleTimeout()); assertThat(connectionFactory.getMaxConnections()).isEqualTo(defaultFactory.getMaxConnections()); assertThat(connectionFactory.getMaxSessionsPerConnection()) - .isEqualTo(defaultFactory.getMaxSessionsPerConnection()); + .isEqualTo(defaultFactory.getMaxSessionsPerConnection()); assertThat(connectionFactory.getConnectionCheckInterval()) - .isEqualTo(defaultFactory.getConnectionCheckInterval()); + .isEqualTo(defaultFactory.getConnectionCheckInterval()); assertThat(connectionFactory.isUseAnonymousProducers()).isEqualTo(defaultFactory.isUseAnonymousProducers()); }); } @@ -325,22 +329,22 @@ class ArtemisAutoConfigurationTests { @Test void customPoolConnectionFactoryIsApplied() { this.contextRunner - .withPropertyValues("spring.artemis.pool.enabled=true", "spring.artemis.pool.blockIfFull=false", - "spring.artemis.pool.blockIfFullTimeout=64", "spring.artemis.pool.idleTimeout=512", - "spring.artemis.pool.maxConnections=256", "spring.artemis.pool.maxSessionsPerConnection=1024", - "spring.artemis.pool.timeBetweenExpirationCheck=2048", - "spring.artemis.pool.useAnonymousProducers=false") - .run((context) -> { - assertThat(context.getBeansOfType(JmsPoolConnectionFactory.class)).hasSize(1); - JmsPoolConnectionFactory connectionFactory = context.getBean(JmsPoolConnectionFactory.class); - assertThat(connectionFactory.isBlockIfSessionPoolIsFull()).isFalse(); - assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()).isEqualTo(64); - assertThat(connectionFactory.getConnectionIdleTimeout()).isEqualTo(512); - assertThat(connectionFactory.getMaxConnections()).isEqualTo(256); - assertThat(connectionFactory.getMaxSessionsPerConnection()).isEqualTo(1024); - assertThat(connectionFactory.getConnectionCheckInterval()).isEqualTo(2048); - assertThat(connectionFactory.isUseAnonymousProducers()).isFalse(); - }); + .withPropertyValues("spring.artemis.pool.enabled=true", "spring.artemis.pool.blockIfFull=false", + "spring.artemis.pool.blockIfFullTimeout=64", "spring.artemis.pool.idleTimeout=512", + "spring.artemis.pool.maxConnections=256", "spring.artemis.pool.maxSessionsPerConnection=1024", + "spring.artemis.pool.timeBetweenExpirationCheck=2048", + "spring.artemis.pool.useAnonymousProducers=false") + .run((context) -> { + assertThat(context.getBeansOfType(JmsPoolConnectionFactory.class)).hasSize(1); + JmsPoolConnectionFactory connectionFactory = context.getBean(JmsPoolConnectionFactory.class); + assertThat(connectionFactory.isBlockIfSessionPoolIsFull()).isFalse(); + assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()).isEqualTo(64); + assertThat(connectionFactory.getConnectionIdleTimeout()).isEqualTo(512); + assertThat(connectionFactory.getMaxConnections()).isEqualTo(256); + assertThat(connectionFactory.getMaxSessionsPerConnection()).isEqualTo(1024); + assertThat(connectionFactory.getConnectionCheckInterval()).isEqualTo(2048); + assertThat(connectionFactory.isUseAnonymousProducers()).isFalse(); + }); } @Test @@ -386,7 +390,7 @@ class ArtemisAutoConfigurationTests { private TransportConfiguration getSingleTransportConfiguration(ActiveMQConnectionFactory connectionFactory) { TransportConfiguration[] transportConfigurations = connectionFactory.getServerLocator() - .getStaticTransportConfigurations(); + .getStaticTransportConfigurations(); assertThat(transportConfigurations).hasSize(1); return transportConfigurations[0]; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java index f6030a87af..f550891c07 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ class ArtemisEmbeddedConfigurationFactoryTests { properties.getEmbedded().setPersistent(true); Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); assertThat(configuration.getJournalDirectory()).startsWith(System.getProperty("java.io.tmpdir")) - .endsWith("/journal"); + .endsWith("/journal"); } @Test @@ -76,9 +76,9 @@ class ArtemisEmbeddedConfigurationFactoryTests { Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); Map addressesSettings = configuration.getAddressesSettings(); assertThat((Object) addressesSettings.get("#").getDeadLetterAddress()) - .isEqualTo(SimpleString.toSimpleString("DLQ")); + .isEqualTo(SimpleString.toSimpleString("DLQ")); assertThat((Object) addressesSettings.get("#").getExpiryAddress()) - .isEqualTo(SimpleString.toSimpleString("ExpiryQueue")); + .isEqualTo(SimpleString.toSimpleString("ExpiryQueue")); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java index ce11238e44..2e14f48018 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ import static org.assertj.core.api.Assertions.assertThat; class JmxAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class)); @Test void testDefaultMBeanExport() { @@ -80,16 +80,18 @@ class JmxAutoConfigurationTests { @Test void testDefaultDomainConfiguredOnMBeanExport() { - this.contextRunner.withPropertyValues("spring.jmx.enabled=true", "spring.jmx.default-domain=my-test-domain", - "spring.jmx.unique-names=true").run((context) -> { - assertThat(context).hasSingleBean(MBeanExporter.class); - MBeanExporter exporter = context.getBean(MBeanExporter.class); - assertThat(exporter).hasFieldOrPropertyWithValue("ensureUniqueRuntimeObjectNames", true); - MetadataNamingStrategy naming = (MetadataNamingStrategy) ReflectionTestUtils.getField(exporter, - "namingStrategy"); - assertThat(naming).hasFieldOrPropertyWithValue("defaultDomain", "my-test-domain"); - assertThat(naming).hasFieldOrPropertyWithValue("ensureUniqueRuntimeObjectNames", true); - }); + this.contextRunner + .withPropertyValues("spring.jmx.enabled=true", "spring.jmx.default-domain=my-test-domain", + "spring.jmx.unique-names=true") + .run((context) -> { + assertThat(context).hasSingleBean(MBeanExporter.class); + MBeanExporter exporter = context.getBean(MBeanExporter.class); + assertThat(exporter).hasFieldOrPropertyWithValue("ensureUniqueRuntimeObjectNames", true); + MetadataNamingStrategy naming = (MetadataNamingStrategy) ReflectionTestUtils.getField(exporter, + "namingStrategy"); + assertThat(naming).hasFieldOrPropertyWithValue("defaultDomain", "my-test-domain"); + assertThat(naming).hasFieldOrPropertyWithValue("ensureUniqueRuntimeObjectNames", true); + }); } @Test @@ -106,21 +108,21 @@ class JmxAutoConfigurationTests { try (AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext()) { parent.register(JmxAutoConfiguration.class, TestConfiguration.class); parent.refresh(); - this.contextRunner.withParent(parent).withConfiguration(UserConfigurations.of(TestConfiguration.class)) - .run((context) -> assertThat(context.isRunning())); + this.contextRunner.withParent(parent) + .withConfiguration(UserConfigurations.of(TestConfiguration.class)) + .run((context) -> assertThat(context.isRunning())); } } @Test void customJmxDomain() { this.contextRunner.withConfiguration(UserConfigurations.of(CustomJmxDomainConfiguration.class)) - .withConfiguration( - AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class)) - .run((context) -> { - assertThat(context).hasSingleBean(IntegrationMBeanExporter.class); - IntegrationMBeanExporter exporter = context.getBean(IntegrationMBeanExporter.class); - assertThat(exporter).hasFieldOrPropertyWithValue("domain", "foo.my"); - }); + .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasSingleBean(IntegrationMBeanExporter.class); + IntegrationMBeanExporter exporter = context.getBean(IntegrationMBeanExporter.class); + assertThat(exporter).hasFieldOrPropertyWithValue("domain", "foo.my"); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/ParentAwareNamingStrategyTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/ParentAwareNamingStrategyTests.java index f16b8324de..569cb878ce 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/ParentAwareNamingStrategyTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/ParentAwareNamingStrategyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class ParentAwareNamingStrategyTests { ParentAwareNamingStrategy strategy = new ParentAwareNamingStrategy(new AnnotationJmxAttributeSource()); strategy.setApplicationContext(context); assertThat(strategy.getObjectName(context.getBean("testManagedResource"), "testManagedResource") - .getKeyPropertyListString()).isEqualTo("type=something,name1=def,name2=ghi"); + .getKeyPropertyListString()).isEqualTo("type=something,name1=def,name2=ghi"); }); } @@ -62,8 +62,10 @@ class ParentAwareNamingStrategyTests { @Test void sameBeanInParentContextAddsContextProperty() { - this.contextRunner.withBean("testManagedResource", TestManagedResource.class).run((parent) -> this.contextRunner - .withBean("testManagedResource", TestManagedResource.class).withParent(parent).run((context) -> { + this.contextRunner.withBean("testManagedResource", TestManagedResource.class) + .run((parent) -> this.contextRunner.withBean("testManagedResource", TestManagedResource.class) + .withParent(parent) + .run((context) -> { ParentAwareNamingStrategy strategy = new ParentAwareNamingStrategy( new AnnotationJmxAttributeSource()); strategy.setApplicationContext(context); @@ -77,8 +79,10 @@ class ParentAwareNamingStrategyTests { @Test void uniqueObjectNameAndSameBeanInParentContextOnlyAddsIdentityProperty() { - this.contextRunner.withBean("testManagedResource", TestManagedResource.class).run((parent) -> this.contextRunner - .withBean("testManagedResource", TestManagedResource.class).withParent(parent).run((context) -> { + this.contextRunner.withBean("testManagedResource", TestManagedResource.class) + .run((parent) -> this.contextRunner.withBean("testManagedResource", TestManagedResource.class) + .withParent(parent) + .run((context) -> { ParentAwareNamingStrategy strategy = new ParentAwareNamingStrategy( new AnnotationJmxAttributeSource()); strategy.setApplicationContext(context); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java index e9f63d3f9d..22796c7c94 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java @@ -65,8 +65,8 @@ import static org.mockito.Mockito.mock; class JooqAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JooqAutoConfiguration.class)) - .withPropertyValues("spring.datasource.name:jooqtest"); + .withConfiguration(AutoConfigurations.of(JooqAutoConfiguration.class)) + .withPropertyValues("spring.datasource.name:jooqtest"); @Test void noDataSource() { @@ -84,8 +84,8 @@ class JooqAutoConfigurationTests { dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('foo');")); dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", "1")); assertThatExceptionOfType(DataIntegrityViolationException.class) - .isThrownBy(() -> dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", - "insert into jooqtest (name) values ('foo');"))); + .isThrownBy(() -> dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", + "insert into jooqtest (name) values ('foo');"))); dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", "2")); }); } @@ -93,19 +93,19 @@ class JooqAutoConfigurationTests { @Test void jooqWithTx() { this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class, TxManagerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(PlatformTransactionManager.class); - DSLContext dsl = context.getBean(DSLContext.class); - assertThat(dsl.configuration().dialect()).isEqualTo(SQLDialect.HSQLDB); - dsl.execute("create table jooqtest_tx (name varchar(255) primary key);"); - dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "0")); - dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest_tx (name) values ('foo');")); - dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); - assertThatExceptionOfType(DataIntegrityViolationException.class).isThrownBy( - () -> dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", - "insert into jooqtest (name) values ('foo');"))); - dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); - }); + .run((context) -> { + assertThat(context).hasSingleBean(PlatformTransactionManager.class); + DSLContext dsl = context.getBean(DSLContext.class); + assertThat(dsl.configuration().dialect()).isEqualTo(SQLDialect.HSQLDB); + dsl.execute("create table jooqtest_tx (name varchar(255) primary key);"); + dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "0")); + dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest_tx (name) values ('foo');")); + dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); + assertThatExceptionOfType(DataIntegrityViolationException.class) + .isThrownBy(() -> dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", + "insert into jooqtest (name) values ('foo');"))); + dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); + }); } @Test @@ -130,13 +130,13 @@ class JooqAutoConfigurationTests { @Test void jooqWithSeveralExecuteListenerProviders() { this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class, TestExecuteListenerProvider.class) - .run((context) -> { - DSLContext dsl = context.getBean(DSLContext.class); - ExecuteListenerProvider[] executeListenerProviders = dsl.configuration().executeListenerProviders(); - assertThat(executeListenerProviders).hasSize(2); - assertThat(executeListenerProviders[0]).isInstanceOf(DefaultExecuteListenerProvider.class); - assertThat(executeListenerProviders[1]).isInstanceOf(TestExecuteListenerProvider.class); - }); + .run((context) -> { + DSLContext dsl = context.getBean(DSLContext.class); + ExecuteListenerProvider[] executeListenerProviders = dsl.configuration().executeListenerProviders(); + assertThat(executeListenerProviders).hasSize(2); + assertThat(executeListenerProviders[0]).isInstanceOf(DefaultExecuteListenerProvider.class); + assertThat(executeListenerProviders[1]).isInstanceOf(TestExecuteListenerProvider.class); + }); } @Test @@ -144,15 +144,15 @@ class JooqAutoConfigurationTests { ConverterProvider converterProvider = mock(ConverterProvider.class); CharsetProvider charsetProvider = mock(CharsetProvider.class); this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class) - .withBean("configurationCustomizer1", DefaultConfigurationCustomizer.class, - () -> (configuration) -> configuration.set(converterProvider)) - .withBean("configurationCustomizer2", DefaultConfigurationCustomizer.class, - () -> (configuration) -> configuration.set(charsetProvider)) - .run((context) -> { - DSLContext dsl = context.getBean(DSLContext.class); - assertThat(dsl.configuration().converterProvider()).isSameAs(converterProvider); - assertThat(dsl.configuration().charsetProvider()).isSameAs(charsetProvider); - }); + .withBean("configurationCustomizer1", DefaultConfigurationCustomizer.class, + () -> (configuration) -> configuration.set(converterProvider)) + .withBean("configurationCustomizer2", DefaultConfigurationCustomizer.class, + () -> (configuration) -> configuration.set(charsetProvider)) + .run((context) -> { + DSLContext dsl = context.getBean(DSLContext.class); + assertThat(dsl.configuration().converterProvider()).isSameAs(converterProvider); + assertThat(dsl.configuration().charsetProvider()).isSameAs(charsetProvider); + }); } @Test @@ -165,39 +165,40 @@ class JooqAutoConfigurationTests { TransactionListenerProvider transactionListenerProvider = mock(TransactionListenerProvider.class); ExecutorProvider executorProvider = mock(ExecutorProvider.class); this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class, TxManagerConfiguration.class) - .withBean(RecordMapperProvider.class, () -> recordMapperProvider) - .withBean(RecordUnmapperProvider.class, () -> recordUnmapperProvider) - .withBean(RecordListenerProvider.class, () -> recordListenerProvider) - .withBean(VisitListenerProvider.class, () -> visitListenerProvider) - .withBean(TransactionListenerProvider.class, () -> transactionListenerProvider) - .withBean(ExecutorProvider.class, () -> executorProvider).run((context) -> { - DSLContext dsl = context.getBean(DSLContext.class); - assertThat(dsl.configuration().recordMapperProvider()).isSameAs(recordMapperProvider); - assertThat(dsl.configuration().recordUnmapperProvider()).isSameAs(recordUnmapperProvider); - assertThat(dsl.configuration().executorProvider()).isSameAs(executorProvider); - assertThat(dsl.configuration().recordListenerProviders()).containsExactly(recordListenerProvider); - assertThat(dsl.configuration().visitListenerProviders()).containsExactly(visitListenerProvider); - assertThat(dsl.configuration().transactionListenerProviders()) - .containsExactly(transactionListenerProvider); - }); + .withBean(RecordMapperProvider.class, () -> recordMapperProvider) + .withBean(RecordUnmapperProvider.class, () -> recordUnmapperProvider) + .withBean(RecordListenerProvider.class, () -> recordListenerProvider) + .withBean(VisitListenerProvider.class, () -> visitListenerProvider) + .withBean(TransactionListenerProvider.class, () -> transactionListenerProvider) + .withBean(ExecutorProvider.class, () -> executorProvider) + .run((context) -> { + DSLContext dsl = context.getBean(DSLContext.class); + assertThat(dsl.configuration().recordMapperProvider()).isSameAs(recordMapperProvider); + assertThat(dsl.configuration().recordUnmapperProvider()).isSameAs(recordUnmapperProvider); + assertThat(dsl.configuration().executorProvider()).isSameAs(executorProvider); + assertThat(dsl.configuration().recordListenerProviders()).containsExactly(recordListenerProvider); + assertThat(dsl.configuration().visitListenerProviders()).containsExactly(visitListenerProvider); + assertThat(dsl.configuration().transactionListenerProviders()) + .containsExactly(transactionListenerProvider); + }); } @Test void relaxedBindingOfSqlDialect() { this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class) - .withPropertyValues("spring.jooq.sql-dialect:PoSTGrES") - .run((context) -> assertThat(context.getBean(org.jooq.Configuration.class).dialect()) - .isEqualTo(SQLDialect.POSTGRES)); + .withPropertyValues("spring.jooq.sql-dialect:PoSTGrES") + .run((context) -> assertThat(context.getBean(org.jooq.Configuration.class).dialect()) + .isEqualTo(SQLDialect.POSTGRES)); } @Test void transactionProviderBacksOffOnExistingTransactionProvider() { this.contextRunner - .withUserConfiguration(JooqDataSourceConfiguration.class, CustomTransactionProviderConfiguration.class) - .run((context) -> { - TransactionProvider transactionProvider = context.getBean(TransactionProvider.class); - assertThat(transactionProvider).isInstanceOf(CustomTransactionProvider.class); - }); + .withUserConfiguration(JooqDataSourceConfiguration.class, CustomTransactionProviderConfiguration.class) + .run((context) -> { + TransactionProvider transactionProvider = context.getBean(TransactionProvider.class); + assertThat(transactionProvider).isInstanceOf(CustomTransactionProvider.class); + }); } static class AssertFetch implements TransactionalRunnable { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/NoDslContextBeanFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/NoDslContextBeanFailureAnalyzerTests.java index a546717b1d..8f0f034d31 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/NoDslContextBeanFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/NoDslContextBeanFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,12 +45,11 @@ class NoDslContextBeanFailureAnalyzerTests { @Test void analysisWithR2dbcAutoConfiguration() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .run((context) -> { - NoDslContextBeanFailureAnalyzer failureAnalyzer = new NoDslContextBeanFailureAnalyzer( - context.getBeanFactory()); - assertThat(failureAnalyzer.analyze(new NoSuchBeanDefinitionException(DSLContext.class))) - .isNotNull(); - }); + .run((context) -> { + NoDslContextBeanFailureAnalyzer failureAnalyzer = new NoDslContextBeanFailureAnalyzer( + context.getBeanFactory()); + assertThat(failureAnalyzer.analyze(new NoSuchBeanDefinitionException(DSLContext.class))).isNotNull(); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationTests.java index cf17fc37db..a8efa8921c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; class JsonbAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)); @Test void jsonbRegistration() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationWithNoProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationWithNoProviderTests.java index 9f2056543b..dd522f3fe4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationWithNoProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationWithNoProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; class JsonbAutoConfigurationWithNoProviderTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)); @Test void jsonbBacksOffWhenThereIsNoProvider() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java index 7e14da6f48..6ca7c2af76 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -105,15 +105,18 @@ class KafkaAutoConfigurationIntegrationTests { "spring.kafka.consumer.auto-offset-reset=earliest"); RetryTopicConfiguration configuration = this.context.getBean(RetryTopicConfiguration.class); assertThat(configuration.getDestinationTopicProperties()).extracting(DestinationTopic.Properties::delay) - .containsExactly(0L, 100L, 200L, 300L, 300L, 0L); + .containsExactly(0L, 100L, 200L, 300L, 300L, 0L); KafkaTemplate template = this.context.getBean(KafkaTemplate.class); template.send(TEST_RETRY_TOPIC, "foo", "bar"); RetryListener listener = this.context.getBean(RetryListener.class); assertThat(listener.latch.await(30, TimeUnit.SECONDS)).isTrue(); - assertThat(listener).extracting(RetryListener::getKey, RetryListener::getReceived).containsExactly("foo", - "bar"); - assertThat(listener).extracting(RetryListener::getTopics).asList().hasSize(5).containsSequence("testRetryTopic", - "testRetryTopic-retry-0", "testRetryTopic-retry-1", "testRetryTopic-retry-2", "testRetryTopic-retry-3"); + assertThat(listener).extracting(RetryListener::getKey, RetryListener::getReceived) + .containsExactly("foo", "bar"); + assertThat(listener).extracting(RetryListener::getTopics) + .asList() + .hasSize(5) + .containsSequence("testRetryTopic", "testRetryTopic-retry-0", "testRetryTopic-retry-1", + "testRetryTopic-retry-2", "testRetryTopic-retry-3"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java index 63926bce85..aa6bbf1f1a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -98,7 +98,7 @@ import static org.mockito.Mockito.never; class KafkaAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(KafkaAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(KafkaAutoConfiguration.class)); @Test void consumerProperties() { @@ -118,44 +118,42 @@ class KafkaAutoConfigurationTests { "spring.kafka.consumer.security.protocol = SSL", "spring.kafka.consumer.key-deserializer = org.apache.kafka.common.serialization.LongDeserializer", "spring.kafka.consumer.value-deserializer = org.apache.kafka.common.serialization.IntegerDeserializer") - .run((context) -> { - DefaultKafkaConsumerFactory consumerFactory = context - .getBean(DefaultKafkaConsumerFactory.class); - Map configs = consumerFactory.getConfigurationProperties(); - // common - assertThat(configs.get(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG)) - .isEqualTo(Collections.singletonList("foo:1234")); - assertThat(configs.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG)).isEqualTo("p1"); - assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "ksLoc"); - assertThat(configs.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)).isEqualTo("p2"); - assertThat(configs.get(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); - assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "tsLoc"); - assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).isEqualTo("p3"); - assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); - assertThat(configs.get(SslConfigs.SSL_PROTOCOL_CONFIG)).isEqualTo("TLSv1.2"); - // consumer - assertThat(configs.get(ConsumerConfig.CLIENT_ID_CONFIG)).isEqualTo("ccid"); // override - assertThat(configs.get(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG)).isEqualTo(Boolean.FALSE); - assertThat(configs.get(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG)).isEqualTo(123); - assertThat(configs.get(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)).isEqualTo("earliest"); - assertThat(configs.get(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG)).isEqualTo(456); - assertThat(configs.get(ConsumerConfig.FETCH_MIN_BYTES_CONFIG)).isEqualTo(1024); - assertThat(configs.get(ConsumerConfig.GROUP_ID_CONFIG)).isEqualTo("bar"); - assertThat(configs.get(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG)).isEqualTo(234); - assertThat(configs.get(ConsumerConfig.ISOLATION_LEVEL_CONFIG)).isEqualTo("read_committed"); - assertThat(configs.get(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG)) - .isEqualTo(LongDeserializer.class); - assertThat(configs.get(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG)).isEqualTo("SSL"); - assertThat(configs.get(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG)) - .isEqualTo(IntegerDeserializer.class); - assertThat(configs.get(ConsumerConfig.MAX_POLL_RECORDS_CONFIG)).isEqualTo(42); - assertThat(configs.get("foo")).isEqualTo("bar"); - assertThat(configs.get("baz")).isEqualTo("qux"); - assertThat(configs.get("foo.bar.baz")).isEqualTo("qux.fiz.buz"); - assertThat(configs.get("fiz.buz")).isEqualTo("fix.fox"); - }); + .run((context) -> { + DefaultKafkaConsumerFactory consumerFactory = context.getBean(DefaultKafkaConsumerFactory.class); + Map configs = consumerFactory.getConfigurationProperties(); + // common + assertThat(configs.get(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG)) + .isEqualTo(Collections.singletonList("foo:1234")); + assertThat(configs.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG)).isEqualTo("p1"); + assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "ksLoc"); + assertThat(configs.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)).isEqualTo("p2"); + assertThat(configs.get(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); + assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "tsLoc"); + assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).isEqualTo("p3"); + assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); + assertThat(configs.get(SslConfigs.SSL_PROTOCOL_CONFIG)).isEqualTo("TLSv1.2"); + // consumer + assertThat(configs.get(ConsumerConfig.CLIENT_ID_CONFIG)).isEqualTo("ccid"); // override + assertThat(configs.get(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG)).isEqualTo(Boolean.FALSE); + assertThat(configs.get(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG)).isEqualTo(123); + assertThat(configs.get(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)).isEqualTo("earliest"); + assertThat(configs.get(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG)).isEqualTo(456); + assertThat(configs.get(ConsumerConfig.FETCH_MIN_BYTES_CONFIG)).isEqualTo(1024); + assertThat(configs.get(ConsumerConfig.GROUP_ID_CONFIG)).isEqualTo("bar"); + assertThat(configs.get(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG)).isEqualTo(234); + assertThat(configs.get(ConsumerConfig.ISOLATION_LEVEL_CONFIG)).isEqualTo("read_committed"); + assertThat(configs.get(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG)).isEqualTo(LongDeserializer.class); + assertThat(configs.get(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG)).isEqualTo("SSL"); + assertThat(configs.get(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG)) + .isEqualTo(IntegerDeserializer.class); + assertThat(configs.get(ConsumerConfig.MAX_POLL_RECORDS_CONFIG)).isEqualTo(42); + assertThat(configs.get("foo")).isEqualTo("bar"); + assertThat(configs.get("baz")).isEqualTo("qux"); + assertThat(configs.get("foo.bar.baz")).isEqualTo("qux.fiz.buz"); + assertThat(configs.get("fiz.buz")).isEqualTo("fix.fox"); + }); } @Test @@ -174,162 +172,163 @@ class KafkaAutoConfigurationTests { "spring.kafka.producer.ssl.trust-store-password=p6", "spring.kafka.producer.ssl.trust-store-type=PKCS12", "spring.kafka.producer.ssl.protocol=TLSv1.2", "spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.IntegerSerializer") - .run((context) -> { - DefaultKafkaProducerFactory producerFactory = context - .getBean(DefaultKafkaProducerFactory.class); - Map configs = producerFactory.getConfigurationProperties(); - // common - assertThat(configs.get(ProducerConfig.CLIENT_ID_CONFIG)).isEqualTo("cid"); - // producer - assertThat(configs.get(ProducerConfig.ACKS_CONFIG)).isEqualTo("all"); - assertThat(configs.get(ProducerConfig.BATCH_SIZE_CONFIG)).isEqualTo(2048); - assertThat(configs.get(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)) - .isEqualTo(Collections.singletonList("bar:1234")); // override - assertThat(configs.get(ProducerConfig.BUFFER_MEMORY_CONFIG)).isEqualTo(4096L); - assertThat(configs.get(ProducerConfig.COMPRESSION_TYPE_CONFIG)).isEqualTo("gzip"); - assertThat(configs.get(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)).isEqualTo(LongSerializer.class); - assertThat(configs.get(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG)).isEqualTo("SSL"); - assertThat(configs.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG)).isEqualTo("p4"); - assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "ksLocP"); - assertThat(configs.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)).isEqualTo("p5"); - assertThat(configs.get(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); - assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "tsLocP"); - assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).isEqualTo("p6"); - assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); - assertThat(configs.get(SslConfigs.SSL_PROTOCOL_CONFIG)).isEqualTo("TLSv1.2"); - assertThat(configs.get(ProducerConfig.RETRIES_CONFIG)).isEqualTo(2); - assertThat(configs.get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)) - .isEqualTo(IntegerSerializer.class); - assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).isEmpty(); - assertThat(context.getBeansOfType(KafkaTransactionManager.class)).isEmpty(); - assertThat(configs.get("foo.bar.baz")).isEqualTo("qux.fiz.buz"); - assertThat(configs.get("fiz.buz")).isEqualTo("fix.fox"); - }); + .run((context) -> { + DefaultKafkaProducerFactory producerFactory = context.getBean(DefaultKafkaProducerFactory.class); + Map configs = producerFactory.getConfigurationProperties(); + // common + assertThat(configs.get(ProducerConfig.CLIENT_ID_CONFIG)).isEqualTo("cid"); + // producer + assertThat(configs.get(ProducerConfig.ACKS_CONFIG)).isEqualTo("all"); + assertThat(configs.get(ProducerConfig.BATCH_SIZE_CONFIG)).isEqualTo(2048); + assertThat(configs.get(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)) + .isEqualTo(Collections.singletonList("bar:1234")); // override + assertThat(configs.get(ProducerConfig.BUFFER_MEMORY_CONFIG)).isEqualTo(4096L); + assertThat(configs.get(ProducerConfig.COMPRESSION_TYPE_CONFIG)).isEqualTo("gzip"); + assertThat(configs.get(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)).isEqualTo(LongSerializer.class); + assertThat(configs.get(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG)).isEqualTo("SSL"); + assertThat(configs.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG)).isEqualTo("p4"); + assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "ksLocP"); + assertThat(configs.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)).isEqualTo("p5"); + assertThat(configs.get(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); + assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "tsLocP"); + assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).isEqualTo("p6"); + assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); + assertThat(configs.get(SslConfigs.SSL_PROTOCOL_CONFIG)).isEqualTo("TLSv1.2"); + assertThat(configs.get(ProducerConfig.RETRIES_CONFIG)).isEqualTo(2); + assertThat(configs.get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)) + .isEqualTo(IntegerSerializer.class); + assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).isEmpty(); + assertThat(context.getBeansOfType(KafkaTransactionManager.class)).isEmpty(); + assertThat(configs.get("foo.bar.baz")).isEqualTo("qux.fiz.buz"); + assertThat(configs.get("fiz.buz")).isEqualTo("fix.fox"); + }); } @Test void adminProperties() { this.contextRunner - .withPropertyValues("spring.kafka.clientId=cid", "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", - "spring.kafka.admin.fail-fast=true", "spring.kafka.admin.properties.fiz.buz=fix.fox", - "spring.kafka.admin.security.protocol=SSL", "spring.kafka.admin.ssl.key-password=p4", - "spring.kafka.admin.ssl.key-store-location=classpath:ksLocP", - "spring.kafka.admin.ssl.key-store-password=p5", "spring.kafka.admin.ssl.key-store-type=PKCS12", - "spring.kafka.admin.ssl.trust-store-location=classpath:tsLocP", - "spring.kafka.admin.ssl.trust-store-password=p6", - "spring.kafka.admin.ssl.trust-store-type=PKCS12", "spring.kafka.admin.ssl.protocol=TLSv1.2") - .run((context) -> { - KafkaAdmin admin = context.getBean(KafkaAdmin.class); - Map configs = admin.getConfigurationProperties(); - // common - assertThat(configs.get(AdminClientConfig.CLIENT_ID_CONFIG)).isEqualTo("cid"); - // admin - assertThat(configs.get(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG)).isEqualTo("SSL"); - assertThat(configs.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG)).isEqualTo("p4"); - assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "ksLocP"); - assertThat(configs.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)).isEqualTo("p5"); - assertThat(configs.get(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); - assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "tsLocP"); - assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).isEqualTo("p6"); - assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); - assertThat(configs.get(SslConfigs.SSL_PROTOCOL_CONFIG)).isEqualTo("TLSv1.2"); - assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).isEmpty(); - assertThat(configs.get("foo.bar.baz")).isEqualTo("qux.fiz.buz"); - assertThat(configs.get("fiz.buz")).isEqualTo("fix.fox"); - assertThat(admin).hasFieldOrPropertyWithValue("fatalIfBrokerNotAvailable", true); - }); + .withPropertyValues("spring.kafka.clientId=cid", "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", + "spring.kafka.admin.fail-fast=true", "spring.kafka.admin.properties.fiz.buz=fix.fox", + "spring.kafka.admin.security.protocol=SSL", "spring.kafka.admin.ssl.key-password=p4", + "spring.kafka.admin.ssl.key-store-location=classpath:ksLocP", + "spring.kafka.admin.ssl.key-store-password=p5", "spring.kafka.admin.ssl.key-store-type=PKCS12", + "spring.kafka.admin.ssl.trust-store-location=classpath:tsLocP", + "spring.kafka.admin.ssl.trust-store-password=p6", "spring.kafka.admin.ssl.trust-store-type=PKCS12", + "spring.kafka.admin.ssl.protocol=TLSv1.2") + .run((context) -> { + KafkaAdmin admin = context.getBean(KafkaAdmin.class); + Map configs = admin.getConfigurationProperties(); + // common + assertThat(configs.get(AdminClientConfig.CLIENT_ID_CONFIG)).isEqualTo("cid"); + // admin + assertThat(configs.get(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG)).isEqualTo("SSL"); + assertThat(configs.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG)).isEqualTo("p4"); + assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "ksLocP"); + assertThat(configs.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)).isEqualTo("p5"); + assertThat(configs.get(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); + assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "tsLocP"); + assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).isEqualTo("p6"); + assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); + assertThat(configs.get(SslConfigs.SSL_PROTOCOL_CONFIG)).isEqualTo("TLSv1.2"); + assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).isEmpty(); + assertThat(configs.get("foo.bar.baz")).isEqualTo("qux.fiz.buz"); + assertThat(configs.get("fiz.buz")).isEqualTo("fix.fox"); + assertThat(admin).hasFieldOrPropertyWithValue("fatalIfBrokerNotAvailable", true); + }); } @SuppressWarnings("unchecked") @Test void streamsProperties() { - this.contextRunner.withUserConfiguration(EnableKafkaStreamsConfiguration.class).withPropertyValues( - "spring.kafka.client-id=cid", "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", - "spring.application.name=appName", "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", - "spring.kafka.streams.auto-startup=false", "spring.kafka.streams.cache-max-size-buffering=1KB", - "spring.kafka.streams.client-id=override", "spring.kafka.streams.properties.fiz.buz=fix.fox", - "spring.kafka.streams.replication-factor=2", "spring.kafka.streams.state-dir=/tmp/state", - "spring.kafka.streams.security.protocol=SSL", "spring.kafka.streams.ssl.key-password=p7", - "spring.kafka.streams.ssl.key-store-location=classpath:ksLocP", - "spring.kafka.streams.ssl.key-store-password=p8", "spring.kafka.streams.ssl.key-store-type=PKCS12", - "spring.kafka.streams.ssl.trust-store-location=classpath:tsLocP", - "spring.kafka.streams.ssl.trust-store-password=p9", "spring.kafka.streams.ssl.trust-store-type=PKCS12", - "spring.kafka.streams.ssl.protocol=TLSv1.2").run((context) -> { - Properties configs = context - .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, - KafkaStreamsConfiguration.class) - .asProperties(); - assertThat((List) configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) - .containsExactly("localhost:9092", "localhost:9093"); - assertThat(configs.get(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG)).isEqualTo(1024); - assertThat(configs.get(StreamsConfig.CLIENT_ID_CONFIG)).isEqualTo("override"); - assertThat(configs.get(StreamsConfig.REPLICATION_FACTOR_CONFIG)).isEqualTo(2); - assertThat(configs.get(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG)).isEqualTo("SSL"); - assertThat(configs.get(StreamsConfig.STATE_DIR_CONFIG)).isEqualTo("/tmp/state"); - assertThat(configs.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG)).isEqualTo("p7"); - assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "ksLocP"); - assertThat(configs.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)).isEqualTo("p8"); - assertThat(configs.get(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); - assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "tsLocP"); - assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).isEqualTo("p9"); - assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); - assertThat(configs.get(SslConfigs.SSL_PROTOCOL_CONFIG)).isEqualTo("TLSv1.2"); - assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).isEmpty(); - assertThat(configs.get("foo.bar.baz")).isEqualTo("qux.fiz.buz"); - assertThat(configs.get("fiz.buz")).isEqualTo("fix.fox"); - assertThat(context.getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_BUILDER_BEAN_NAME)) - .isNotNull(); - }); + this.contextRunner.withUserConfiguration(EnableKafkaStreamsConfiguration.class) + .withPropertyValues("spring.kafka.client-id=cid", + "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", "spring.application.name=appName", + "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", "spring.kafka.streams.auto-startup=false", + "spring.kafka.streams.cache-max-size-buffering=1KB", "spring.kafka.streams.client-id=override", + "spring.kafka.streams.properties.fiz.buz=fix.fox", "spring.kafka.streams.replication-factor=2", + "spring.kafka.streams.state-dir=/tmp/state", "spring.kafka.streams.security.protocol=SSL", + "spring.kafka.streams.ssl.key-password=p7", + "spring.kafka.streams.ssl.key-store-location=classpath:ksLocP", + "spring.kafka.streams.ssl.key-store-password=p8", "spring.kafka.streams.ssl.key-store-type=PKCS12", + "spring.kafka.streams.ssl.trust-store-location=classpath:tsLocP", + "spring.kafka.streams.ssl.trust-store-password=p9", + "spring.kafka.streams.ssl.trust-store-type=PKCS12", "spring.kafka.streams.ssl.protocol=TLSv1.2") + .run((context) -> { + Properties configs = context + .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, + KafkaStreamsConfiguration.class) + .asProperties(); + assertThat((List) configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) + .containsExactly("localhost:9092", "localhost:9093"); + assertThat(configs.get(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG)).isEqualTo(1024); + assertThat(configs.get(StreamsConfig.CLIENT_ID_CONFIG)).isEqualTo("override"); + assertThat(configs.get(StreamsConfig.REPLICATION_FACTOR_CONFIG)).isEqualTo(2); + assertThat(configs.get(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG)).isEqualTo("SSL"); + assertThat(configs.get(StreamsConfig.STATE_DIR_CONFIG)).isEqualTo("/tmp/state"); + assertThat(configs.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG)).isEqualTo("p7"); + assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "ksLocP"); + assertThat(configs.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)).isEqualTo("p8"); + assertThat(configs.get(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); + assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "tsLocP"); + assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)).isEqualTo("p9"); + assertThat(configs.get(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)).isEqualTo("PKCS12"); + assertThat(configs.get(SslConfigs.SSL_PROTOCOL_CONFIG)).isEqualTo("TLSv1.2"); + assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).isEmpty(); + assertThat(configs.get("foo.bar.baz")).isEqualTo("qux.fiz.buz"); + assertThat(configs.get("fiz.buz")).isEqualTo("fix.fox"); + assertThat(context.getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_BUILDER_BEAN_NAME)) + .isNotNull(); + }); } @SuppressWarnings("unchecked") @Test void streamsApplicationIdUsesMainApplicationNameByDefault() { this.contextRunner.withUserConfiguration(EnableKafkaStreamsConfiguration.class) - .withPropertyValues("spring.application.name=my-test-app", - "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", - "spring.kafka.streams.auto-startup=false") - .run((context) -> { - Properties configs = context - .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, - KafkaStreamsConfiguration.class) - .asProperties(); - assertThat((List) configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) - .containsExactly("localhost:9092", "localhost:9093"); - assertThat(configs.get(StreamsConfig.APPLICATION_ID_CONFIG)).isEqualTo("my-test-app"); - }); + .withPropertyValues("spring.application.name=my-test-app", + "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", + "spring.kafka.streams.auto-startup=false") + .run((context) -> { + Properties configs = context + .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, + KafkaStreamsConfiguration.class) + .asProperties(); + assertThat((List) configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) + .containsExactly("localhost:9092", "localhost:9093"); + assertThat(configs.get(StreamsConfig.APPLICATION_ID_CONFIG)).isEqualTo("my-test-app"); + }); } @Test void streamsWithCustomKafkaConfiguration() { this.contextRunner - .withUserConfiguration(EnableKafkaStreamsConfiguration.class, TestKafkaStreamsConfiguration.class) - .withPropertyValues("spring.application.name=my-test-app", - "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", - "spring.kafka.streams.auto-startup=false") - .run((context) -> { - Properties configs = context - .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, - KafkaStreamsConfiguration.class) - .asProperties(); - assertThat(configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) - .isEqualTo("localhost:9094, localhost:9095"); - assertThat(configs.get(StreamsConfig.APPLICATION_ID_CONFIG)).isEqualTo("test-id"); - }); + .withUserConfiguration(EnableKafkaStreamsConfiguration.class, TestKafkaStreamsConfiguration.class) + .withPropertyValues("spring.application.name=my-test-app", + "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", + "spring.kafka.streams.auto-startup=false") + .run((context) -> { + Properties configs = context + .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, + KafkaStreamsConfiguration.class) + .asProperties(); + assertThat(configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) + .isEqualTo("localhost:9094, localhost:9095"); + assertThat(configs.get(StreamsConfig.APPLICATION_ID_CONFIG)).isEqualTo("test-id"); + }); } @Test void retryTopicConfigurationIsNotEnabledByDefault() { this.contextRunner - .withPropertyValues("spring.application.name=my-test-app", - "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093") - .run((context) -> assertThat(context).doesNotHaveBean(RetryTopicConfiguration.class)); + .withPropertyValues("spring.application.name=my-test-app", + "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093") + .run((context) -> assertThat(context).doesNotHaveBean(RetryTopicConfiguration.class)); } @Test @@ -337,26 +336,28 @@ class KafkaAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.application.name=my-test-app", "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", "spring.kafka.retry.topic.enabled=true", "spring.kafka.retry.topic.attempts=5", "spring.kafka.retry.topic.delay=100ms", - "spring.kafka.retry.topic.multiplier=2", "spring.kafka.retry.topic.max-delay=300ms").run((context) -> { - RetryTopicConfiguration configuration = context.getBean(RetryTopicConfiguration.class); - assertThat(configuration.getDestinationTopicProperties()).hasSize(6) - .extracting(DestinationTopic.Properties::delay, DestinationTopic.Properties::suffix) - .containsExactly(tuple(0L, ""), tuple(100L, "-retry-0"), tuple(200L, "-retry-1"), - tuple(300L, "-retry-2"), tuple(300L, "-retry-3"), tuple(0L, "-dlt")); - }); + "spring.kafka.retry.topic.multiplier=2", "spring.kafka.retry.topic.max-delay=300ms") + .run((context) -> { + RetryTopicConfiguration configuration = context.getBean(RetryTopicConfiguration.class); + assertThat(configuration.getDestinationTopicProperties()).hasSize(6) + .extracting(DestinationTopic.Properties::delay, DestinationTopic.Properties::suffix) + .containsExactly(tuple(0L, ""), tuple(100L, "-retry-0"), tuple(200L, "-retry-1"), + tuple(300L, "-retry-2"), tuple(300L, "-retry-3"), tuple(0L, "-dlt")); + }); } @Test void retryTopicConfigurationWithDefaultProperties() { this.contextRunner.withPropertyValues("spring.application.name=my-test-app", "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", "spring.kafka.retry.topic.enabled=true") - .run(assertRetryTopicConfiguration((configuration) -> { - assertThat(configuration.getDestinationTopicProperties()).hasSize(3) - .extracting(DestinationTopic.Properties::delay, DestinationTopic.Properties::suffix) - .containsExactly(tuple(0L, ""), tuple(1000L, "-retry"), tuple(0L, "-dlt")); - assertThat(configuration.forKafkaTopicAutoCreation()).extracting("shouldCreateTopics") - .asInstanceOf(InstanceOfAssertFactories.BOOLEAN).isFalse(); - })); + .run(assertRetryTopicConfiguration((configuration) -> { + assertThat(configuration.getDestinationTopicProperties()).hasSize(3) + .extracting(DestinationTopic.Properties::delay, DestinationTopic.Properties::suffix) + .containsExactly(tuple(0L, ""), tuple(1000L, "-retry"), tuple(0L, "-dlt")); + assertThat(configuration.forKafkaTopicAutoCreation()).extracting("shouldCreateTopics") + .asInstanceOf(InstanceOfAssertFactories.BOOLEAN) + .isFalse(); + })); } @Test @@ -364,9 +365,10 @@ class KafkaAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.application.name=my-test-app", "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", "spring.kafka.retry.topic.enabled=true", "spring.kafka.retry.topic.attempts=4", "spring.kafka.retry.topic.delay=2s") - .run(assertRetryTopicConfiguration( - (configuration) -> assertThat(configuration.getDestinationTopicProperties()).hasSize(3) - .extracting(DestinationTopic.Properties::delay).containsExactly(0L, 2000L, 0L))); + .run(assertRetryTopicConfiguration( + (configuration) -> assertThat(configuration.getDestinationTopicProperties()).hasSize(3) + .extracting(DestinationTopic.Properties::delay) + .containsExactly(0L, 2000L, 0L))); } @Test @@ -374,9 +376,10 @@ class KafkaAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.application.name=my-test-app", "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", "spring.kafka.retry.topic.enabled=true", "spring.kafka.retry.topic.attempts=4", "spring.kafka.retry.topic.delay=0") - .run(assertRetryTopicConfiguration( - (configuration) -> assertThat(configuration.getDestinationTopicProperties()).hasSize(3) - .extracting(DestinationTopic.Properties::delay).containsExactly(0L, 0L, 0L))); + .run(assertRetryTopicConfiguration( + (configuration) -> assertThat(configuration.getDestinationTopicProperties()).hasSize(3) + .extracting(DestinationTopic.Properties::delay) + .containsExactly(0L, 0L, 0L))); } private ContextConsumer assertRetryTopicConfiguration( @@ -391,52 +394,54 @@ class KafkaAutoConfigurationTests { @Test void streamsWithSeveralStreamsBuilderFactoryBeans() { this.contextRunner - .withUserConfiguration(EnableKafkaStreamsConfiguration.class, - TestStreamsBuilderFactoryBeanConfiguration.class) - .withPropertyValues("spring.application.name=my-test-app", - "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", - "spring.kafka.streams.auto-startup=false") - .run((context) -> { - Properties configs = context - .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, - KafkaStreamsConfiguration.class) - .asProperties(); - assertThat((List) configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) - .containsExactly("localhost:9092", "localhost:9093"); - then(context.getBean("&firstStreamsBuilderFactoryBean", StreamsBuilderFactoryBean.class)) - .should(never()).setAutoStartup(false); - then(context.getBean("&secondStreamsBuilderFactoryBean", StreamsBuilderFactoryBean.class)) - .should(never()).setAutoStartup(false); - }); + .withUserConfiguration(EnableKafkaStreamsConfiguration.class, + TestStreamsBuilderFactoryBeanConfiguration.class) + .withPropertyValues("spring.application.name=my-test-app", + "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", + "spring.kafka.streams.auto-startup=false") + .run((context) -> { + Properties configs = context + .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, + KafkaStreamsConfiguration.class) + .asProperties(); + assertThat((List) configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) + .containsExactly("localhost:9092", "localhost:9093"); + then(context.getBean("&firstStreamsBuilderFactoryBean", StreamsBuilderFactoryBean.class)) + .should(never()) + .setAutoStartup(false); + then(context.getBean("&secondStreamsBuilderFactoryBean", StreamsBuilderFactoryBean.class)) + .should(never()) + .setAutoStartup(false); + }); } @Test void streamsWithCleanupConfig() { this.contextRunner - .withUserConfiguration(EnableKafkaStreamsConfiguration.class, TestKafkaStreamsConfiguration.class) - .withPropertyValues("spring.application.name=my-test-app", - "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", - "spring.kafka.streams.auto-startup=false", "spring.kafka.streams.cleanup.on-startup=true", - "spring.kafka.streams.cleanup.on-shutdown=false") - .run((context) -> { - StreamsBuilderFactoryBean streamsBuilderFactoryBean = context - .getBean(StreamsBuilderFactoryBean.class); - assertThat(streamsBuilderFactoryBean) - .extracting("cleanupConfig", InstanceOfAssertFactories.type(CleanupConfig.class)) - .satisfies((cleanupConfig) -> { - assertThat(cleanupConfig.cleanupOnStart()).isTrue(); - assertThat(cleanupConfig.cleanupOnStop()).isFalse(); - }); - }); + .withUserConfiguration(EnableKafkaStreamsConfiguration.class, TestKafkaStreamsConfiguration.class) + .withPropertyValues("spring.application.name=my-test-app", + "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", + "spring.kafka.streams.auto-startup=false", "spring.kafka.streams.cleanup.on-startup=true", + "spring.kafka.streams.cleanup.on-shutdown=false") + .run((context) -> { + StreamsBuilderFactoryBean streamsBuilderFactoryBean = context.getBean(StreamsBuilderFactoryBean.class); + assertThat(streamsBuilderFactoryBean) + .extracting("cleanupConfig", InstanceOfAssertFactories.type(CleanupConfig.class)) + .satisfies((cleanupConfig) -> { + assertThat(cleanupConfig.cleanupOnStart()).isTrue(); + assertThat(cleanupConfig.cleanupOnStop()).isFalse(); + }); + }); } @Test void streamsApplicationIdIsMandatory() { this.contextRunner.withUserConfiguration(EnableKafkaStreamsConfiguration.class).run((context) -> { assertThat(context).hasFailed(); - assertThat(context).getFailure().hasMessageContaining("spring.kafka.streams.application-id") - .hasMessageContaining( - "This property is mandatory and fallback 'spring.application.name' is not set either."); + assertThat(context).getFailure() + .hasMessageContaining("spring.kafka.streams.application-id") + .hasMessageContaining( + "This property is mandatory and fallback 'spring.application.name' is not set either."); }); } @@ -464,44 +469,42 @@ class KafkaAutoConfigurationTests { "spring.kafka.jaas.enabled=true", "spring.kafka.listener.immediate-stop=true", "spring.kafka.producer.transaction-id-prefix=foo", "spring.kafka.jaas.login-module=foo", "spring.kafka.jaas.control-flag=REQUISITE", "spring.kafka.jaas.options.useKeyTab=true") - .run((context) -> { - DefaultKafkaProducerFactory producerFactory = context - .getBean(DefaultKafkaProducerFactory.class); - DefaultKafkaConsumerFactory consumerFactory = context - .getBean(DefaultKafkaConsumerFactory.class); - KafkaTemplate kafkaTemplate = context.getBean(KafkaTemplate.class); - AbstractKafkaListenerContainerFactory kafkaListenerContainerFactory = (AbstractKafkaListenerContainerFactory) context - .getBean(KafkaListenerContainerFactory.class); - assertThat(kafkaTemplate.getMessageConverter()).isInstanceOf(MessagingMessageConverter.class); - assertThat(kafkaTemplate).hasFieldOrPropertyWithValue("producerFactory", producerFactory); - assertThat(kafkaTemplate.getDefaultTopic()).isEqualTo("testTopic"); - assertThat(kafkaTemplate).hasFieldOrPropertyWithValue("transactionIdPrefix", "txOverride"); - assertThat(kafkaListenerContainerFactory.getConsumerFactory()).isEqualTo(consumerFactory); - ContainerProperties containerProperties = kafkaListenerContainerFactory.getContainerProperties(); - assertThat(containerProperties.getAckMode()).isEqualTo(AckMode.MANUAL); - assertThat(containerProperties.getClientId()).isEqualTo("client"); - assertThat(containerProperties.getAckCount()).isEqualTo(123); - assertThat(containerProperties.getAckTime()).isEqualTo(456L); - assertThat(containerProperties.getPollTimeout()).isEqualTo(2000L); - assertThat(containerProperties.getNoPollThreshold()).isEqualTo(2.5f); - assertThat(containerProperties.getIdleBetweenPolls()).isEqualTo(1000L); - assertThat(containerProperties.getIdleEventInterval()).isEqualTo(1000L); - assertThat(containerProperties.getIdlePartitionEventInterval()).isEqualTo(1000L); - assertThat(containerProperties.getMonitorInterval()).isEqualTo(45); - assertThat(containerProperties.isLogContainerConfig()).isTrue(); - assertThat(containerProperties.isMissingTopicsFatal()).isTrue(); - assertThat(containerProperties.isStopImmediate()).isTrue(); - assertThat(kafkaListenerContainerFactory).extracting("concurrency").isEqualTo(3); - assertThat(kafkaListenerContainerFactory.isBatchListener()).isTrue(); - assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).hasSize(1); - KafkaJaasLoginModuleInitializer jaas = context.getBean(KafkaJaasLoginModuleInitializer.class); - assertThat(jaas).hasFieldOrPropertyWithValue("loginModule", "foo"); - assertThat(jaas).hasFieldOrPropertyWithValue("controlFlag", - AppConfigurationEntry.LoginModuleControlFlag.REQUISITE); - assertThat(context.getBeansOfType(KafkaTransactionManager.class)).hasSize(1); - assertThat(((Map) ReflectionTestUtils.getField(jaas, "options"))) - .containsExactly(entry("useKeyTab", "true")); - }); + .run((context) -> { + DefaultKafkaProducerFactory producerFactory = context.getBean(DefaultKafkaProducerFactory.class); + DefaultKafkaConsumerFactory consumerFactory = context.getBean(DefaultKafkaConsumerFactory.class); + KafkaTemplate kafkaTemplate = context.getBean(KafkaTemplate.class); + AbstractKafkaListenerContainerFactory kafkaListenerContainerFactory = (AbstractKafkaListenerContainerFactory) context + .getBean(KafkaListenerContainerFactory.class); + assertThat(kafkaTemplate.getMessageConverter()).isInstanceOf(MessagingMessageConverter.class); + assertThat(kafkaTemplate).hasFieldOrPropertyWithValue("producerFactory", producerFactory); + assertThat(kafkaTemplate.getDefaultTopic()).isEqualTo("testTopic"); + assertThat(kafkaTemplate).hasFieldOrPropertyWithValue("transactionIdPrefix", "txOverride"); + assertThat(kafkaListenerContainerFactory.getConsumerFactory()).isEqualTo(consumerFactory); + ContainerProperties containerProperties = kafkaListenerContainerFactory.getContainerProperties(); + assertThat(containerProperties.getAckMode()).isEqualTo(AckMode.MANUAL); + assertThat(containerProperties.getClientId()).isEqualTo("client"); + assertThat(containerProperties.getAckCount()).isEqualTo(123); + assertThat(containerProperties.getAckTime()).isEqualTo(456L); + assertThat(containerProperties.getPollTimeout()).isEqualTo(2000L); + assertThat(containerProperties.getNoPollThreshold()).isEqualTo(2.5f); + assertThat(containerProperties.getIdleBetweenPolls()).isEqualTo(1000L); + assertThat(containerProperties.getIdleEventInterval()).isEqualTo(1000L); + assertThat(containerProperties.getIdlePartitionEventInterval()).isEqualTo(1000L); + assertThat(containerProperties.getMonitorInterval()).isEqualTo(45); + assertThat(containerProperties.isLogContainerConfig()).isTrue(); + assertThat(containerProperties.isMissingTopicsFatal()).isTrue(); + assertThat(containerProperties.isStopImmediate()).isTrue(); + assertThat(kafkaListenerContainerFactory).extracting("concurrency").isEqualTo(3); + assertThat(kafkaListenerContainerFactory.isBatchListener()).isTrue(); + assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).hasSize(1); + KafkaJaasLoginModuleInitializer jaas = context.getBean(KafkaJaasLoginModuleInitializer.class); + assertThat(jaas).hasFieldOrPropertyWithValue("loginModule", "foo"); + assertThat(jaas).hasFieldOrPropertyWithValue("controlFlag", + AppConfigurationEntry.LoginModuleControlFlag.REQUISITE); + assertThat(context.getBeansOfType(KafkaTransactionManager.class)).hasSize(1); + assertThat(((Map) ReflectionTestUtils.getField(jaas, "options"))) + .containsExactly(entry("useKeyTab", "true")); + }); } @Test @@ -510,7 +513,7 @@ class KafkaAutoConfigurationTests { void logOnlyRecordMetadataProperty() { this.contextRunner.withPropertyValues("spring.kafka.listener.only-log-record-metadata=true").run((context) -> { AbstractKafkaListenerContainerFactory kafkaListenerContainerFactory = (AbstractKafkaListenerContainerFactory) context - .getBean(KafkaListenerContainerFactory.class); + .getBean(KafkaListenerContainerFactory.class); ContainerProperties containerProperties = kafkaListenerContainerFactory.getContainerProperties(); assertThat(containerProperties.isOnlyLogRecordMetadata()).isTrue(); }); @@ -519,17 +522,18 @@ class KafkaAutoConfigurationTests { @Test void testKafkaTemplateRecordMessageConverters() { this.contextRunner.withUserConfiguration(MessageConverterConfiguration.class) - .withPropertyValues("spring.kafka.producer.transaction-id-prefix=test").run((context) -> { - KafkaTemplate kafkaTemplate = context.getBean(KafkaTemplate.class); - assertThat(kafkaTemplate.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); - }); + .withPropertyValues("spring.kafka.producer.transaction-id-prefix=test") + .run((context) -> { + KafkaTemplate kafkaTemplate = context.getBean(KafkaTemplate.class); + assertThat(kafkaTemplate.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); + }); } @Test void testConcurrentKafkaListenerContainerFactoryWithCustomMessageConverter() { this.contextRunner.withUserConfiguration(MessageConverterConfiguration.class).run((context) -> { ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(kafkaListenerContainerFactory).hasFieldOrPropertyWithValue("messageConverter", context.getBean("myMessageConverter")); }); @@ -538,34 +542,36 @@ class KafkaAutoConfigurationTests { @Test void testConcurrentKafkaListenerContainerFactoryInBatchModeWithCustomMessageConverter() { this.contextRunner - .withUserConfiguration(BatchMessageConverterConfiguration.class, MessageConverterConfiguration.class) - .withPropertyValues("spring.kafka.listener.type=batch").run((context) -> { - ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - assertThat(kafkaListenerContainerFactory).hasFieldOrPropertyWithValue("messageConverter", - context.getBean("myBatchMessageConverter")); - }); + .withUserConfiguration(BatchMessageConverterConfiguration.class, MessageConverterConfiguration.class) + .withPropertyValues("spring.kafka.listener.type=batch") + .run((context) -> { + ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + assertThat(kafkaListenerContainerFactory).hasFieldOrPropertyWithValue("messageConverter", + context.getBean("myBatchMessageConverter")); + }); } @Test void testConcurrentKafkaListenerContainerFactoryInBatchModeWrapsCustomMessageConverter() { this.contextRunner.withUserConfiguration(MessageConverterConfiguration.class) - .withPropertyValues("spring.kafka.listener.type=batch").run((context) -> { - ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - Object messageConverter = ReflectionTestUtils.getField(kafkaListenerContainerFactory, - "messageConverter"); - assertThat(messageConverter).isInstanceOf(BatchMessagingMessageConverter.class); - assertThat(((BatchMessageConverter) messageConverter).getRecordMessageConverter()) - .isSameAs(context.getBean("myMessageConverter")); - }); + .withPropertyValues("spring.kafka.listener.type=batch") + .run((context) -> { + ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + Object messageConverter = ReflectionTestUtils.getField(kafkaListenerContainerFactory, + "messageConverter"); + assertThat(messageConverter).isInstanceOf(BatchMessagingMessageConverter.class); + assertThat(((BatchMessageConverter) messageConverter).getRecordMessageConverter()) + .isSameAs(context.getBean("myMessageConverter")); + }); } @Test void testConcurrentKafkaListenerContainerFactoryInBatchModeWithNoMessageConverter() { this.contextRunner.withPropertyValues("spring.kafka.listener.type=batch").run((context) -> { ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); Object messageConverter = ReflectionTestUtils.getField(kafkaListenerContainerFactory, "messageConverter"); assertThat(messageConverter).isInstanceOf(BatchMessagingMessageConverter.class); assertThat(((BatchMessageConverter) messageConverter).getRecordMessageConverter()).isNull(); @@ -576,7 +582,7 @@ class KafkaAutoConfigurationTests { void testConcurrentKafkaListenerContainerFactoryWithDefaultRecordFilterStrategy() { this.contextRunner.run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(factory).hasFieldOrPropertyWithValue("recordFilterStrategy", null); }); } @@ -585,7 +591,7 @@ class KafkaAutoConfigurationTests { void testConcurrentKafkaListenerContainerFactoryWithCustomRecordFilterStrategy() { this.contextRunner.withUserConfiguration(RecordFilterStrategyConfiguration.class).run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(factory).hasFieldOrPropertyWithValue("recordFilterStrategy", context.getBean("recordFilterStrategy")); }); @@ -595,30 +601,30 @@ class KafkaAutoConfigurationTests { @Deprecated void testConcurrentKafkaListenerContainerFactoryWithCustomErrorHandler() { this.contextRunner.withBean("errorHandler", ErrorHandler.class, () -> mock(ErrorHandler.class)) - .run((context) -> { - ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - assertThat(factory).hasFieldOrPropertyWithValue("errorHandler", context.getBean("errorHandler")); - }); + .run((context) -> { + ConcurrentKafkaListenerContainerFactory factory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + assertThat(factory).hasFieldOrPropertyWithValue("errorHandler", context.getBean("errorHandler")); + }); } @Test @Deprecated void concurrentKafkaListenerContainerFactoryInBatchModeShouldUseBatchErrorHandler() { this.contextRunner.withBean("batchErrorHandler", BatchErrorHandler.class, () -> mock(BatchErrorHandler.class)) - .withPropertyValues("spring.kafka.listener.type=batch").run((context) -> { - ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - assertThat(factory).hasFieldOrPropertyWithValue("errorHandler", - context.getBean("batchErrorHandler")); - }); + .withPropertyValues("spring.kafka.listener.type=batch") + .run((context) -> { + ConcurrentKafkaListenerContainerFactory factory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + assertThat(factory).hasFieldOrPropertyWithValue("errorHandler", context.getBean("batchErrorHandler")); + }); } @Test void concurrentKafkaListenerContainerFactoryInBatchModeWhenBatchErrorHandlerNotAvailableShouldBeNull() { this.contextRunner.withPropertyValues("spring.kafka.listener.type=batch").run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(factory).hasFieldOrPropertyWithValue("errorHandler", null); }); } @@ -626,22 +632,22 @@ class KafkaAutoConfigurationTests { @Test void concurrentKafkaListenerContainerFactoryInBatchModeAndSimpleErrorHandlerShouldBeNull() { this.contextRunner.withPropertyValues("spring.kafka.listener.type=batch") - .withBean("errorHandler", ErrorHandler.class, () -> mock(ErrorHandler.class)).run((context) -> { - ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - assertThat(factory).hasFieldOrPropertyWithValue("errorHandler", null); - }); + .withBean("errorHandler", ErrorHandler.class, () -> mock(ErrorHandler.class)) + .run((context) -> { + ConcurrentKafkaListenerContainerFactory factory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + assertThat(factory).hasFieldOrPropertyWithValue("errorHandler", null); + }); } @Test void testConcurrentKafkaListenerContainerFactoryWithCustomCommonErrorHandler() { this.contextRunner.withBean("errorHandler", CommonErrorHandler.class, () -> mock(CommonErrorHandler.class)) - .run((context) -> { - ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - assertThat(factory).hasFieldOrPropertyWithValue("commonErrorHandler", - context.getBean("errorHandler")); - }); + .run((context) -> { + ConcurrentKafkaListenerContainerFactory factory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + assertThat(factory).hasFieldOrPropertyWithValue("commonErrorHandler", context.getBean("errorHandler")); + }); } @Test @@ -649,9 +655,9 @@ class KafkaAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.kafka.producer.transaction-id-prefix=test").run((context) -> { assertThat(context).hasSingleBean(KafkaAwareTransactionManager.class); ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(factory.getContainerProperties().getTransactionManager()) - .isSameAs(context.getBean(KafkaAwareTransactionManager.class)); + .isSameAs(context.getBean(KafkaAwareTransactionManager.class)); }); } @@ -660,20 +666,21 @@ class KafkaAutoConfigurationTests { void testConcurrentKafkaListenerContainerFactoryWithCustomTransactionManager() { KafkaTransactionManager customTransactionManager = mock(KafkaTransactionManager.class); this.contextRunner - .withBean("customTransactionManager", KafkaTransactionManager.class, () -> customTransactionManager) - .withPropertyValues("spring.kafka.producer.transaction-id-prefix=test").run((context) -> { - ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - assertThat(factory.getContainerProperties().getTransactionManager()) - .isSameAs(context.getBean("customTransactionManager")); - }); + .withBean("customTransactionManager", KafkaTransactionManager.class, () -> customTransactionManager) + .withPropertyValues("spring.kafka.producer.transaction-id-prefix=test") + .run((context) -> { + ConcurrentKafkaListenerContainerFactory factory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + assertThat(factory.getContainerProperties().getTransactionManager()) + .isSameAs(context.getBean("customTransactionManager")); + }); } @Test void testConcurrentKafkaListenerContainerFactoryWithCustomAfterRollbackProcessor() { this.contextRunner.withUserConfiguration(AfterRollbackProcessorConfiguration.class).run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(factory).hasFieldOrPropertyWithValue("afterRollbackProcessor", context.getBean("afterRollbackProcessor")); }); @@ -683,7 +690,7 @@ class KafkaAutoConfigurationTests { void testConcurrentKafkaListenerContainerFactoryWithCustomRecordInterceptor() { this.contextRunner.withUserConfiguration(RecordInterceptorConfiguration.class).run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(factory).hasFieldOrPropertyWithValue("recordInterceptor", context.getBean("recordInterceptor")); }); } @@ -692,7 +699,7 @@ class KafkaAutoConfigurationTests { void testConcurrentKafkaListenerContainerFactoryWithCustomRebalanceListener() { this.contextRunner.withUserConfiguration(RebalanceListenerConfiguration.class).run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(factory.getContainerProperties()).hasFieldOrPropertyWithValue("consumerRebalanceListener", context.getBean("rebalanceListener")); }); @@ -702,7 +709,7 @@ class KafkaAutoConfigurationTests { void testConcurrentKafkaListenerContainerFactoryWithKafkaTemplate() { this.contextRunner.run((context) -> { ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(kafkaListenerContainerFactory).hasFieldOrPropertyWithValue("replyTemplate", context.getBean(KafkaTemplate.class)); }); @@ -712,24 +719,24 @@ class KafkaAutoConfigurationTests { void testConcurrentKafkaListenerContainerFactoryWithCustomConsumerFactory() { this.contextRunner.withUserConfiguration(ConsumerFactoryConfiguration.class).run((context) -> { ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(kafkaListenerContainerFactory.getConsumerFactory()) - .isNotSameAs(context.getBean(ConsumerFactoryConfiguration.class).consumerFactory); + .isNotSameAs(context.getBean(ConsumerFactoryConfiguration.class).consumerFactory); }); } @Test void specificSecurityProtocolOverridesCommonSecurityProtocol() { - this.contextRunner.withPropertyValues("spring.kafka.security.protocol=SSL", - "spring.kafka.admin.security.protocol=PLAINTEXT").run((context) -> { - DefaultKafkaProducerFactory producerFactory = context - .getBean(DefaultKafkaProducerFactory.class); - Map producerConfigs = producerFactory.getConfigurationProperties(); - assertThat(producerConfigs.get(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG)).isEqualTo("SSL"); - KafkaAdmin admin = context.getBean(KafkaAdmin.class); - Map configs = admin.getConfigurationProperties(); - assertThat(configs.get(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG)).isEqualTo("PLAINTEXT"); - }); + this.contextRunner + .withPropertyValues("spring.kafka.security.protocol=SSL", "spring.kafka.admin.security.protocol=PLAINTEXT") + .run((context) -> { + DefaultKafkaProducerFactory producerFactory = context.getBean(DefaultKafkaProducerFactory.class); + Map producerConfigs = producerFactory.getConfigurationProperties(); + assertThat(producerConfigs.get(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG)).isEqualTo("SSL"); + KafkaAdmin admin = context.getBean(KafkaAdmin.class); + Map configs = admin.getConfigurationProperties(); + assertThat(configs.get(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG)).isEqualTo("PLAINTEXT"); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaPropertiesTests.java index 620e0b25ea..8b210aaa7f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,10 +44,10 @@ class KafkaPropertiesTests { @Test void isolationLevelEnumConsistentWithKafkaVersion() { org.apache.kafka.common.IsolationLevel[] original = org.apache.kafka.common.IsolationLevel.values(); - assertThat(original).extracting(Enum::name).containsExactly(IsolationLevel.READ_UNCOMMITTED.name(), - IsolationLevel.READ_COMMITTED.name()); - assertThat(original).extracting("id").containsExactly(IsolationLevel.READ_UNCOMMITTED.id(), - IsolationLevel.READ_COMMITTED.id()); + assertThat(original).extracting(Enum::name) + .containsExactly(IsolationLevel.READ_UNCOMMITTED.name(), IsolationLevel.READ_COMMITTED.name()); + assertThat(original).extracting("id") + .containsExactly(IsolationLevel.READ_UNCOMMITTED.id(), IsolationLevel.READ_COMMITTED.id()); assertThat(original).hasSize(IsolationLevel.values().length); } @@ -68,7 +68,7 @@ class KafkaPropertiesTests { assertThat(consumerProperties.get(SslConfigs.SSL_KEYSTORE_KEY_CONFIG)).isEqualTo("-----BEGINkey"); assertThat(consumerProperties.get(SslConfigs.SSL_TRUSTSTORE_CERTIFICATES_CONFIG)).isEqualTo("-----BEGINtrust"); assertThat(consumerProperties.get(SslConfigs.SSL_KEYSTORE_CERTIFICATE_CHAIN_CONFIG)) - .isEqualTo("-----BEGINchain"); + .isEqualTo("-----BEGINchain"); } @Test @@ -77,7 +77,7 @@ class KafkaPropertiesTests { properties.getSsl().setKeyStoreKey("-----BEGIN"); properties.getSsl().setKeyStoreLocation(new ClassPathResource("ksLoc")); assertThatExceptionOfType(MutuallyExclusiveConfigurationPropertiesException.class) - .isThrownBy(properties::buildConsumerProperties); + .isThrownBy(properties::buildConsumerProperties); } @Test @@ -86,7 +86,7 @@ class KafkaPropertiesTests { properties.getSsl().setTrustStoreLocation(new ClassPathResource("tsLoc")); properties.getSsl().setTrustStoreCertificates("-----BEGIN"); assertThatExceptionOfType(MutuallyExclusiveConfigurationPropertiesException.class) - .isThrownBy(properties::buildConsumerProperties); + .isThrownBy(properties::buildConsumerProperties); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kubernetes/ApplicationAvailabilityAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kubernetes/ApplicationAvailabilityAutoConfigurationTests.java index 144db9dcd0..ec2aab1bed 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kubernetes/ApplicationAvailabilityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kubernetes/ApplicationAvailabilityAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ApplicationAvailabilityAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ApplicationAvailabilityAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ApplicationAvailabilityAutoConfiguration.class)); @Test void providerIsPresent() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java index e6f7dc88e9..51c5bddb4c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ import static org.mockito.Mockito.mock; class LdapAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(LdapAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(LdapAutoConfiguration.class)); @Test void contextSourceWithDefaultUrl() { @@ -65,12 +65,12 @@ class LdapAutoConfigurationTests { @Test void contextSourceWithSeveralUrls() { this.contextRunner.withPropertyValues("spring.ldap.urls:ldap://localhost:123,ldap://mycompany:123") - .run((context) -> { - LdapContextSource contextSource = context.getBean(LdapContextSource.class); - LdapProperties ldapProperties = context.getBean(LdapProperties.class); - assertThat(contextSource.getUrls()).containsExactly("ldap://localhost:123", "ldap://mycompany:123"); - assertThat(ldapProperties.getUrls()).hasSize(2); - }); + .run((context) -> { + LdapContextSource contextSource = context.getBean(LdapContextSource.class); + LdapProperties ldapProperties = context.getBean(LdapProperties.class); + assertThat(contextSource.getUrls()).containsExactly("ldap://localhost:123", "ldap://mycompany:123"); + assertThat(ldapProperties.getUrls()).hasSize(2); + }); } @Test @@ -84,19 +84,21 @@ class LdapAutoConfigurationTests { @Test void contextSourceWithExtraCustomization() { - this.contextRunner.withPropertyValues("spring.ldap.urls:ldap://localhost:123", "spring.ldap.username:root", - "spring.ldap.password:secret", "spring.ldap.anonymous-read-only:true", - "spring.ldap.base:cn=SpringDevelopers", - "spring.ldap.baseEnvironment.java.naming.security.authentication:DIGEST-MD5").run((context) -> { - LdapContextSource contextSource = context.getBean(LdapContextSource.class); - assertThat(contextSource.getUserDn()).isEqualTo("root"); - assertThat(contextSource.getPassword()).isEqualTo("secret"); - assertThat(contextSource.isAnonymousReadOnly()).isTrue(); - assertThat(contextSource.getBaseLdapPathAsString()).isEqualTo("cn=SpringDevelopers"); - LdapProperties ldapProperties = context.getBean(LdapProperties.class); - assertThat(ldapProperties.getBaseEnvironment()).containsEntry("java.naming.security.authentication", - "DIGEST-MD5"); - }); + this.contextRunner + .withPropertyValues("spring.ldap.urls:ldap://localhost:123", "spring.ldap.username:root", + "spring.ldap.password:secret", "spring.ldap.anonymous-read-only:true", + "spring.ldap.base:cn=SpringDevelopers", + "spring.ldap.baseEnvironment.java.naming.security.authentication:DIGEST-MD5") + .run((context) -> { + LdapContextSource contextSource = context.getBean(LdapContextSource.class); + assertThat(contextSource.getUserDn()).isEqualTo("root"); + assertThat(contextSource.getPassword()).isEqualTo("secret"); + assertThat(contextSource.isAnonymousReadOnly()).isTrue(); + assertThat(contextSource.getBaseLdapPathAsString()).isEqualTo("cn=SpringDevelopers"); + LdapProperties ldapProperties = context.getBean(LdapProperties.class); + assertThat(ldapProperties.getBaseEnvironment()).containsEntry("java.naming.security.authentication", + "DIGEST-MD5"); + }); } @Test @@ -123,16 +125,18 @@ class LdapAutoConfigurationTests { @Test void templateConfigurationCanBeCustomized() { - this.contextRunner.withPropertyValues("spring.ldap.urls:ldap://localhost:389", - "spring.ldap.template.ignorePartialResultException=true", - "spring.ldap.template.ignoreNameNotFoundException=true", - "spring.ldap.template.ignoreSizeLimitExceededException=false").run((context) -> { - assertThat(context).hasSingleBean(LdapTemplate.class); - LdapTemplate ldapTemplate = context.getBean(LdapTemplate.class); - assertThat(ldapTemplate).hasFieldOrPropertyWithValue("ignorePartialResultException", true); - assertThat(ldapTemplate).hasFieldOrPropertyWithValue("ignoreNameNotFoundException", true); - assertThat(ldapTemplate).hasFieldOrPropertyWithValue("ignoreSizeLimitExceededException", false); - }); + this.contextRunner + .withPropertyValues("spring.ldap.urls:ldap://localhost:389", + "spring.ldap.template.ignorePartialResultException=true", + "spring.ldap.template.ignoreNameNotFoundException=true", + "spring.ldap.template.ignoreSizeLimitExceededException=false") + .run((context) -> { + assertThat(context).hasSingleBean(LdapTemplate.class); + LdapTemplate ldapTemplate = context.getBean(LdapTemplate.class); + assertThat(ldapTemplate).hasFieldOrPropertyWithValue("ignorePartialResultException", true); + assertThat(ldapTemplate).hasFieldOrPropertyWithValue("ignoreNameNotFoundException", true); + assertThat(ldapTemplate).hasFieldOrPropertyWithValue("ignoreSizeLimitExceededException", false); + }); } @Test @@ -150,22 +154,24 @@ class LdapAutoConfigurationTests { assertThat(context).hasSingleBean(DirContextAuthenticationStrategy.class); LdapContextSource contextSource = context.getBean(LdapContextSource.class); assertThat(contextSource).extracting("authenticationStrategy") - .isSameAs(context.getBean("customDirContextAuthenticationStrategy")); + .isSameAs(context.getBean("customDirContextAuthenticationStrategy")); }); } @Test void contextSourceWithCustomNonUniqueDirContextAuthenticationStrategy() { - this.contextRunner.withUserConfiguration(CustomDirContextAuthenticationStrategy.class, - AnotherCustomDirContextAuthenticationStrategy.class).run((context) -> { - assertThat(context).hasBean("customDirContextAuthenticationStrategy") - .hasBean("anotherCustomDirContextAuthenticationStrategy"); - LdapContextSource contextSource = context.getBean(LdapContextSource.class); - assertThat(contextSource).extracting("authenticationStrategy") - .isNotSameAs(context.getBean("customDirContextAuthenticationStrategy")) - .isNotSameAs(context.getBean("anotherCustomDirContextAuthenticationStrategy")) - .isInstanceOf(SimpleDirContextAuthenticationStrategy.class); - }); + this.contextRunner + .withUserConfiguration(CustomDirContextAuthenticationStrategy.class, + AnotherCustomDirContextAuthenticationStrategy.class) + .run((context) -> { + assertThat(context).hasBean("customDirContextAuthenticationStrategy") + .hasBean("anotherCustomDirContextAuthenticationStrategy"); + LdapContextSource contextSource = context.getBean(LdapContextSource.class); + assertThat(contextSource).extracting("authenticationStrategy") + .isNotSameAs(context.getBean("customDirContextAuthenticationStrategy")) + .isNotSameAs(context.getBean("anotherCustomDirContextAuthenticationStrategy")) + .isInstanceOf(SimpleDirContextAuthenticationStrategy.class); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java index 8a5e571a4c..dd0ec514a1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java @@ -47,16 +47,16 @@ import static org.assertj.core.api.Assertions.assertThat; class EmbeddedLdapAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(EmbeddedLdapAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(EmbeddedLdapAutoConfiguration.class)); @Test void testSetDefaultPort() { this.contextRunner - .withPropertyValues("spring.ldap.embedded.port:1234", "spring.ldap.embedded.base-dn:dc=spring,dc=org") - .run((context) -> { - InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); - assertThat(server.getListenPort()).isEqualTo(1234); - }); + .withPropertyValues("spring.ldap.embedded.port:1234", "spring.ldap.embedded.base-dn:dc=spring,dc=org") + .run((context) -> { + InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); + assertThat(server.getListenPort()).isEqualTo(1234); + }); } @Test @@ -64,7 +64,7 @@ class EmbeddedLdapAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org").run((context) -> { InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); assertThat(server.getListenPort()) - .isEqualTo(context.getEnvironment().getProperty("local.ldap.port", Integer.class)); + .isEqualTo(context.getEnvironment().getProperty("local.ldap.port", Integer.class)); }); } @@ -77,18 +77,18 @@ class EmbeddedLdapAutoConfigurationTests { context.refresh(); LDAPConnection connection = context.getBean(LDAPConnection.class); assertThat(connection.getConnectedPort()) - .isEqualTo(context.getEnvironment().getProperty("local.ldap.port", Integer.class)); + .isEqualTo(context.getEnvironment().getProperty("local.ldap.port", Integer.class)); } @Test void testSetCredentials() { this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org", "spring.ldap.embedded.credential.username:uid=root", "spring.ldap.embedded.credential.password:boot") - .run((context) -> { - InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); - BindResult result = server.bind("uid=root", "boot"); - assertThat(result).isNotNull(); - }); + .run((context) -> { + InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); + BindResult result = server.bind("uid=root", "boot"); + assertThat(result).isNotNull(); + }); } @Test @@ -110,54 +110,59 @@ class EmbeddedLdapAutoConfigurationTests { @Test void testQueryEmbeddedLdap() { this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org") - .withConfiguration(AutoConfigurations.of(LdapAutoConfiguration.class)).run((context) -> { - assertThat(context).hasSingleBean(LdapTemplate.class); - LdapTemplate ldapTemplate = context.getBean(LdapTemplate.class); - assertThat(ldapTemplate.list("ou=company1,c=Sweden,dc=spring,dc=org")).hasSize(4); - }); + .withConfiguration(AutoConfigurations.of(LdapAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasSingleBean(LdapTemplate.class); + LdapTemplate ldapTemplate = context.getBean(LdapTemplate.class); + assertThat(ldapTemplate.list("ou=company1,c=Sweden,dc=spring,dc=org")).hasSize(4); + }); } @Test void testDisableSchemaValidation() { - this.contextRunner.withPropertyValues("spring.ldap.embedded.validation.enabled:false", - "spring.ldap.embedded.base-dn:dc=spring,dc=org").run((context) -> { - InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); - assertThat(server.getSchema()).isNull(); - }); + this.contextRunner + .withPropertyValues("spring.ldap.embedded.validation.enabled:false", + "spring.ldap.embedded.base-dn:dc=spring,dc=org") + .run((context) -> { + InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); + assertThat(server.getSchema()).isNull(); + }); } @Test void testCustomSchemaValidation() { - this.contextRunner.withPropertyValues("spring.ldap.embedded.validation.schema:classpath:custom-schema.ldif", - "spring.ldap.embedded.ldif:classpath:custom-schema-sample.ldif", - "spring.ldap.embedded.base-dn:dc=spring,dc=org").run((context) -> { - InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); - - assertThat(server.getSchema().getObjectClass("exampleAuxiliaryClass")).isNotNull(); - assertThat(server.getSchema().getAttributeType("exampleAttributeName")).isNotNull(); - }); + this.contextRunner + .withPropertyValues("spring.ldap.embedded.validation.schema:classpath:custom-schema.ldif", + "spring.ldap.embedded.ldif:classpath:custom-schema-sample.ldif", + "spring.ldap.embedded.base-dn:dc=spring,dc=org") + .run((context) -> { + InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); + + assertThat(server.getSchema().getObjectClass("exampleAuxiliaryClass")).isNotNull(); + assertThat(server.getSchema().getAttributeType("exampleAttributeName")).isNotNull(); + }); } @Test void testMultiBaseDn() { this.contextRunner.withPropertyValues("spring.ldap.embedded.ldif:classpath:schema-multi-basedn.ldif", "spring.ldap.embedded.base-dn[0]:dc=spring,dc=org", "spring.ldap.embedded.base-dn[1]:dc=vmware,dc=com") - .run((context) -> { - InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); - assertThat(server.countEntriesBelow("ou=company1,c=Sweden,dc=spring,dc=org")).isEqualTo(5); - assertThat(server.countEntriesBelow("c=Sweden,dc=vmware,dc=com")).isEqualTo(2); - }); + .run((context) -> { + InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); + assertThat(server.countEntriesBelow("ou=company1,c=Sweden,dc=spring,dc=org")).isEqualTo(5); + assertThat(server.countEntriesBelow("c=Sweden,dc=vmware,dc=com")).isEqualTo(2); + }); } @Test void ldapContextSourceWithCredentialsIsCreated() { this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org", "spring.ldap.embedded.credential.username:uid=root", "spring.ldap.embedded.credential.password:boot") - .run((context) -> { - LdapContextSource ldapContextSource = context.getBean(LdapContextSource.class); - assertThat(ldapContextSource.getUrls()).isNotEmpty(); - assertThat(ldapContextSource.getUserDn()).isEqualTo("uid=root"); - }); + .run((context) -> { + LdapContextSource ldapContextSource = context.getBean(LdapContextSource.class); + assertThat(ldapContextSource.getUrls()).isNotEmpty(); + assertThat(ldapContextSource.getUserDn()).isEqualTo("uid=root"); + }); } @Test @@ -172,10 +177,11 @@ class EmbeddedLdapAutoConfigurationTests { @Test void ldapContextWithoutSpringLdapIsNotCreated() { this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org") - .withClassLoader(new FilteredClassLoader(ContextSource.class)).run((context) -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(LdapContextSource.class); - }); + .withClassLoader(new FilteredClassLoader(ContextSource.class)) + .run((context) -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(LdapContextSource.class); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java index da2c65f98d..2c73264800 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,8 +77,8 @@ import static org.assertj.core.api.Assertions.contentOf; class LiquibaseAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true"); + .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test void backsOffWithNoDataSourceBeanAndNoLiquibaseUrl() { @@ -97,118 +97,119 @@ class LiquibaseAutoConfigurationTests { @Test void backsOffWithLiquibaseUrlAndNoSpringJdbc() { this.contextRunner.withPropertyValues("spring.liquibase.url:jdbc:hsqldb:mem:" + UUID.randomUUID()) - .withClassLoader(new FilteredClassLoader("org.springframework.jdbc")) - .run((context) -> assertThat(context).doesNotHaveBean(SpringLiquibase.class)); + .withClassLoader(new FilteredClassLoader("org.springframework.jdbc")) + .run((context) -> assertThat(context).doesNotHaveBean(SpringLiquibase.class)); } @Test void defaultSpringLiquibase() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .run(assertLiquibase((liquibase) -> { - assertThat(liquibase.getChangeLog()).isEqualTo("classpath:/db/changelog/db.changelog-master.yaml"); - assertThat(liquibase.getContexts()).isNull(); - assertThat(liquibase.getDefaultSchema()).isNull(); - assertThat(liquibase.isDropFirst()).isFalse(); - assertThat(liquibase.isClearCheckSums()).isFalse(); - })); + .run(assertLiquibase((liquibase) -> { + assertThat(liquibase.getChangeLog()).isEqualTo("classpath:/db/changelog/db.changelog-master.yaml"); + assertThat(liquibase.getContexts()).isNull(); + assertThat(liquibase.getDefaultSchema()).isNull(); + assertThat(liquibase.isDropFirst()).isFalse(); + assertThat(liquibase.isClearCheckSums()).isFalse(); + })); } @Test void changelogXml() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.xml") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog()) - .isEqualTo("classpath:/db/changelog/db.changelog-override.xml"))); + .withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.xml") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog()) + .isEqualTo("classpath:/db/changelog/db.changelog-override.xml"))); } @Test void changelogJson() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.json") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog()) - .isEqualTo("classpath:/db/changelog/db.changelog-override.json"))); + .withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.json") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog()) + .isEqualTo("classpath:/db/changelog/db.changelog-override.json"))); } @Test void changelogSql() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.sql") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog()) - .isEqualTo("classpath:/db/changelog/db.changelog-override.sql"))); + .withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.sql") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog()) + .isEqualTo("classpath:/db/changelog/db.changelog-override.sql"))); } @Test void defaultValues() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .run(assertLiquibase((liquibase) -> { - LiquibaseProperties properties = new LiquibaseProperties(); - assertThat(liquibase.getDatabaseChangeLogTable()).isEqualTo(properties.getDatabaseChangeLogTable()); - assertThat(liquibase.getDatabaseChangeLogLockTable()) - .isEqualTo(properties.getDatabaseChangeLogLockTable()); - assertThat(liquibase.isDropFirst()).isEqualTo(properties.isDropFirst()); - assertThat(liquibase.isClearCheckSums()).isEqualTo(properties.isClearChecksums()); - assertThat(liquibase.isTestRollbackOnUpdate()).isEqualTo(properties.isTestRollbackOnUpdate()); - })); + .run(assertLiquibase((liquibase) -> { + LiquibaseProperties properties = new LiquibaseProperties(); + assertThat(liquibase.getDatabaseChangeLogTable()).isEqualTo(properties.getDatabaseChangeLogTable()); + assertThat(liquibase.getDatabaseChangeLogLockTable()) + .isEqualTo(properties.getDatabaseChangeLogLockTable()); + assertThat(liquibase.isDropFirst()).isEqualTo(properties.isDropFirst()); + assertThat(liquibase.isClearCheckSums()).isEqualTo(properties.isClearChecksums()); + assertThat(liquibase.isTestRollbackOnUpdate()).isEqualTo(properties.isTestRollbackOnUpdate()); + })); } @Test void overrideContexts() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.contexts:test, production") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.getContexts()).isEqualTo("test, production"))); + .withPropertyValues("spring.liquibase.contexts:test, production") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getContexts()).isEqualTo("test, production"))); } @Test void overrideDefaultSchema() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.default-schema:public") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.getDefaultSchema()).isEqualTo("public"))); + .withPropertyValues("spring.liquibase.default-schema:public") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getDefaultSchema()).isEqualTo("public"))); } @Test void overrideLiquibaseInfrastructure() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.liquibase-schema:public", - "spring.liquibase.liquibase-tablespace:infra", - "spring.liquibase.database-change-log-table:LIQUI_LOG", - "spring.liquibase.database-change-log-lock-table:LIQUI_LOCK") - .run((context) -> { - SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); - assertThat(liquibase.getLiquibaseSchema()).isEqualTo("public"); - assertThat(liquibase.getLiquibaseTablespace()).isEqualTo("infra"); - assertThat(liquibase.getDatabaseChangeLogTable()).isEqualTo("LIQUI_LOG"); - assertThat(liquibase.getDatabaseChangeLogLockTable()).isEqualTo("LIQUI_LOCK"); - JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getBean(DataSource.class)); - assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM public.LIQUI_LOG", Integer.class)) - .isEqualTo(1); - assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM public.LIQUI_LOCK", Integer.class)) - .isEqualTo(1); - }); + .withPropertyValues("spring.liquibase.liquibase-schema:public", + "spring.liquibase.liquibase-tablespace:infra", + "spring.liquibase.database-change-log-table:LIQUI_LOG", + "spring.liquibase.database-change-log-lock-table:LIQUI_LOCK") + .run((context) -> { + SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); + assertThat(liquibase.getLiquibaseSchema()).isEqualTo("public"); + assertThat(liquibase.getLiquibaseTablespace()).isEqualTo("infra"); + assertThat(liquibase.getDatabaseChangeLogTable()).isEqualTo("LIQUI_LOG"); + assertThat(liquibase.getDatabaseChangeLogLockTable()).isEqualTo("LIQUI_LOCK"); + JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getBean(DataSource.class)); + assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM public.LIQUI_LOG", Integer.class)) + .isEqualTo(1); + assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM public.LIQUI_LOCK", Integer.class)) + .isEqualTo(1); + }); } @Test void overrideDropFirst() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.drop-first:true") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.isDropFirst()).isTrue())); + .withPropertyValues("spring.liquibase.drop-first:true") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.isDropFirst()).isTrue())); } @Test void overrideClearChecksums() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.clear-checksums:true") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.isClearCheckSums()).isTrue())); + .withPropertyValues("spring.liquibase.clear-checksums:true") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.isClearCheckSums()).isTrue())); } @Test void overrideDataSource() { String jdbcUrl = "jdbc:hsqldb:mem:liquibase" + UUID.randomUUID(); this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.url:" + jdbcUrl).run(assertLiquibase((liquibase) -> { - SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); - assertThat(dataSource.getUrl()).isEqualTo(jdbcUrl); - assertThat(dataSource.getDriver().getClass().getName()).isEqualTo("org.hsqldb.jdbc.JDBCDriver"); - })); + .withPropertyValues("spring.liquibase.url:" + jdbcUrl) + .run(assertLiquibase((liquibase) -> { + SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); + assertThat(dataSource.getUrl()).isEqualTo(jdbcUrl); + assertThat(dataSource.getDriver().getClass().getName()).isEqualTo("org.hsqldb.jdbc.JDBCDriver"); + })); } @Test @@ -216,124 +217,131 @@ class LiquibaseAutoConfigurationTests { String jdbcUrl = "jdbc:hsqldb:mem:liquibase" + UUID.randomUUID(); String driverClassName = "org.hsqldb.jdbcDriver"; this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.url:" + jdbcUrl, - "spring.liquibase.driver-class-name:" + driverClassName) - .run(assertLiquibase((liquibase) -> { - SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); - assertThat(dataSource.getUrl()).isEqualTo(jdbcUrl); - assertThat(dataSource.getDriver().getClass().getName()).isEqualTo(driverClassName); - })); + .withPropertyValues("spring.liquibase.url:" + jdbcUrl, + "spring.liquibase.driver-class-name:" + driverClassName) + .run(assertLiquibase((liquibase) -> { + SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); + assertThat(dataSource.getUrl()).isEqualTo(jdbcUrl); + assertThat(dataSource.getDriver().getClass().getName()).isEqualTo(driverClassName); + })); } @Test void overrideUser() { String databaseName = "normal" + UUID.randomUUID(); this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.datasource.generate-unique-name:false", - "spring.datasource.name:" + databaseName, "spring.datasource.username:not-sa", - "spring.liquibase.user:sa") - .run(assertLiquibase((liquibase) -> { - SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); - assertThat(dataSource.getUrl()).contains("jdbc:h2:mem:" + databaseName); - assertThat(dataSource.getUsername()).isEqualTo("sa"); - })); + .withPropertyValues("spring.datasource.generate-unique-name:false", + "spring.datasource.name:" + databaseName, "spring.datasource.username:not-sa", + "spring.liquibase.user:sa") + .run(assertLiquibase((liquibase) -> { + SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); + assertThat(dataSource.getUrl()).contains("jdbc:h2:mem:" + databaseName); + assertThat(dataSource.getUsername()).isEqualTo("sa"); + })); } @Test void overrideUserWhenCustom() { this.contextRunner.withUserConfiguration(CustomDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.user:test", "spring.liquibase.password:secret").run((context) -> { - String expectedName = context.getBean(CustomDataSourceConfiguration.class).name; - SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); - SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); - assertThat(dataSource.getUrl()).contains(expectedName); - assertThat(dataSource.getUsername()).isEqualTo("test"); - }); + .withPropertyValues("spring.liquibase.user:test", "spring.liquibase.password:secret") + .run((context) -> { + String expectedName = context.getBean(CustomDataSourceConfiguration.class).name; + SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); + SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); + assertThat(dataSource.getUrl()).contains(expectedName); + assertThat(dataSource.getUsername()).isEqualTo("test"); + }); } @Test void createDataSourceDoesNotFallbackToEmbeddedProperties() { String jdbcUrl = "jdbc:hsqldb:mem:liquibase" + UUID.randomUUID(); this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.url:" + jdbcUrl).run(assertLiquibase((liquibase) -> { - SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); - assertThat(dataSource.getUsername()).isNull(); - assertThat(dataSource.getPassword()).isNull(); - })); + .withPropertyValues("spring.liquibase.url:" + jdbcUrl) + .run(assertLiquibase((liquibase) -> { + SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); + assertThat(dataSource.getUsername()).isNull(); + assertThat(dataSource.getPassword()).isNull(); + })); } @Test void overrideUserAndFallbackToEmbeddedProperties() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.user:sa").run(assertLiquibase((liquibase) -> { - SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); - assertThat(dataSource.getUrl()).startsWith("jdbc:h2:mem:"); - })); + .withPropertyValues("spring.liquibase.user:sa") + .run(assertLiquibase((liquibase) -> { + SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); + assertThat(dataSource.getUrl()).startsWith("jdbc:h2:mem:"); + })); } @Test void overrideTestRollbackOnUpdate() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.test-rollback-on-update:true").run((context) -> { - SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); - assertThat(liquibase.isTestRollbackOnUpdate()).isTrue(); - }); + .withPropertyValues("spring.liquibase.test-rollback-on-update:true") + .run((context) -> { + SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); + assertThat(liquibase.isTestRollbackOnUpdate()).isTrue(); + }); } @Test void changeLogDoesNotExist() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.change-log:classpath:/no-such-changelog.yaml").run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().isInstanceOf(BeanCreationException.class); - }); + .withPropertyValues("spring.liquibase.change-log:classpath:/no-such-changelog.yaml") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().isInstanceOf(BeanCreationException.class); + }); } @Test void logging(CapturedOutput output) { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .run(assertLiquibase((liquibase) -> assertThat(output).doesNotContain(": liquibase:"))); + .run(assertLiquibase((liquibase) -> assertThat(output).doesNotContain(": liquibase:"))); } @Test void overrideLabels() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.labels:test, production") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.getLabels()).isEqualTo("test, production"))); + .withPropertyValues("spring.liquibase.labels:test, production") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getLabels()).isEqualTo("test, production"))); } @Test @SuppressWarnings("unchecked") void testOverrideParameters() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.parameters.foo:bar").run(assertLiquibase((liquibase) -> { - Map parameters = (Map) ReflectionTestUtils.getField(liquibase, - "parameters"); - assertThat(parameters).containsKey("foo"); - assertThat(parameters.get("foo")).isEqualTo("bar"); - })); + .withPropertyValues("spring.liquibase.parameters.foo:bar") + .run(assertLiquibase((liquibase) -> { + Map parameters = (Map) ReflectionTestUtils.getField(liquibase, + "parameters"); + assertThat(parameters).containsKey("foo"); + assertThat(parameters.get("foo")).isEqualTo("bar"); + })); } @Test void rollbackFile(@TempDir Path temp) throws IOException { File file = Files.createTempFile(temp, "rollback-file", "sql").toFile(); this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.rollbackFile:" + file.getAbsolutePath()).run((context) -> { - SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); - File actualFile = (File) ReflectionTestUtils.getField(liquibase, "rollbackFile"); - assertThat(actualFile).isEqualTo(file).exists(); - assertThat(contentOf(file)).contains("DROP TABLE PUBLIC.customer;"); - }); + .withPropertyValues("spring.liquibase.rollbackFile:" + file.getAbsolutePath()) + .run((context) -> { + SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); + File actualFile = (File) ReflectionTestUtils.getField(liquibase, "rollbackFile"); + assertThat(actualFile).isEqualTo(file).exists(); + assertThat(contentOf(file)).contains("DROP TABLE PUBLIC.customer;"); + }); } @Test void liquibaseDataSource() { this.contextRunner - .withUserConfiguration(LiquibaseDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); - assertThat(liquibase.getDataSource()).isEqualTo(context.getBean("liquibaseDataSource")); - }); + .withUserConfiguration(LiquibaseDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { + SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); + assertThat(liquibase.getDataSource()).isEqualTo(context.getBean("liquibaseDataSource")); + }); } @Test @@ -347,57 +355,58 @@ class LiquibaseAutoConfigurationTests { @Test void userConfigurationBeans() { this.contextRunner - .withUserConfiguration(LiquibaseUserConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).hasBean("springLiquibase"); - assertThat(context).doesNotHaveBean("liquibase"); - }); + .withUserConfiguration(LiquibaseUserConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { + assertThat(context).hasBean("springLiquibase"); + assertThat(context).doesNotHaveBean("liquibase"); + }); } @Test void userConfigurationEntityManagerFactoryDependency() { this.contextRunner.withConfiguration(AutoConfigurations.of(HibernateJpaAutoConfiguration.class)) - .withUserConfiguration(LiquibaseUserConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("entityManagerFactory"); - assertThat(beanDefinition.getDependsOn()).containsExactly("springLiquibase"); - }); + .withUserConfiguration(LiquibaseUserConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("entityManagerFactory"); + assertThat(beanDefinition.getDependsOn()).containsExactly("springLiquibase"); + }); } @Test void userConfigurationJdbcTemplateDependency() { this.contextRunner.withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class)) - .withUserConfiguration(LiquibaseUserConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("jdbcTemplate"); - assertThat(beanDefinition.getDependsOn()).containsExactly("springLiquibase"); - }); + .withUserConfiguration(LiquibaseUserConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("jdbcTemplate"); + assertThat(beanDefinition.getDependsOn()).containsExactly("springLiquibase"); + }); } @Test void overrideTag() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.tag:1.0.0") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.getTag()).isEqualTo("1.0.0"))); + .withPropertyValues("spring.liquibase.tag:1.0.0") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getTag()).isEqualTo("1.0.0"))); } @Test void whenLiquibaseIsAutoConfiguredThenJooqDslContextDependsOnSpringLiquibaseBeans() { this.contextRunner.withConfiguration(AutoConfigurations.of(JooqAutoConfiguration.class)) - .withUserConfiguration(EmbeddedDataSourceConfiguration.class).run((context) -> { - BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); - assertThat(beanDefinition.getDependsOn()).containsExactly("liquibase"); - }); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class) + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); + assertThat(beanDefinition.getDependsOn()).containsExactly("liquibase"); + }); } @Test void whenCustomSpringLiquibaseIsDefinedThenJooqDslContextDependsOnSpringLiquibaseBeans() { this.contextRunner.withConfiguration(AutoConfigurations.of(JooqAutoConfiguration.class)) - .withUserConfiguration(LiquibaseUserConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); - assertThat(beanDefinition.getDependsOn()).containsExactly("springLiquibase"); - }); + .withUserConfiguration(LiquibaseUserConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); + assertThat(beanDefinition.getDependsOn()).containsExactly("springLiquibase"); + }); } private ContextConsumer assertLiquibase(Consumer consumer) { @@ -420,8 +429,10 @@ class LiquibaseAutoConfigurationTests { @LiquibaseDataSource @Bean DataSource liquibaseDataSource() { - return DataSourceBuilder.create().url("jdbc:hsqldb:mem:liquibasetest" + UUID.randomUUID()).username("sa") - .build(); + return DataSourceBuilder.create() + .url("jdbc:hsqldb:mem:liquibasetest" + UUID.randomUUID()) + .username("sa") + .build(); } } @@ -448,7 +459,8 @@ class LiquibaseAutoConfigurationTests { @Bean(destroyMethod = "shutdown") EmbeddedDatabase dataSource() throws SQLException { EmbeddedDatabase database = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) - .setName(this.name).build(); + .setName(this.name) + .build(); insertUser(database); return database; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java index d986541b78..605365785b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,8 +74,8 @@ class ConditionEvaluationReportLoggingListenerTests { this.initializer.initialize(context); context.register(ErrorConfig.class); assertThatExceptionOfType(Exception.class).isThrownBy(context::refresh) - .satisfies((ex) -> withDebugLogging(() -> this.initializer.onApplicationEvent( - new ApplicationFailedEvent(new SpringApplication(), new String[0], context, ex)))); + .satisfies((ex) -> withDebugLogging(() -> this.initializer + .onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(), new String[0], context, ex)))); assertThat(output).contains("CONDITIONS EVALUATION REPORT"); } @@ -84,7 +84,8 @@ class ConditionEvaluationReportLoggingListenerTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); this.initializer.initialize(context); context.register(ErrorConfig.class); - assertThatExceptionOfType(Exception.class).isThrownBy(context::refresh).satisfies((ex) -> this.initializer + assertThatExceptionOfType(Exception.class).isThrownBy(context::refresh) + .satisfies((ex) -> this.initializer .onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(), new String[0], context, ex))); assertThat(output).contains("Error starting ApplicationContext. To display the conditions report re-run" + " your application with 'debug' enabled."); @@ -135,8 +136,8 @@ class ConditionEvaluationReportLoggingListenerTests { @Test void listenerSupportsOnlyInfoAndDebug() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ConditionEvaluationReportLoggingListener(LogLevel.TRACE)) - .withMessageContaining("LogLevel must be INFO or DEBUG"); + .isThrownBy(() -> new ConditionEvaluationReportLoggingListener(LogLevel.TRACE)) + .withMessageContaining("LogLevel must be INFO or DEBUG"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java index 3b4089357d..e56fc5513e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -91,29 +91,31 @@ class MailSenderAutoConfigurationTests { @Test void smtpHostWithSettings() { String host = "192.168.1.234"; - this.contextRunner.withPropertyValues("spring.mail.host:" + host, "spring.mail.port:42", - "spring.mail.username:john", "spring.mail.password:secret", "spring.mail.default-encoding:US-ASCII", - "spring.mail.protocol:smtps").run((context) -> { - assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); - assertThat(mailSender.getHost()).isEqualTo(host); - assertThat(mailSender.getPort()).isEqualTo(42); - assertThat(mailSender.getUsername()).isEqualTo("john"); - assertThat(mailSender.getPassword()).isEqualTo("secret"); - assertThat(mailSender.getDefaultEncoding()).isEqualTo("US-ASCII"); - assertThat(mailSender.getProtocol()).isEqualTo("smtps"); - }); + this.contextRunner + .withPropertyValues("spring.mail.host:" + host, "spring.mail.port:42", "spring.mail.username:john", + "spring.mail.password:secret", "spring.mail.default-encoding:US-ASCII", + "spring.mail.protocol:smtps") + .run((context) -> { + assertThat(context).hasSingleBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); + assertThat(mailSender.getHost()).isEqualTo(host); + assertThat(mailSender.getPort()).isEqualTo(42); + assertThat(mailSender.getUsername()).isEqualTo("john"); + assertThat(mailSender.getPassword()).isEqualTo("secret"); + assertThat(mailSender.getDefaultEncoding()).isEqualTo("US-ASCII"); + assertThat(mailSender.getProtocol()).isEqualTo("smtps"); + }); } @Test void smtpHostWithJavaMailProperties() { this.contextRunner - .withPropertyValues("spring.mail.host:localhost", "spring.mail.properties.mail.smtp.auth:true") - .run((context) -> { - assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); - assertThat(mailSender.getJavaMailProperties().get("mail.smtp.auth")).isEqualTo("true"); - }); + .withPropertyValues("spring.mail.host:localhost", "spring.mail.properties.mail.smtp.auth:true") + .run((context) -> { + assertThat(context).hasSingleBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); + assertThat(mailSender.getJavaMailProperties().get("mail.smtp.auth")).isEqualTo("true"); + }); } @Test @@ -124,14 +126,14 @@ class MailSenderAutoConfigurationTests { @Test void mailSenderBackOff() { this.contextRunner.withUserConfiguration(ManualMailConfiguration.class) - .withPropertyValues("spring.mail.host:smtp.acme.org", "spring.mail.user:user", - "spring.mail.password:secret") - .run((context) -> { - assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); - assertThat(mailSender.getUsername()).isNull(); - assertThat(mailSender.getPassword()).isNull(); - }); + .withPropertyValues("spring.mail.host:smtp.acme.org", "spring.mail.user:user", + "spring.mail.password:secret") + .run((context) -> { + assertThat(context).hasSingleBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); + assertThat(mailSender.getUsername()).isNull(); + assertThat(mailSender.getPassword()).isNull(); + }); } @Test @@ -179,7 +181,7 @@ class MailSenderAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.mail.jndi-name:foo").run((context) -> { assertThat(context).hasFailed(); assertThat(context.getStartupFailure()).isInstanceOf(BeanCreationException.class) - .hasMessageContaining("Unable to find Session in JNDI location foo"); + .hasMessageContaining("Unable to find Session in JNDI location foo"); }); } @@ -187,54 +189,55 @@ class MailSenderAutoConfigurationTests { void jndiSessionTakesPrecedenceOverProperties() { Session session = configureJndiSession("foo"); this.contextRunner.withPropertyValues("spring.mail.jndi-name:foo", "spring.mail.host:localhost") - .run((context) -> { - assertThat(context).hasSingleBean(Session.class); - Session sessionBean = context.getBean(Session.class); - assertThat(sessionBean).isEqualTo(session); - assertThat(context.getBean(JavaMailSenderImpl.class).getSession()).isEqualTo(sessionBean); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Session.class); + Session sessionBean = context.getBean(Session.class); + assertThat(sessionBean).isEqualTo(session); + assertThat(context.getBean(JavaMailSenderImpl.class).getSession()).isEqualTo(sessionBean); + }); } @Test void defaultEncodingWithProperties() { this.contextRunner.withPropertyValues("spring.mail.host:localhost", "spring.mail.default-encoding:UTF-16") - .run((context) -> { - assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); - assertThat(mailSender.getDefaultEncoding()).isEqualTo("UTF-16"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); + assertThat(mailSender.getDefaultEncoding()).isEqualTo("UTF-16"); + }); } @Test void defaultEncodingWithJndi() { configureJndiSession("foo"); this.contextRunner.withPropertyValues("spring.mail.jndi-name:foo", "spring.mail.default-encoding:UTF-16") - .run((context) -> { - assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); - assertThat(mailSender.getDefaultEncoding()).isEqualTo("UTF-16"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); + assertThat(mailSender.getDefaultEncoding()).isEqualTo("UTF-16"); + }); } @Test void connectionOnStartup() { this.contextRunner.withUserConfiguration(MockMailConfiguration.class) - .withPropertyValues("spring.mail.host:10.0.0.23", "spring.mail.test-connection:true").run((context) -> { - assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); - then(mailSender).should().testConnection(); - }); + .withPropertyValues("spring.mail.host:10.0.0.23", "spring.mail.test-connection:true") + .run((context) -> { + assertThat(context).hasSingleBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); + then(mailSender).should().testConnection(); + }); } @Test void connectionOnStartupNotCalled() { this.contextRunner.withUserConfiguration(MockMailConfiguration.class) - .withPropertyValues("spring.mail.host:10.0.0.23", "spring.mail.test-connection:false") - .run((context) -> { - assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); - then(mailSender).should(never()).testConnection(); - }); + .withPropertyValues("spring.mail.host:10.0.0.23", "spring.mail.test-connection:false") + .run((context) -> { + assertThat(context).hasSingleBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); + then(mailSender).should(never()).testConnection(); + }); } private Session configureJndiSession(String name) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java index b6ff9c5521..abe1ec7a09 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; class MongoAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)); @Test void clientExists() { @@ -52,36 +52,36 @@ class MongoAutoConfigurationTests { @Test void settingsAdded() { this.contextRunner.withUserConfiguration(SettingsConfig.class) - .run((context) -> assertThat( - getSettings(context).getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)) - .isEqualTo(300)); + .run((context) -> assertThat( + getSettings(context).getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)) + .isEqualTo(300)); } @Test void settingsAddedButNoHost() { this.contextRunner.withUserConfiguration(SettingsConfig.class) - .run((context) -> assertThat( - getSettings(context).getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)) - .isEqualTo(300)); + .run((context) -> assertThat( + getSettings(context).getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)) + .isEqualTo(300)); } @Test void settingsSslConfig() { this.contextRunner.withUserConfiguration(SslSettingsConfig.class) - .run((context) -> assertThat(getSettings(context).getSslSettings().isEnabled()).isTrue()); + .run((context) -> assertThat(getSettings(context).getSslSettings().isEnabled()).isTrue()); } @Test void configuresSingleClient() { this.contextRunner.withUserConfiguration(FallbackMongoClientConfig.class) - .run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); + .run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); } @Test void customizerOverridesAutoConfig() { this.contextRunner.withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test?appname=auto-config") - .withUserConfiguration(SimpleCustomizerConfig.class) - .run((context) -> assertThat(getSettings(context).getApplicationName()).isEqualTo("overridden-name")); + .withUserConfiguration(SimpleCustomizerConfig.class) + .run((context) -> assertThat(getSettings(context).getApplicationName()).isEqualTo("overridden-name")); } private MongoClientSettings getSettings(AssertableApplicationContext context) { @@ -95,8 +95,9 @@ class MongoAutoConfigurationTests { @Bean MongoClientSettings mongoClientSettings() { - return MongoClientSettings.builder().applyToSocketSettings( - (socketSettings) -> socketSettings.connectTimeout(300, TimeUnit.MILLISECONDS)).build(); + return MongoClientSettings.builder() + .applyToSocketSettings((socketSettings) -> socketSettings.connectTimeout(300, TimeUnit.MILLISECONDS)) + .build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactorySupportTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactorySupportTests.java index 1829ec803c..984360a68e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactorySupportTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactorySupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,20 +76,20 @@ abstract class MongoClientFactorySupportTests { T client = createMongoClient(settings); MongoClientSettings wrapped = getClientSettings(client); assertThat(wrapped.getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)) - .isEqualTo(settings.getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)); + .isEqualTo(settings.getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)); assertThat(wrapped.getSocketSettings().getReadTimeout(TimeUnit.MILLISECONDS)) - .isEqualTo(settings.getSocketSettings().getReadTimeout(TimeUnit.MILLISECONDS)); + .isEqualTo(settings.getSocketSettings().getReadTimeout(TimeUnit.MILLISECONDS)); assertThat(wrapped.getServerSettings().getHeartbeatFrequency(TimeUnit.MILLISECONDS)) - .isEqualTo(settings.getServerSettings().getHeartbeatFrequency(TimeUnit.MILLISECONDS)); + .isEqualTo(settings.getServerSettings().getHeartbeatFrequency(TimeUnit.MILLISECONDS)); assertThat(wrapped.getServerSettings().getMinHeartbeatFrequency(TimeUnit.MILLISECONDS)) - .isEqualTo(settings.getServerSettings().getMinHeartbeatFrequency(TimeUnit.MILLISECONDS)); + .isEqualTo(settings.getServerSettings().getMinHeartbeatFrequency(TimeUnit.MILLISECONDS)); assertThat(wrapped.getApplicationName()).isEqualTo(settings.getApplicationName()); assertThat(wrapped.getConnectionPoolSettings().getMaxWaitTime(TimeUnit.MILLISECONDS)) - .isEqualTo(settings.getConnectionPoolSettings().getMaxWaitTime(TimeUnit.MILLISECONDS)); + .isEqualTo(settings.getConnectionPoolSettings().getMaxWaitTime(TimeUnit.MILLISECONDS)); assertThat(wrapped.getConnectionPoolSettings().getMaxConnectionLifeTime(TimeUnit.MILLISECONDS)) - .isEqualTo(settings.getConnectionPoolSettings().getMaxConnectionLifeTime(TimeUnit.MILLISECONDS)); + .isEqualTo(settings.getConnectionPoolSettings().getMaxConnectionLifeTime(TimeUnit.MILLISECONDS)); assertThat(wrapped.getConnectionPoolSettings().getMaxConnectionIdleTime(TimeUnit.MILLISECONDS)) - .isEqualTo(settings.getConnectionPoolSettings().getMaxConnectionIdleTime(TimeUnit.MILLISECONDS)); + .isEqualTo(settings.getConnectionPoolSettings().getMaxConnectionIdleTime(TimeUnit.MILLISECONDS)); assertThat(wrapped.getSslSettings().isEnabled()).isEqualTo(settings.getSslSettings().isEnabled()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfigurationTests.java index 30ed753e99..268c8963a1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,7 @@ import static org.mockito.Mockito.mock; class MongoReactiveAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoReactiveAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoReactiveAutoConfiguration.class)); @Test void clientExists() { @@ -61,28 +61,28 @@ class MongoReactiveAutoConfigurationTests { @Test void settingsAdded() { this.contextRunner.withPropertyValues("spring.data.mongodb.host:localhost") - .withUserConfiguration(SettingsConfig.class) - .run((context) -> assertThat(getSettings(context).getSocketSettings().getReadTimeout(TimeUnit.SECONDS)) - .isEqualTo(300)); + .withUserConfiguration(SettingsConfig.class) + .run((context) -> assertThat(getSettings(context).getSocketSettings().getReadTimeout(TimeUnit.SECONDS)) + .isEqualTo(300)); } @Test void settingsAddedButNoHost() { this.contextRunner.withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test") - .withUserConfiguration(SettingsConfig.class) - .run((context) -> assertThat(getSettings(context).getReadPreference()) - .isEqualTo(ReadPreference.nearest())); + .withUserConfiguration(SettingsConfig.class) + .run((context) -> assertThat(getSettings(context).getReadPreference()).isEqualTo(ReadPreference.nearest())); } @Test void settingsSslConfig() { this.contextRunner.withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test") - .withUserConfiguration(SslSettingsConfig.class).run((context) -> { - assertThat(context).hasSingleBean(MongoClient.class); - MongoClientSettings settings = getSettings(context); - assertThat(settings.getApplicationName()).isEqualTo("test-config"); - assertThat(settings.getStreamFactoryFactory()).isSameAs(context.getBean("myStreamFactoryFactory")); - }); + .withUserConfiguration(SslSettingsConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(MongoClient.class); + MongoClientSettings settings = getSettings(context); + assertThat(settings.getApplicationName()).isEqualTo("test-config"); + assertThat(settings.getStreamFactoryFactory()).isSameAs(context.getBean("myStreamFactoryFactory")); + }); } @Test @@ -102,13 +102,13 @@ class MongoReactiveAutoConfigurationTests { @Test void customizerOverridesAutoConfig() { this.contextRunner.withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test?appname=auto-config") - .withUserConfiguration(SimpleCustomizerConfig.class).run((context) -> { - assertThat(context).hasSingleBean(MongoClient.class); - MongoClientSettings settings = getSettings(context); - assertThat(settings.getApplicationName()).isEqualTo("overridden-name"); - assertThat(settings.getStreamFactoryFactory()) - .isEqualTo(SimpleCustomizerConfig.streamFactoryFactory); - }); + .withUserConfiguration(SimpleCustomizerConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(MongoClient.class); + MongoClientSettings settings = getSettings(context); + assertThat(settings.getApplicationName()).isEqualTo("overridden-name"); + assertThat(settings.getStreamFactoryFactory()).isEqualTo(SimpleCustomizerConfig.streamFactoryFactory); + }); } private MongoClientSettings getSettings(ApplicationContext context) { @@ -121,8 +121,10 @@ class MongoReactiveAutoConfigurationTests { @Bean MongoClientSettings mongoClientSettings() { - return MongoClientSettings.builder().readPreference(ReadPreference.nearest()) - .applyToSocketSettings((socket) -> socket.readTimeout(300, TimeUnit.SECONDS)).build(); + return MongoClientSettings.builder() + .readPreference(ReadPreference.nearest()) + .applyToSocketSettings((socket) -> socket.readTimeout(300, TimeUnit.SECONDS)) + .build(); } } @@ -132,8 +134,10 @@ class MongoReactiveAutoConfigurationTests { @Bean MongoClientSettings mongoClientSettings(StreamFactoryFactory streamFactoryFactory) { - return MongoClientSettings.builder().applicationName("test-config") - .streamFactoryFactory(streamFactoryFactory).build(); + return MongoClientSettings.builder() + .applicationName("test-config") + .streamFactoryFactory(streamFactoryFactory) + .build(); } @Bean @@ -149,12 +153,12 @@ class MongoReactiveAutoConfigurationTests { static class SimpleCustomizerConfig { private static final StreamFactoryFactory streamFactoryFactory = new AsynchronousSocketChannelStreamFactoryFactory.Builder() - .build(); + .build(); @Bean MongoClientSettingsBuilderCustomizer customizer() { return (clientSettingsBuilder) -> clientSettingsBuilder.applicationName("overridden-name") - .streamFactoryFactory(streamFactoryFactory); + .streamFactoryFactory(streamFactoryFactory); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java index 5b36d1ebc1..7e9de20982 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -83,8 +83,8 @@ class EmbeddedMongoAutoConfigurationTests { this.context.register(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, EmbeddedMongoAutoConfiguration.class); assertThatThrownBy(() -> this.context.refresh()).hasRootCauseExactlyInstanceOf(IllegalStateException.class) - .hasRootCauseMessage("Set the spring.mongodb.embedded.version property or define your own MongodConfig " - + "bean to use embedded MongoDB"); + .hasRootCauseMessage("Set the spring.mongodb.embedded.version property or define your own MongodConfig " + + "bean to use embedded MongoDB"); } @Test @@ -178,7 +178,7 @@ class EmbeddedMongoAutoConfigurationTests { loadWithValidVersion(DownloadConfigBuilderCustomizerConfiguration.class); RuntimeConfig runtimeConfig = this.context.getBean(RuntimeConfig.class); DownloadConfig downloadConfig = (DownloadConfig) new DirectFieldAccessor(runtimeConfig.artifactStore()) - .getPropertyValue("downloadConfig"); + .getPropertyValue("downloadConfig"); assertThat(downloadConfig.getUserAgent()).isEqualTo("Test User Agent"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationReactiveIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationReactiveIntegrationTests.java index 61b4091692..9f9524eaa7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationReactiveIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,15 +56,27 @@ class MustacheAutoConfigurationReactiveIntegrationTests { @Test void testHomePage() { - String result = this.client.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class) - .returnResult().getResponseBody(); + String result = this.client.get() + .uri("/") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .returnResult() + .getResponseBody(); assertThat(result).contains("Hello App").contains("Hello World"); } @Test void testPartialPage() { - String result = this.client.get().uri("/partial").exchange().expectStatus().isOk().expectBody(String.class) - .returnResult().getResponseBody(); + String result = this.client.get() + .uri("/partial") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .returnResult() + .getResponseBody(); assertThat(result).contains("Hello App").contains("Hello World"); } @@ -93,7 +105,7 @@ class MustacheAutoConfigurationReactiveIntegrationTests { @Bean MustacheViewResolver viewResolver() { Mustache.Compiler compiler = Mustache.compiler() - .withLoader(new MustacheResourceTemplateLoader("classpath:/mustache-templates/", ".html")); + .withLoader(new MustacheResourceTemplateLoader("classpath:/mustache-templates/", ".html")); MustacheViewResolver resolver = new MustacheViewResolver(compiler); resolver.setPrefix("classpath:/mustache-templates/"); resolver.setSuffix(".html"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationServletIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationServletIntegrationTests.java index 4fc072b7e9..1e70a9af37 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationServletIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationServletIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -115,7 +115,7 @@ class MustacheAutoConfigurationServletIntegrationTests { @Bean MustacheViewResolver viewResolver() { Mustache.Compiler compiler = Mustache.compiler() - .withLoader(new MustacheResourceTemplateLoader("classpath:/mustache-templates/", ".html")); + .withLoader(new MustacheResourceTemplateLoader("classpath:/mustache-templates/", ".html")); MustacheViewResolver resolver = new MustacheViewResolver(compiler); resolver.setPrefix("classpath:/mustache-templates/"); resolver.setSuffix(".html"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationTests.java index 185c20b35b..0d72602760 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,22 +56,22 @@ class MustacheAutoConfigurationTests { @Test void servletViewResolverCanBeDisabled() { configure(new WebApplicationContextRunner()).withPropertyValues("spring.mustache.enabled=false") - .run((context) -> { - assertThat(context).hasSingleBean(Mustache.Compiler.class); - assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); - assertThat(context).doesNotHaveBean(MustacheViewResolver.class); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Mustache.Compiler.class); + assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); + assertThat(context).doesNotHaveBean(MustacheViewResolver.class); + }); } @Test void registerCompilerForServletApp() { configure(new WebApplicationContextRunner()).withUserConfiguration(CustomCompilerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(Mustache.Compiler.class); - assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); - assertThat(context).hasSingleBean(MustacheViewResolver.class); - assertThat(context.getBean(Mustache.Compiler.class).standardsMode).isTrue(); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Mustache.Compiler.class); + assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); + assertThat(context).hasSingleBean(MustacheViewResolver.class); + assertThat(context.getBean(Mustache.Compiler.class).standardsMode).isTrue(); + }); } @Test @@ -81,32 +81,32 @@ class MustacheAutoConfigurationTests { assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); assertThat(context).doesNotHaveBean(MustacheViewResolver.class); assertThat(context) - .hasSingleBean(org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class); + .hasSingleBean(org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class); }); } @Test void reactiveViewResolverCanBeDisabled() { configure(new ReactiveWebApplicationContextRunner()).withPropertyValues("spring.mustache.enabled=false") - .run((context) -> { - assertThat(context).hasSingleBean(Mustache.Compiler.class); - assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); - assertThat(context).doesNotHaveBean( - org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Mustache.Compiler.class); + assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); + assertThat(context) + .doesNotHaveBean(org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class); + }); } @Test void registerCompilerForReactiveApp() { configure(new ReactiveWebApplicationContextRunner()).withUserConfiguration(CustomCompilerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(Mustache.Compiler.class); - assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); - assertThat(context).doesNotHaveBean(MustacheViewResolver.class); - assertThat(context).hasSingleBean( - org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class); - assertThat(context.getBean(Mustache.Compiler.class).standardsMode).isTrue(); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Mustache.Compiler.class); + assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); + assertThat(context).doesNotHaveBean(MustacheViewResolver.class); + assertThat(context) + .hasSingleBean(org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class); + assertThat(context.getBean(Mustache.Compiler.class).standardsMode).isTrue(); + }); } @Test @@ -130,13 +130,13 @@ class MustacheAutoConfigurationTests { void defaultReactiveViewResolverConfiguration() { configure(new ReactiveWebApplicationContextRunner()).run((context) -> { org.springframework.boot.web.reactive.result.view.MustacheViewResolver viewResolver = context - .getBean(org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class); + .getBean(org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class); assertThat(viewResolver).extracting("charset").isEqualTo("UTF-8"); assertThat(viewResolver).extracting("prefix").isEqualTo("classpath:/templates/"); assertThat(viewResolver).extracting("requestContextAttribute").isNull(); assertThat(viewResolver).extracting("suffix").isEqualTo(".mustache"); assertThat(viewResolver.getSupportedMediaTypes()) - .containsExactly(MediaType.parseMediaType("text/html;charset=UTF-8")); + .containsExactly(MediaType.parseMediaType("text/html;charset=UTF-8")); }); } @@ -252,9 +252,11 @@ class MustacheAutoConfigurationTests { private void assertViewResolverProperty(ViewResolverKind kind, String property, String field, Object expectedValue) { - kind.runner().withConfiguration(AutoConfigurations.of(MustacheAutoConfiguration.class)) - .withPropertyValues(property).run((context) -> assertThat(context.getBean(kind.viewResolverClass())) - .extracting(field).isEqualTo(expectedValue)); + kind.runner() + .withConfiguration(AutoConfigurations.of(MustacheAutoConfiguration.class)) + .withPropertyValues(property) + .run((context) -> assertThat(context.getBean(kind.viewResolverClass())).extracting(field) + .isEqualTo(expectedValue)); } private > T configure(T runner) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationWithoutWebMvcTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationWithoutWebMvcTests.java index be2a47669e..09199b6a29 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationWithoutWebMvcTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationWithoutWebMvcTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,10 +36,10 @@ class MustacheAutoConfigurationWithoutWebMvcTests { @Test void registerBeansForServletAppWithoutMvc() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(MustacheAutoConfiguration.class)) - .run((context) -> { - assertThat(context).hasSingleBean(Mustache.Compiler.class); - assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Mustache.Compiler.class); + assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java index c4daba94a2..af49dbcbe9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ class MustacheStandaloneIntegrationTests { @Test void directCompilation() { assertThat(this.compiler.compile("Hello: {{world}}").execute(Collections.singletonMap("world", "World"))) - .isEqualTo("Hello: World"); + .isEqualTo("Hello: World"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfigurationIntegrationTests.java index 074db2bce1..c8febbbe60 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,8 @@ class Neo4jAutoConfigurationIntegrationTests { @Container private static final Neo4jContainer neo4jServer = new Neo4jContainer<>(DockerImageNames.neo4j()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void neo4jProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfigurationTests.java index 53da528090..ee056aab27 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,13 +54,13 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; class Neo4jAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(Neo4jAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(Neo4jAutoConfiguration.class)); @Test void driverNotConfiguredWithoutDriverApi() { this.contextRunner.withPropertyValues("spring.neo4j.uri=bolt://localhost:4711") - .withClassLoader(new FilteredClassLoader(Driver.class)) - .run((ctx) -> assertThat(ctx).doesNotHaveBean(Driver.class)); + .withClassLoader(new FilteredClassLoader(Driver.class)) + .run((ctx) -> assertThat(ctx).doesNotHaveBean(Driver.class)); } @Test @@ -71,8 +71,8 @@ class Neo4jAutoConfigurationTests { @Test void driverShouldInvokeConfigBuilderCustomizers() { this.contextRunner.withPropertyValues("spring.neo4j.uri=bolt://localhost:4711") - .withBean(ConfigBuilderCustomizer.class, () -> ConfigBuilder::withEncryption) - .run((ctx) -> assertThat(ctx.getBean(Driver.class).isEncrypted()).isTrue()); + .withBean(ConfigBuilderCustomizer.class, () -> ConfigBuilder::withEncryption) + .run((ctx) -> assertThat(ctx.getBean(Driver.class).isEncrypted()).isTrue()); } @ParameterizedTest @@ -98,8 +98,9 @@ class Neo4jAutoConfigurationTests { @ValueSource(strings = { "bolt+routing", "bolt+x", "neo4j+wth" }) void uriWithInvalidSchemesAreDetected(String invalidScheme) { this.contextRunner.withPropertyValues("spring.neo4j.uri=" + invalidScheme + "://localhost:4711") - .run((ctx) -> assertThat(ctx).hasFailed().getFailure() - .hasMessageContaining("'%s' is not a supported scheme.", invalidScheme)); + .run((ctx) -> assertThat(ctx).hasFailed() + .getFailure() + .hasMessageContaining("'%s' is not a supported scheme.", invalidScheme)); } @Test @@ -114,13 +115,13 @@ class Neo4jAutoConfigurationTests { Neo4jProperties properties = new Neo4jProperties(); properties.setMaxTransactionRetryTime(Duration.ofSeconds(2)); assertThat(mapDriverConfig(properties)).extracting("retrySettings") - .hasFieldOrPropertyWithValue("maxRetryTimeMs", 2000L); + .hasFieldOrPropertyWithValue("maxRetryTimeMs", 2000L); } @Test void determineServerUriShouldDefaultToLocalhost() { assertThat(determineServerUri(new Neo4jProperties(), new MockEnvironment())) - .isEqualTo(URI.create("bolt://localhost:7687")); + .isEqualTo(URI.create("bolt://localhost:7687")); } @Test @@ -177,7 +178,7 @@ class Neo4jAutoConfigurationTests { @Deprecated void authenticationWithUsernameUsingDeprecatedPropertiesShouldEnableBasicAuth() { MockEnvironment environment = new MockEnvironment().withProperty("spring.data.neo4j.username", "user") - .withProperty("spring.data.neo4j.password", "secret"); + .withProperty("spring.data.neo4j.password", "secret"); assertThat(mapAuthToken(new Authentication(), environment)).isEqualTo(AuthTokens.basic("user", "secret")); } @@ -185,7 +186,7 @@ class Neo4jAutoConfigurationTests { @Deprecated void authenticationWithUsernameShouldTakePrecedenceOverDeprecatedPropertiesAndEnableBasicAuth() { MockEnvironment environment = new MockEnvironment().withProperty("spring.data.neo4j.username", "user") - .withProperty("spring.data.neo4j.password", "secret"); + .withProperty("spring.data.neo4j.password", "secret"); Authentication authentication = new Authentication(); authentication.setUsername("Farin"); authentication.setPassword("Urlaub"); @@ -205,7 +206,7 @@ class Neo4jAutoConfigurationTests { authentication.setUsername("Farin"); authentication.setKerberosTicket("AABBCCDDEE"); assertThatIllegalStateException().isThrownBy(() -> mapAuthToken(authentication)) - .withMessage("Cannot specify both username ('Farin') and kerberos ticket ('AABBCCDDEE')"); + .withMessage("Cannot specify both username ('Farin') and kerberos ticket ('AABBCCDDEE')"); } @Test @@ -262,7 +263,7 @@ class Neo4jAutoConfigurationTests { Neo4jProperties properties = new Neo4jProperties(); properties.getSecurity().setTrustStrategy(TrustStrategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES); assertThat(mapDriverConfig(properties).trustStrategy().strategy()) - .isEqualTo(Config.TrustStrategy.Strategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES); + .isEqualTo(Config.TrustStrategy.Strategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES); } @Test @@ -270,7 +271,7 @@ class Neo4jAutoConfigurationTests { Neo4jProperties properties = new Neo4jProperties(); properties.getSecurity().setTrustStrategy(TrustStrategy.TRUST_ALL_CERTIFICATES); assertThat(mapDriverConfig(properties).trustStrategy().strategy()) - .isEqualTo(Config.TrustStrategy.Strategy.TRUST_ALL_CERTIFICATES); + .isEqualTo(Config.TrustStrategy.Strategy.TRUST_ALL_CERTIFICATES); } @Test @@ -291,7 +292,7 @@ class Neo4jAutoConfigurationTests { properties.getSecurity().setCertFile(certFile); Config.TrustStrategy trustStrategy = mapDriverConfig(properties).trustStrategy(); assertThat(trustStrategy.strategy()) - .isEqualTo(Config.TrustStrategy.Strategy.TRUST_CUSTOM_CA_SIGNED_CERTIFICATES); + .isEqualTo(Config.TrustStrategy.Strategy.TRUST_CUSTOM_CA_SIGNED_CERTIFICATES); assertThat(trustStrategy.certFiles()).containsOnly(certFile); } @@ -300,8 +301,9 @@ class Neo4jAutoConfigurationTests { Neo4jProperties properties = new Neo4jProperties(); properties.getSecurity().setTrustStrategy(TrustStrategy.TRUST_CUSTOM_CA_SIGNED_CERTIFICATES); assertThatExceptionOfType(InvalidConfigurationPropertyValueException.class) - .isThrownBy(() -> mapDriverConfig(properties)).withMessage( - "Property spring.neo4j.security.trust-strategy with value 'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES' is invalid: Configured trust strategy requires a certificate file."); + .isThrownBy(() -> mapDriverConfig(properties)) + .withMessage( + "Property spring.neo4j.security.trust-strategy with value 'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES' is invalid: Configured trust strategy requires a certificate file."); } @Test @@ -309,13 +311,13 @@ class Neo4jAutoConfigurationTests { Neo4jProperties properties = new Neo4jProperties(); properties.getSecurity().setTrustStrategy(TrustStrategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES); assertThat(mapDriverConfig(properties).trustStrategy().strategy()) - .isEqualTo(Config.TrustStrategy.Strategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES); + .isEqualTo(Config.TrustStrategy.Strategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES); } @Test void driverConfigShouldBeConfiguredToUseUseSpringJclLogging() { assertThat(mapDriverConfig(new Neo4jProperties()).logging()).isNotNull() - .isInstanceOf(Neo4jSpringJclLogging.class); + .isInstanceOf(Neo4jSpringJclLogging.class); } private URI determineServerUri(Neo4jProperties properties, Environment environment) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jPropertiesTests.java index 07bdc12275..432f3637ca 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,9 +52,9 @@ class Neo4jPropertiesTests { Neo4jProperties properties = new Neo4jProperties(); assertThat(properties.getSecurity().isEncrypted()).isEqualTo(defaultConfig.encrypted()); assertThat(properties.getSecurity().getTrustStrategy().name()) - .isEqualTo(defaultConfig.trustStrategy().strategy().name()); + .isEqualTo(defaultConfig.trustStrategy().strategy().name()); assertThat(properties.getSecurity().isHostnameVerificationEnabled()) - .isEqualTo(defaultConfig.trustStrategy().isHostnameVerificationEnabled()); + .isEqualTo(defaultConfig.trustStrategy().isHostnameVerificationEnabled()); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/netty/NettyAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/netty/NettyAutoConfigurationTests.java index 821fd4cba9..92136193e7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/netty/NettyAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/netty/NettyAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat; class NettyAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(NettyAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(NettyAutoConfiguration.class)); @Test void leakDetectionShouldBeConfigured() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java index 64408fb98e..cc7a500eac 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,12 +73,11 @@ abstract class AbstractJpaAutoConfigurationTests { protected AbstractJpaAutoConfigurationTests(Class autoConfiguredClass) { this.autoConfiguredClass = autoConfiguredClass; this.contextRunner = new ApplicationContextRunner() - .withPropertyValues("spring.datasource.generate-unique-name=true", - "spring.jta.log-dir=" - + new File(new BuildOutput(getClass()).getRootLocation(), "transaction-logs")) - .withUserConfiguration(TestConfiguration.class).withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class, TransactionAutoConfiguration.class, - SqlInitializationAutoConfiguration.class, autoConfiguredClass)); + .withPropertyValues("spring.datasource.generate-unique-name=true", + "spring.jta.log-dir=" + new File(new BuildOutput(getClass()).getRootLocation(), "transaction-logs")) + .withUserConfiguration(TestConfiguration.class) + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + TransactionAutoConfiguration.class, SqlInitializationAutoConfiguration.class, autoConfiguredClass)); } protected ApplicationContextRunner contextRunner() { @@ -88,13 +87,14 @@ abstract class AbstractJpaAutoConfigurationTests { @Test void notConfiguredIfDataSourceIsNotAvailable() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(this.autoConfiguredClass)) - .run(assertJpaIsNotAutoConfigured()); + .run(assertJpaIsNotAutoConfigured()); } @Test void notConfiguredIfNoSingleDataSourceCandidateIsAvailable() { new ApplicationContextRunner().withUserConfiguration(TestTwoDataSourcesConfiguration.class) - .withConfiguration(AutoConfigurations.of(this.autoConfiguredClass)).run(assertJpaIsNotAutoConfigured()); + .withConfiguration(AutoConfigurations.of(this.autoConfiguredClass)) + .run(assertJpaIsNotAutoConfigured()); } protected ContextConsumer assertJpaIsNotAutoConfigured() { @@ -127,93 +127,94 @@ abstract class AbstractJpaAutoConfigurationTests { @Test void jpaTransactionManagerTakesPrecedenceOverSimpleDataSourceOne() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class)) - .run((context) -> { - assertThat(context).hasSingleBean(DataSource.class); - assertThat(context).hasSingleBean(JpaTransactionManager.class); - assertThat(context).getBean("transactionManager").isInstanceOf(JpaTransactionManager.class); - }); + .run((context) -> { + assertThat(context).hasSingleBean(DataSource.class); + assertThat(context).hasSingleBean(JpaTransactionManager.class); + assertThat(context).getBean("transactionManager").isInstanceOf(JpaTransactionManager.class); + }); } @Test void openEntityManagerInViewInterceptorIsCreated() { new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true") - .withUserConfiguration(TestConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - TransactionAutoConfiguration.class, this.autoConfiguredClass)) - .run((context) -> assertThat(context).hasSingleBean(OpenEntityManagerInViewInterceptor.class)); + .withUserConfiguration(TestConfiguration.class) + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + TransactionAutoConfiguration.class, this.autoConfiguredClass)) + .run((context) -> assertThat(context).hasSingleBean(OpenEntityManagerInViewInterceptor.class)); } @Test void openEntityManagerInViewInterceptorIsNotRegisteredWhenFilterPresent() { new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true") - .withUserConfiguration(TestFilterConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - TransactionAutoConfiguration.class, this.autoConfiguredClass)) - .run((context) -> assertThat(context).doesNotHaveBean(OpenEntityManagerInViewInterceptor.class)); + .withUserConfiguration(TestFilterConfiguration.class) + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + TransactionAutoConfiguration.class, this.autoConfiguredClass)) + .run((context) -> assertThat(context).doesNotHaveBean(OpenEntityManagerInViewInterceptor.class)); } @Test void openEntityManagerInViewInterceptorIsNotRegisteredWhenFilterRegistrationPresent() { new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true") - .withUserConfiguration(TestFilterRegistrationConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - TransactionAutoConfiguration.class, this.autoConfiguredClass)) - .run((context) -> assertThat(context).doesNotHaveBean(OpenEntityManagerInViewInterceptor.class)); + .withUserConfiguration(TestFilterRegistrationConfiguration.class) + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + TransactionAutoConfiguration.class, this.autoConfiguredClass)) + .run((context) -> assertThat(context).doesNotHaveBean(OpenEntityManagerInViewInterceptor.class)); } @Test void openEntityManagerInViewInterceptorAutoConfigurationBacksOffWhenManuallyRegistered() { new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true") - .withUserConfiguration(TestInterceptorManualConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - TransactionAutoConfiguration.class, this.autoConfiguredClass)) - .run((context) -> assertThat(context).getBean(OpenEntityManagerInViewInterceptor.class) - .isExactlyInstanceOf( - TestInterceptorManualConfiguration.ManualOpenEntityManagerInViewInterceptor.class)); + .withUserConfiguration(TestInterceptorManualConfiguration.class) + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + TransactionAutoConfiguration.class, this.autoConfiguredClass)) + .run((context) -> assertThat(context).getBean(OpenEntityManagerInViewInterceptor.class) + .isExactlyInstanceOf( + TestInterceptorManualConfiguration.ManualOpenEntityManagerInViewInterceptor.class)); } @Test void openEntityManagerInViewInterceptorIsNotRegisteredWhenExplicitlyOff() { new WebApplicationContextRunner() - .withPropertyValues("spring.datasource.generate-unique-name=true", "spring.jpa.open-in-view=false") - .withUserConfiguration(TestConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - TransactionAutoConfiguration.class, this.autoConfiguredClass)) - .run((context) -> assertThat(context).doesNotHaveBean(OpenEntityManagerInViewInterceptor.class)); + .withPropertyValues("spring.datasource.generate-unique-name=true", "spring.jpa.open-in-view=false") + .withUserConfiguration(TestConfiguration.class) + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + TransactionAutoConfiguration.class, this.autoConfiguredClass)) + .run((context) -> assertThat(context).doesNotHaveBean(OpenEntityManagerInViewInterceptor.class)); } @Test void customJpaProperties() { - this.contextRunner.withPropertyValues("spring.jpa.properties.a:b", "spring.jpa.properties.a.b:c", - "spring.jpa.properties.c:d").run((context) -> { - LocalContainerEntityManagerFactoryBean bean = context - .getBean(LocalContainerEntityManagerFactoryBean.class); - Map map = bean.getJpaPropertyMap(); - assertThat(map.get("a")).isEqualTo("b"); - assertThat(map.get("c")).isEqualTo("d"); - assertThat(map.get("a.b")).isEqualTo("c"); - }); + this.contextRunner + .withPropertyValues("spring.jpa.properties.a:b", "spring.jpa.properties.a.b:c", "spring.jpa.properties.c:d") + .run((context) -> { + LocalContainerEntityManagerFactoryBean bean = context + .getBean(LocalContainerEntityManagerFactoryBean.class); + Map map = bean.getJpaPropertyMap(); + assertThat(map.get("a")).isEqualTo("b"); + assertThat(map.get("c")).isEqualTo("d"); + assertThat(map.get("a.b")).isEqualTo("c"); + }); } @Test void usesManuallyDefinedLocalContainerEntityManagerFactoryBeanIfAvailable() { this.contextRunner.withUserConfiguration(TestConfigurationWithLocalContainerEntityManagerFactoryBean.class) - .run((context) -> { - LocalContainerEntityManagerFactoryBean factoryBean = context - .getBean(LocalContainerEntityManagerFactoryBean.class); - Map map = factoryBean.getJpaPropertyMap(); - assertThat(map.get("configured")).isEqualTo("manually"); - }); + .run((context) -> { + LocalContainerEntityManagerFactoryBean factoryBean = context + .getBean(LocalContainerEntityManagerFactoryBean.class); + Map map = factoryBean.getJpaPropertyMap(); + assertThat(map.get("configured")).isEqualTo("manually"); + }); } @Test void usesManuallyDefinedEntityManagerFactoryIfAvailable() { this.contextRunner.withUserConfiguration(TestConfigurationWithLocalContainerEntityManagerFactoryBean.class) - .run((context) -> { - EntityManagerFactory factoryBean = context.getBean(EntityManagerFactory.class); - Map map = factoryBean.getProperties(); - assertThat(map.get("configured")).isEqualTo("manually"); - }); + .run((context) -> { + EntityManagerFactory factoryBean = context.getBean(EntityManagerFactory.class); + Map map = factoryBean.getProperties(); + assertThat(map.get("configured")).isEqualTo("manually"); + }); } @Test @@ -228,25 +229,25 @@ abstract class AbstractJpaAutoConfigurationTests { @Test void customPersistenceUnitManager() { this.contextRunner.withUserConfiguration(TestConfigurationWithCustomPersistenceUnitManager.class) - .run((context) -> { - LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = context - .getBean(LocalContainerEntityManagerFactoryBean.class); - assertThat(entityManagerFactoryBean).hasFieldOrPropertyWithValue("persistenceUnitManager", - context.getBean(PersistenceUnitManager.class)); - }); + .run((context) -> { + LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = context + .getBean(LocalContainerEntityManagerFactoryBean.class); + assertThat(entityManagerFactoryBean).hasFieldOrPropertyWithValue("persistenceUnitManager", + context.getBean(PersistenceUnitManager.class)); + }); } @Test void customPersistenceUnitPostProcessors() { this.contextRunner.withUserConfiguration(TestConfigurationWithCustomPersistenceUnitPostProcessors.class) - .run((context) -> { - LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = context - .getBean(LocalContainerEntityManagerFactoryBean.class); - PersistenceUnitInfo persistenceUnitInfo = entityManagerFactoryBean.getPersistenceUnitInfo(); - assertThat(persistenceUnitInfo).isNotNull(); - assertThat(persistenceUnitInfo.getManagedClassNames()) - .contains("customized.attribute.converter.class.name"); - }); + .run((context) -> { + LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = context + .getBean(LocalContainerEntityManagerFactoryBean.class); + PersistenceUnitInfo persistenceUnitInfo = entityManagerFactoryBean.getPersistenceUnitInfo(); + assertThat(persistenceUnitInfo).isNotNull(); + assertThat(persistenceUnitInfo.getManagedClassNames()) + .contains("customized.attribute.converter.class.name"); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java index e47926a267..ae7c3d3d26 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,33 +56,37 @@ import static org.mockito.Mockito.mock; class CustomHibernateJpaAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withPropertyValues("spring.datasource.generate-unique-name=true") - .withUserConfiguration(TestConfiguration.class).withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class)); + .withPropertyValues("spring.datasource.generate-unique-name=true") + .withUserConfiguration(TestConfiguration.class) + .withConfiguration( + AutoConfigurations.of(DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class)); @Test void namingStrategyDelegatorTakesPrecedence() { - this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.ejb.naming_strategy_delegator:" - + "org.hibernate.cfg.naming.ImprovedNamingStrategyDelegator").run((context) -> { - JpaProperties jpaProperties = context.getBean(JpaProperties.class); - HibernateProperties hibernateProperties = context.getBean(HibernateProperties.class); - Map properties = hibernateProperties - .determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings()); - assertThat(properties.get("hibernate.ejb.naming_strategy")).isNull(); - }); + this.contextRunner + .withPropertyValues("spring.jpa.properties.hibernate.ejb.naming_strategy_delegator:" + + "org.hibernate.cfg.naming.ImprovedNamingStrategyDelegator") + .run((context) -> { + JpaProperties jpaProperties = context.getBean(JpaProperties.class); + HibernateProperties hibernateProperties = context.getBean(HibernateProperties.class); + Map properties = hibernateProperties + .determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings()); + assertThat(properties.get("hibernate.ejb.naming_strategy")).isNull(); + }); } @Test void namingStrategyBeansAreUsed() { this.contextRunner.withUserConfiguration(NamingStrategyConfiguration.class) - .withPropertyValues("spring.datasource.url:jdbc:h2:mem:naming-strategy-beans").run((context) -> { - HibernateJpaConfiguration jpaConfiguration = context.getBean(HibernateJpaConfiguration.class); - Map hibernateProperties = jpaConfiguration.getVendorProperties(); - assertThat(hibernateProperties.get("hibernate.implicit_naming_strategy")) - .isEqualTo(NamingStrategyConfiguration.implicitNamingStrategy); - assertThat(hibernateProperties.get("hibernate.physical_naming_strategy")) - .isEqualTo(NamingStrategyConfiguration.physicalNamingStrategy); - }); + .withPropertyValues("spring.datasource.url:jdbc:h2:mem:naming-strategy-beans") + .run((context) -> { + HibernateJpaConfiguration jpaConfiguration = context.getBean(HibernateJpaConfiguration.class); + Map hibernateProperties = jpaConfiguration.getVendorProperties(); + assertThat(hibernateProperties.get("hibernate.implicit_naming_strategy")) + .isEqualTo(NamingStrategyConfiguration.implicitNamingStrategy); + assertThat(hibernateProperties.get("hibernate.physical_naming_strategy")) + .isEqualTo(NamingStrategyConfiguration.physicalNamingStrategy); + }); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheIntegrationTests.java index 049ae5abe9..30cdd19b3d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,21 +36,21 @@ import static org.assertj.core.api.Assertions.assertThat; class Hibernate2ndLevelCacheIntegrationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class, DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class)) - .withUserConfiguration(TestConfiguration.class); + .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class, DataSourceAutoConfiguration.class, + HibernateJpaAutoConfiguration.class)) + .withUserConfiguration(TestConfiguration.class); @Test void hibernate2ndLevelCacheWithJCacheAndEhCache3() { String cachingProviderFqn = EhcacheCachingProvider.class.getName(); String configLocation = "ehcache3.xml"; this.contextRunner - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.jcache.config=" + configLocation, - "spring.jpa.properties.hibernate.cache.region.factory_class=jcache", - "spring.jpa.properties.hibernate.cache.provider=" + cachingProviderFqn, - "spring.jpa.properties.hibernate.javax.cache.uri=" + configLocation) - .run((context) -> assertThat(context).hasNotFailed()); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.jcache.config=" + configLocation, + "spring.jpa.properties.hibernate.cache.region.factory_class=jcache", + "spring.jpa.properties.hibernate.cache.provider=" + cachingProviderFqn, + "spring.jpa.properties.hibernate.javax.cache.uri=" + configLocation) + .run((context) -> assertThat(context).hasNotFailed()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java index a4b215b5f3..a75bc861c2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -101,10 +101,11 @@ class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTes void testDmlScriptWithMissingDdl() { contextRunner().withPropertyValues("spring.sql.init.data-locations:classpath:/city.sql", // Missing: - "spring.sql.init.schema-locations:classpath:/ddl.sql").run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()).hasMessageContaining("ddl.sql"); - }); + "spring.sql.init.schema-locations:classpath:/ddl.sql") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()).hasMessageContaining("ddl.sql"); + }); } @Test @@ -120,35 +121,35 @@ class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTes @Test void testDmlScriptRunsEarly() { contextRunner().withUserConfiguration(TestInitializedJpaConfiguration.class) - .withClassLoader(new HideDataScriptClassLoader()) - .withPropertyValues("spring.jpa.show-sql=true", "spring.jpa.hibernate.ddl-auto:create-drop", - "spring.sql.init.data-locations:/city.sql", "spring.jpa.defer-datasource-initialization=true") - .run((context) -> assertThat(context.getBean(TestInitializedJpaConfiguration.class).called).isTrue()); + .withClassLoader(new HideDataScriptClassLoader()) + .withPropertyValues("spring.jpa.show-sql=true", "spring.jpa.hibernate.ddl-auto:create-drop", + "spring.sql.init.data-locations:/city.sql", "spring.jpa.defer-datasource-initialization=true") + .run((context) -> assertThat(context.getBean(TestInitializedJpaConfiguration.class).called).isTrue()); } @Test void testFlywaySwitchOffDdlAuto() { contextRunner().withPropertyValues("spring.sql.init.mode:never", "spring.flyway.locations:classpath:db/city") - .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) - .run((context) -> assertThat(context).hasNotFailed()); + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) + .run((context) -> assertThat(context).hasNotFailed()); } @Test void testFlywayPlusValidation() { contextRunner() - .withPropertyValues("spring.sql.init.mode:never", "spring.flyway.locations:classpath:db/city", - "spring.jpa.hibernate.ddl-auto:validate") - .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) - .run((context) -> assertThat(context).hasNotFailed()); + .withPropertyValues("spring.sql.init.mode:never", "spring.flyway.locations:classpath:db/city", + "spring.jpa.hibernate.ddl-auto:validate") + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) + .run((context) -> assertThat(context).hasNotFailed()); } @Test void testLiquibasePlusValidation() { contextRunner() - .withPropertyValues("spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml", - "spring.jpa.hibernate.ddl-auto:validate") - .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)) - .run((context) -> assertThat(context).hasNotFailed()); + .withPropertyValues("spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml", + "spring.jpa.hibernate.ddl-auto:validate") + .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)) + .run((context) -> assertThat(context).hasNotFailed()); } @Test @@ -160,16 +161,16 @@ class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTes @Test void hibernateDialectIsSetWhenDatabaseIsSet() { contextRunner().withPropertyValues("spring.jpa.database=H2") - .run(assertJpaVendorAdapter((adapter) -> assertThat(adapter.getJpaPropertyMap()) - .contains(entry("hibernate.dialect", H2Dialect.class.getName())))); + .run(assertJpaVendorAdapter((adapter) -> assertThat(adapter.getJpaPropertyMap()) + .contains(entry("hibernate.dialect", H2Dialect.class.getName())))); } @Test void hibernateDialectIsSetWhenDatabasePlatformIsSet() { String databasePlatform = TestH2Dialect.class.getName(); contextRunner().withPropertyValues("spring.jpa.database-platform=" + databasePlatform) - .run(assertJpaVendorAdapter((adapter) -> assertThat(adapter.getJpaPropertyMap()) - .contains(entry("hibernate.dialect", databasePlatform)))); + .run(assertJpaVendorAdapter((adapter) -> assertThat(adapter.getJpaPropertyMap()) + .contains(entry("hibernate.dialect", databasePlatform)))); } private ContextConsumer assertJpaVendorAdapter( @@ -184,16 +185,16 @@ class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTes @Test void jtaDefaultPlatform() { contextRunner().withConfiguration(AutoConfigurations.of(JtaAutoConfiguration.class)) - .run(assertJtaPlatform(SpringJtaPlatform.class)); + .run(assertJtaPlatform(SpringJtaPlatform.class)); } @Test void jtaCustomPlatform() { contextRunner() - .withPropertyValues( - "spring.jpa.properties.hibernate.transaction.jta.platform:" + TestJtaPlatform.class.getName()) - .withConfiguration(AutoConfigurations.of(JtaAutoConfiguration.class)) - .run(assertJtaPlatform(TestJtaPlatform.class)); + .withPropertyValues( + "spring.jpa.properties.hibernate.transaction.jta.platform:" + TestJtaPlatform.class.getName()) + .withConfiguration(AutoConfigurations.of(JtaAutoConfiguration.class)) + .run(assertJtaPlatform(TestJtaPlatform.class)); } @Test @@ -204,100 +205,106 @@ class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTes private ContextConsumer assertJtaPlatform(Class expectedType) { return (context) -> { SessionFactoryImpl sessionFactory = context.getBean(LocalContainerEntityManagerFactoryBean.class) - .getNativeEntityManagerFactory().unwrap(SessionFactoryImpl.class); + .getNativeEntityManagerFactory() + .unwrap(SessionFactoryImpl.class); assertThat(sessionFactory.getServiceRegistry().getService(JtaPlatform.class)).isInstanceOf(expectedType); }; } @Test void jtaCustomTransactionManagerUsingProperties() { - contextRunner().withPropertyValues("spring.transaction.default-timeout:30", - "spring.transaction.rollback-on-commit-failure:true").run((context) -> { - JpaTransactionManager transactionManager = context.getBean(JpaTransactionManager.class); - assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); - assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); - }); + contextRunner() + .withPropertyValues("spring.transaction.default-timeout:30", + "spring.transaction.rollback-on-commit-failure:true") + .run((context) -> { + JpaTransactionManager transactionManager = context.getBean(JpaTransactionManager.class); + assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); + assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); + }); } @Test void autoConfigurationBacksOffWithSeveralDataSources() { contextRunner() - .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, - XADataSourceAutoConfiguration.class, JtaAutoConfiguration.class)) - .withUserConfiguration(TestTwoDataSourcesConfiguration.class).run((context) -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(EntityManagerFactory.class); - }); + .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, + XADataSourceAutoConfiguration.class, JtaAutoConfiguration.class)) + .withUserConfiguration(TestTwoDataSourcesConfiguration.class) + .run((context) -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(EntityManagerFactory.class); + }); } @Test void providerDisablesAutoCommitIsConfigured() { - contextRunner().withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), - "spring.datasource.hikari.auto-commit:false").run((context) -> { - Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) - .getJpaPropertyMap(); - assertThat(jpaProperties) - .contains(entry("hibernate.connection.provider_disables_autocommit", "true")); - }); + contextRunner() + .withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), + "spring.datasource.hikari.auto-commit:false") + .run((context) -> { + Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) + .getJpaPropertyMap(); + assertThat(jpaProperties).contains(entry("hibernate.connection.provider_disables_autocommit", "true")); + }); } @Test void providerDisablesAutoCommitIsNotConfiguredIfAutoCommitIsEnabled() { - contextRunner().withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), - "spring.datasource.hikari.auto-commit:true").run((context) -> { - Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) - .getJpaPropertyMap(); - assertThat(jpaProperties).doesNotContainKeys("hibernate.connection.provider_disables_autocommit"); - }); + contextRunner() + .withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), + "spring.datasource.hikari.auto-commit:true") + .run((context) -> { + Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) + .getJpaPropertyMap(); + assertThat(jpaProperties).doesNotContainKeys("hibernate.connection.provider_disables_autocommit"); + }); } @Test void providerDisablesAutoCommitIsNotConfiguredIfPropertyIsSet() { contextRunner() - .withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), - "spring.datasource.hikari.auto-commit:false", - "spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false") - .run((context) -> { - Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) - .getJpaPropertyMap(); - assertThat(jpaProperties) - .contains(entry("hibernate.connection.provider_disables_autocommit", "false")); - }); + .withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), + "spring.datasource.hikari.auto-commit:false", + "spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false") + .run((context) -> { + Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) + .getJpaPropertyMap(); + assertThat(jpaProperties).contains(entry("hibernate.connection.provider_disables_autocommit", "false")); + }); } @Test void providerDisablesAutoCommitIsNotConfiguredWithJta() { contextRunner().withConfiguration(AutoConfigurations.of(JtaAutoConfiguration.class)) - .withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), - "spring.datasource.hikari.auto-commit:false") - .run((context) -> { - Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) - .getJpaPropertyMap(); - assertThat(jpaProperties).doesNotContainKeys("hibernate.connection.provider_disables_autocommit"); - }); + .withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), + "spring.datasource.hikari.auto-commit:false") + .run((context) -> { + Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) + .getJpaPropertyMap(); + assertThat(jpaProperties).doesNotContainKeys("hibernate.connection.provider_disables_autocommit"); + }); } @Test void customResourceMapping() { contextRunner().withClassLoader(new HideDataScriptClassLoader()) - .withPropertyValues("spring.sql.init.data-locations:classpath:/db/non-annotated-data.sql", - "spring.jpa.mapping-resources=META-INF/mappings/non-annotated.xml", - "spring.jpa.defer-datasource-initialization=true") - .run((context) -> { - EntityManager em = context.getBean(EntityManagerFactory.class).createEntityManager(); - NonAnnotatedEntity found = em.find(NonAnnotatedEntity.class, 2000L); - assertThat(found).isNotNull(); - assertThat(found.getItem()).isEqualTo("Test"); - }); + .withPropertyValues("spring.sql.init.data-locations:classpath:/db/non-annotated-data.sql", + "spring.jpa.mapping-resources=META-INF/mappings/non-annotated.xml", + "spring.jpa.defer-datasource-initialization=true") + .run((context) -> { + EntityManager em = context.getBean(EntityManagerFactory.class).createEntityManager(); + NonAnnotatedEntity found = em.find(NonAnnotatedEntity.class, 2000L); + assertThat(found).isNotNull(); + assertThat(found.getItem()).isEqualTo("Test"); + }); } @Test void physicalNamingStrategyCanBeUsed() { contextRunner().withUserConfiguration(TestPhysicalNamingStrategyConfiguration.class).run((context) -> { Map hibernateProperties = context.getBean(HibernateJpaConfiguration.class) - .getVendorProperties(); - assertThat(hibernateProperties).contains( - entry("hibernate.physical_naming_strategy", context.getBean("testPhysicalNamingStrategy"))); + .getVendorProperties(); + assertThat(hibernateProperties) + .contains(entry("hibernate.physical_naming_strategy", context.getBean("testPhysicalNamingStrategy"))); assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); }); } @@ -306,9 +313,9 @@ class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTes void implicitNamingStrategyCanBeUsed() { contextRunner().withUserConfiguration(TestImplicitNamingStrategyConfiguration.class).run((context) -> { Map hibernateProperties = context.getBean(HibernateJpaConfiguration.class) - .getVendorProperties(); - assertThat(hibernateProperties).contains( - entry("hibernate.implicit_naming_strategy", context.getBean("testImplicitNamingStrategy"))); + .getVendorProperties(); + assertThat(hibernateProperties) + .contains(entry("hibernate.implicit_naming_strategy", context.getBean("testImplicitNamingStrategy"))); assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); }); } @@ -316,57 +323,57 @@ class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTes @Test void namingStrategyInstancesTakePrecedenceOverNamingStrategyProperties() { contextRunner() - .withUserConfiguration(TestPhysicalNamingStrategyConfiguration.class, - TestImplicitNamingStrategyConfiguration.class) - .withPropertyValues("spring.jpa.hibernate.naming.physical-strategy:com.example.Physical", - "spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit") - .run((context) -> { - Map hibernateProperties = context.getBean(HibernateJpaConfiguration.class) - .getVendorProperties(); - assertThat(hibernateProperties).contains( - entry("hibernate.physical_naming_strategy", context.getBean("testPhysicalNamingStrategy")), - entry("hibernate.implicit_naming_strategy", context.getBean("testImplicitNamingStrategy"))); - assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); - }); + .withUserConfiguration(TestPhysicalNamingStrategyConfiguration.class, + TestImplicitNamingStrategyConfiguration.class) + .withPropertyValues("spring.jpa.hibernate.naming.physical-strategy:com.example.Physical", + "spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit") + .run((context) -> { + Map hibernateProperties = context.getBean(HibernateJpaConfiguration.class) + .getVendorProperties(); + assertThat(hibernateProperties).contains( + entry("hibernate.physical_naming_strategy", context.getBean("testPhysicalNamingStrategy")), + entry("hibernate.implicit_naming_strategy", context.getBean("testImplicitNamingStrategy"))); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); + }); } @Test void hibernatePropertiesCustomizerTakesPrecedenceOverStrategyInstancesAndNamingStrategyProperties() { contextRunner() - .withUserConfiguration(TestHibernatePropertiesCustomizerConfiguration.class, - TestPhysicalNamingStrategyConfiguration.class, TestImplicitNamingStrategyConfiguration.class) - .withPropertyValues("spring.jpa.hibernate.naming.physical-strategy:com.example.Physical", - "spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit") - .run((context) -> { - Map hibernateProperties = context.getBean(HibernateJpaConfiguration.class) - .getVendorProperties(); - TestHibernatePropertiesCustomizerConfiguration configuration = context - .getBean(TestHibernatePropertiesCustomizerConfiguration.class); - assertThat(hibernateProperties).contains( - entry("hibernate.physical_naming_strategy", configuration.physicalNamingStrategy), - entry("hibernate.implicit_naming_strategy", configuration.implicitNamingStrategy)); - assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); - }); + .withUserConfiguration(TestHibernatePropertiesCustomizerConfiguration.class, + TestPhysicalNamingStrategyConfiguration.class, TestImplicitNamingStrategyConfiguration.class) + .withPropertyValues("spring.jpa.hibernate.naming.physical-strategy:com.example.Physical", + "spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit") + .run((context) -> { + Map hibernateProperties = context.getBean(HibernateJpaConfiguration.class) + .getVendorProperties(); + TestHibernatePropertiesCustomizerConfiguration configuration = context + .getBean(TestHibernatePropertiesCustomizerConfiguration.class); + assertThat(hibernateProperties).contains( + entry("hibernate.physical_naming_strategy", configuration.physicalNamingStrategy), + entry("hibernate.implicit_naming_strategy", configuration.implicitNamingStrategy)); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); + }); } @Test void eventListenerCanBeRegisteredAsBeans() { contextRunner().withUserConfiguration(TestInitializedJpaConfiguration.class) - .withClassLoader(new HideDataScriptClassLoader()) - .withPropertyValues("spring.jpa.show-sql=true", "spring.jpa.hibernate.ddl-auto:create-drop", - "spring.sql.init.data-locations:classpath:/city.sql", - "spring.jpa.defer-datasource-initialization=true") - .run((context) -> { - // See CityListener - assertThat(context).hasSingleBean(City.class); - assertThat(context.getBean(City.class).getName()).isEqualTo("Washington"); - }); + .withClassLoader(new HideDataScriptClassLoader()) + .withPropertyValues("spring.jpa.show-sql=true", "spring.jpa.hibernate.ddl-auto:create-drop", + "spring.sql.init.data-locations:classpath:/city.sql", + "spring.jpa.defer-datasource-initialization=true") + .run((context) -> { + // See CityListener + assertThat(context).hasSingleBean(City.class); + assertThat(context.getBean(City.class).getName()).isEqualTo("Washington"); + }); } @Test void hibernatePropertiesCustomizerCanDisableBeanContainer() { contextRunner().withUserConfiguration(DisableBeanContainerConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(City.class)); + .run((context) -> assertThat(context).doesNotHaveBean(City.class)); } @Test @@ -380,55 +387,55 @@ class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTes @Test void vendorPropertiesWhenDdlAutoPropertyIsSet() { contextRunner().withPropertyValues("spring.jpa.hibernate.ddl-auto=update") - .run(vendorProperties((vendorProperties) -> { - assertThat(vendorProperties).doesNotContainKeys(AvailableSettings.HBM2DDL_DATABASE_ACTION); - assertThat(vendorProperties.get(AvailableSettings.HBM2DDL_AUTO)).isEqualTo("update"); - })); + .run(vendorProperties((vendorProperties) -> { + assertThat(vendorProperties).doesNotContainKeys(AvailableSettings.HBM2DDL_DATABASE_ACTION); + assertThat(vendorProperties.get(AvailableSettings.HBM2DDL_AUTO)).isEqualTo("update"); + })); } @Test void vendorPropertiesWhenDdlAutoPropertyAndHibernatePropertiesAreSet() { contextRunner() - .withPropertyValues("spring.jpa.hibernate.ddl-auto=update", - "spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop") - .run(vendorProperties((vendorProperties) -> { - assertThat(vendorProperties).doesNotContainKeys(AvailableSettings.HBM2DDL_DATABASE_ACTION); - assertThat(vendorProperties.get(AvailableSettings.HBM2DDL_AUTO)).isEqualTo("create-drop"); - })); + .withPropertyValues("spring.jpa.hibernate.ddl-auto=update", + "spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop") + .run(vendorProperties((vendorProperties) -> { + assertThat(vendorProperties).doesNotContainKeys(AvailableSettings.HBM2DDL_DATABASE_ACTION); + assertThat(vendorProperties.get(AvailableSettings.HBM2DDL_AUTO)).isEqualTo("create-drop"); + })); } @Test void vendorPropertiesWhenDdlAutoPropertyIsSetToNone() { contextRunner().withPropertyValues("spring.jpa.hibernate.ddl-auto=none") - .run(vendorProperties((vendorProperties) -> assertThat(vendorProperties).doesNotContainKeys( - AvailableSettings.HBM2DDL_DATABASE_ACTION, AvailableSettings.HBM2DDL_AUTO))); + .run(vendorProperties((vendorProperties) -> assertThat(vendorProperties) + .doesNotContainKeys(AvailableSettings.HBM2DDL_DATABASE_ACTION, AvailableSettings.HBM2DDL_AUTO))); } @Test void vendorPropertiesWhenJpaDdlActionIsSet() { contextRunner() - .withPropertyValues("spring.jpa.properties.javax.persistence.schema-generation.database.action=create") - .run(vendorProperties((vendorProperties) -> { - assertThat(vendorProperties.get(AvailableSettings.HBM2DDL_DATABASE_ACTION)).isEqualTo("create"); - assertThat(vendorProperties).doesNotContainKeys(AvailableSettings.HBM2DDL_AUTO); - })); + .withPropertyValues("spring.jpa.properties.javax.persistence.schema-generation.database.action=create") + .run(vendorProperties((vendorProperties) -> { + assertThat(vendorProperties.get(AvailableSettings.HBM2DDL_DATABASE_ACTION)).isEqualTo("create"); + assertThat(vendorProperties).doesNotContainKeys(AvailableSettings.HBM2DDL_AUTO); + })); } @Test void vendorPropertiesWhenBothDdlAutoPropertiesAreSet() { contextRunner() - .withPropertyValues("spring.jpa.properties.javax.persistence.schema-generation.database.action=create", - "spring.jpa.hibernate.ddl-auto=create-only") - .run(vendorProperties((vendorProperties) -> { - assertThat(vendorProperties.get(AvailableSettings.HBM2DDL_DATABASE_ACTION)).isEqualTo("create"); - assertThat(vendorProperties.get(AvailableSettings.HBM2DDL_AUTO)).isEqualTo("create-only"); - })); + .withPropertyValues("spring.jpa.properties.javax.persistence.schema-generation.database.action=create", + "spring.jpa.hibernate.ddl-auto=create-only") + .run(vendorProperties((vendorProperties) -> { + assertThat(vendorProperties.get(AvailableSettings.HBM2DDL_DATABASE_ACTION)).isEqualTo("create"); + assertThat(vendorProperties.get(AvailableSettings.HBM2DDL_AUTO)).isEqualTo("create-only"); + })); } private ContextConsumer vendorProperties( Consumer> vendorProperties) { return (context) -> vendorProperties - .accept(context.getBean(HibernateJpaConfiguration.class).getVendorProperties()); + .accept(context.getBean(HibernateJpaConfiguration.class).getVendorProperties()); } @Test @@ -443,29 +450,30 @@ class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTes @Test void withAsyncBootstrappingAnApplicationListenerThatUsesJpaDoesNotTriggerABeanCurrentlyInCreationException() { - contextRunner().withUserConfiguration(AsyncBootstrappingConfiguration.class, - JpaUsingApplicationListenerConfiguration.class).run((context) -> { - assertThat(context).hasNotFailed(); - EventCapturingApplicationListener listener = context - .getBean(EventCapturingApplicationListener.class); - assertThat(listener.events).hasSize(1); - assertThat(listener.events).hasOnlyElementsOfType(ContextRefreshedEvent.class); - // createEntityManager requires Hibernate bootstrapping to be complete - assertThatNoException() - .isThrownBy(() -> context.getBean(EntityManagerFactory.class).createEntityManager()); - }); + contextRunner() + .withUserConfiguration(AsyncBootstrappingConfiguration.class, + JpaUsingApplicationListenerConfiguration.class) + .run((context) -> { + assertThat(context).hasNotFailed(); + EventCapturingApplicationListener listener = context.getBean(EventCapturingApplicationListener.class); + assertThat(listener.events).hasSize(1); + assertThat(listener.events).hasOnlyElementsOfType(ContextRefreshedEvent.class); + // createEntityManager requires Hibernate bootstrapping to be complete + assertThatNoException() + .isThrownBy(() -> context.getBean(EntityManagerFactory.class).createEntityManager()); + }); } @Test void whenLocalContainerEntityManagerFactoryBeanHasNoJpaVendorAdapterAutoConfigurationSucceeds() { contextRunner() - .withUserConfiguration( - TestConfigurationWithLocalContainerEntityManagerFactoryBeanWithNoJpaVendorAdapter.class) - .run((context) -> { - EntityManagerFactory factoryBean = context.getBean(EntityManagerFactory.class); - Map map = factoryBean.getProperties(); - assertThat(map.get("configured")).isEqualTo("manually"); - }); + .withUserConfiguration( + TestConfigurationWithLocalContainerEntityManagerFactoryBeanWithNoJpaVendorAdapter.class) + .run((context) -> { + EntityManagerFactory factoryBean = context.getBean(EntityManagerFactory.class); + Map map = factoryBean.getProperties(); + assertThat(map.get("configured")).isEqualTo("manually"); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernatePropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernatePropertiesTests.java index 2813367feb..2de4d8387d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernatePropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernatePropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ import static org.mockito.Mockito.never; class HibernatePropertiesTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(TestConfiguration.class); + .withUserConfiguration(TestConfiguration.class); @Mock private Supplier ddlAutoSupplier; @@ -69,80 +69,80 @@ class HibernatePropertiesTests { @Test void hibernate5CustomNamingStrategies() { this.contextRunner - .withPropertyValues("spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit", - "spring.jpa.hibernate.naming.physical-strategy:com.example.Physical") - .run(assertHibernateProperties((hibernateProperties) -> { - assertThat(hibernateProperties).contains( - entry(AvailableSettings.IMPLICIT_NAMING_STRATEGY, "com.example.Implicit"), - entry(AvailableSettings.PHYSICAL_NAMING_STRATEGY, "com.example.Physical")); - assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); - })); + .withPropertyValues("spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit", + "spring.jpa.hibernate.naming.physical-strategy:com.example.Physical") + .run(assertHibernateProperties((hibernateProperties) -> { + assertThat(hibernateProperties).contains( + entry(AvailableSettings.IMPLICIT_NAMING_STRATEGY, "com.example.Implicit"), + entry(AvailableSettings.PHYSICAL_NAMING_STRATEGY, "com.example.Physical")); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); + })); } @Test void hibernate5CustomNamingStrategiesViaJpaProperties() { this.contextRunner - .withPropertyValues("spring.jpa.properties.hibernate.implicit_naming_strategy:com.example.Implicit", - "spring.jpa.properties.hibernate.physical_naming_strategy:com.example.Physical") - .run(assertHibernateProperties((hibernateProperties) -> { - // You can override them as we don't provide any default - assertThat(hibernateProperties).contains( - entry(AvailableSettings.IMPLICIT_NAMING_STRATEGY, "com.example.Implicit"), - entry(AvailableSettings.PHYSICAL_NAMING_STRATEGY, "com.example.Physical")); - assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); - })); + .withPropertyValues("spring.jpa.properties.hibernate.implicit_naming_strategy:com.example.Implicit", + "spring.jpa.properties.hibernate.physical_naming_strategy:com.example.Physical") + .run(assertHibernateProperties((hibernateProperties) -> { + // You can override them as we don't provide any default + assertThat(hibernateProperties).contains( + entry(AvailableSettings.IMPLICIT_NAMING_STRATEGY, "com.example.Implicit"), + entry(AvailableSettings.PHYSICAL_NAMING_STRATEGY, "com.example.Physical")); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); + })); } @Test void useNewIdGeneratorMappingsDefault() { this.contextRunner.run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties) - .containsEntry(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true"))); + .containsEntry(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true"))); } @Test void useNewIdGeneratorMappingsFalse() { this.contextRunner.withPropertyValues("spring.jpa.hibernate.use-new-id-generator-mappings:false") - .run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties) - .containsEntry(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "false"))); + .run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties) + .containsEntry(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "false"))); } @Test void scannerUsesDisabledScannerByDefault() { this.contextRunner.run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties) - .containsEntry(AvailableSettings.SCANNER, "org.hibernate.boot.archive.scan.internal.DisabledScanner"))); + .containsEntry(AvailableSettings.SCANNER, "org.hibernate.boot.archive.scan.internal.DisabledScanner"))); } @Test void scannerCanBeCustomized() { this.contextRunner.withPropertyValues( "spring.jpa.properties.hibernate.archive.scanner:org.hibernate.boot.archive.scan.internal.StandardScanner") - .run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties).containsEntry( - AvailableSettings.SCANNER, "org.hibernate.boot.archive.scan.internal.StandardScanner"))); + .run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties) + .containsEntry(AvailableSettings.SCANNER, "org.hibernate.boot.archive.scan.internal.StandardScanner"))); } @Test void defaultDdlAutoIsNotInvokedIfPropertyIsSet() { this.contextRunner.withPropertyValues("spring.jpa.hibernate.ddl-auto=validate") - .run(assertDefaultDdlAutoNotInvoked("validate")); + .run(assertDefaultDdlAutoNotInvoked("validate")); } @Test void defaultDdlAutoIsNotInvokedIfHibernateSpecificPropertyIsSet() { this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.hbm2ddl.auto=create") - .run(assertDefaultDdlAutoNotInvoked("create")); + .run(assertDefaultDdlAutoNotInvoked("create")); } @Test void defaultDdlAutoIsNotInvokedAndDdlAutoIsNotSetIfJpaDbActionPropertyIsSet() { this.contextRunner - .withPropertyValues( - "spring.jpa.properties.javax.persistence.schema-generation.database.action=drop-and-create") - .run(assertHibernateProperties((hibernateProperties) -> { - assertThat(hibernateProperties).doesNotContainKey(AvailableSettings.HBM2DDL_AUTO); - assertThat(hibernateProperties).containsEntry(AvailableSettings.HBM2DDL_DATABASE_ACTION, - "drop-and-create"); - then(this.ddlAutoSupplier).should(never()).get(); - })); + .withPropertyValues( + "spring.jpa.properties.javax.persistence.schema-generation.database.action=drop-and-create") + .run(assertHibernateProperties((hibernateProperties) -> { + assertThat(hibernateProperties).doesNotContainKey(AvailableSettings.HBM2DDL_AUTO); + assertThat(hibernateProperties).containsEntry(AvailableSettings.HBM2DDL_DATABASE_ACTION, + "drop-and-create"); + then(this.ddlAutoSupplier).should(never()).get(); + })); } private ContextConsumer assertDefaultDdlAutoNotInvoked(String expectedDdlAuto) { @@ -158,8 +158,8 @@ class HibernatePropertiesTests { assertThat(context).hasSingleBean(JpaProperties.class); assertThat(context).hasSingleBean(HibernateProperties.class); Map hibernateProperties = context.getBean(HibernateProperties.class) - .determineHibernateProperties(context.getBean(JpaProperties.class).getProperties(), - new HibernateSettings().ddlAuto(this.ddlAutoSupplier)); + .determineHibernateProperties(context.getBean(JpaProperties.class).getProperties(), + new HibernateSettings().ddlAuto(this.ddlAutoSupplier)); consumer.accept(hibernateProperties); }; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfigurationTests.java index f307b04c11..80d63d1ad2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,8 +87,8 @@ import static org.mockito.Mockito.mock; class QuartzAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withPropertyValues("spring.datasource.generate-unique-name=true") - .withConfiguration(AutoConfigurations.of(QuartzAutoConfiguration.class)); + .withPropertyValues("spring.datasource.generate-unique-name=true") + .withConfiguration(AutoConfigurations.of(QuartzAutoConfiguration.class)); @Test void withNoDataSource() { @@ -101,97 +101,105 @@ class QuartzAutoConfigurationTests { @Test void withDataSourceUseMemoryByDefault() { - this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)).run((context) -> { - assertThat(context).hasSingleBean(Scheduler.class); - Scheduler scheduler = context.getBean(Scheduler.class); - assertThat(scheduler.getMetaData().getJobStoreClass()).isAssignableFrom(RAMJobStore.class); - }); + this.contextRunner + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasSingleBean(Scheduler.class); + Scheduler scheduler = context.getBean(Scheduler.class); + assertThat(scheduler.getMetaData().getJobStoreClass()).isAssignableFrom(RAMJobStore.class); + }); } @Test void withDataSource() { this.contextRunner.withUserConfiguration(QuartzJobsConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withPropertyValues("spring.quartz.job-store-type=jdbc") - .run(assertDataSourceInitializedByDataSourceDatabaseScriptInitializer("dataSource")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withPropertyValues("spring.quartz.job-store-type=jdbc") + .run(assertDataSourceInitializedByDataSourceDatabaseScriptInitializer("dataSource")); } @Test void withDataSourceAndInMemoryStoreDoesNotInitializeDataSource() { this.contextRunner.withUserConfiguration(QuartzJobsConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withPropertyValues("spring.quartz.job-store-type=memory").run((context) -> { - JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getBean("dataSource", DataSource.class)); - assertThat(jdbcTemplate.queryForList("SHOW TABLES").stream() - .map((table) -> (String) table.get("TABLE_NAME"))) - .noneMatch((name) -> name.startsWith("QRTZ")); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withPropertyValues("spring.quartz.job-store-type=memory") + .run((context) -> { + JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getBean("dataSource", DataSource.class)); + assertThat(jdbcTemplate.queryForList("SHOW TABLES") + .stream() + .map((table) -> (String) table.get("TABLE_NAME"))).noneMatch((name) -> name.startsWith("QRTZ")); + }); } @Test void withDataSourceNoTransactionManager() { this.contextRunner.withUserConfiguration(QuartzJobsConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.quartz.job-store-type=jdbc") - .run(assertDataSourceInitializedByDataSourceDatabaseScriptInitializer("dataSource")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.quartz.job-store-type=jdbc") + .run(assertDataSourceInitializedByDataSourceDatabaseScriptInitializer("dataSource")); } @Test void dataSourceWithQuartzDataSourceQualifierUsedWhenMultiplePresent() { this.contextRunner.withUserConfiguration(QuartzJobsConfiguration.class, MultipleDataSourceConfiguration.class) - .withPropertyValues("spring.quartz.job-store-type=jdbc") - .run(assertDataSourceInitializedByDataSourceDatabaseScriptInitializer("quartzDataSource")); + .withPropertyValues("spring.quartz.job-store-type=jdbc") + .run(assertDataSourceInitializedByDataSourceDatabaseScriptInitializer("quartzDataSource")); } @Test void transactionManagerWithQuartzTransactionManagerUsedWhenMultiplePresent() { this.contextRunner - .withUserConfiguration(QuartzJobsConfiguration.class, MultipleTransactionManagersConfiguration.class) - .withPropertyValues("spring.quartz.job-store-type=jdbc").run((context) -> { - SchedulerFactoryBean schedulerFactoryBean = context.getBean(SchedulerFactoryBean.class); - assertThat(schedulerFactoryBean).extracting("transactionManager") - .isEqualTo(context.getBean("quartzTransactionManager")); - }); + .withUserConfiguration(QuartzJobsConfiguration.class, MultipleTransactionManagersConfiguration.class) + .withPropertyValues("spring.quartz.job-store-type=jdbc") + .run((context) -> { + SchedulerFactoryBean schedulerFactoryBean = context.getBean(SchedulerFactoryBean.class); + assertThat(schedulerFactoryBean).extracting("transactionManager") + .isEqualTo(context.getBean("quartzTransactionManager")); + }); } @Test void withTaskExecutor() { this.contextRunner.withUserConfiguration(MockExecutorConfiguration.class) - .withPropertyValues("spring.quartz.properties.org.quartz.threadPool.threadCount=50").run((context) -> { - assertThat(context).hasSingleBean(Scheduler.class); - Scheduler scheduler = context.getBean(Scheduler.class); - assertThat(scheduler.getMetaData().getThreadPoolSize()).isEqualTo(50); - Executor executor = context.getBean(Executor.class); - then(executor).shouldHaveNoInteractions(); - }); + .withPropertyValues("spring.quartz.properties.org.quartz.threadPool.threadCount=50") + .run((context) -> { + assertThat(context).hasSingleBean(Scheduler.class); + Scheduler scheduler = context.getBean(Scheduler.class); + assertThat(scheduler.getMetaData().getThreadPoolSize()).isEqualTo(50); + Executor executor = context.getBean(Executor.class); + then(executor).shouldHaveNoInteractions(); + }); } @Test void withOverwriteExistingJobs() { this.contextRunner.withUserConfiguration(OverwriteTriggerConfiguration.class) - .withPropertyValues("spring.quartz.overwrite-existing-jobs=true").run((context) -> { - assertThat(context).hasSingleBean(Scheduler.class); - Scheduler scheduler = context.getBean(Scheduler.class); - Trigger fooTrigger = scheduler.getTrigger(TriggerKey.triggerKey("fooTrigger")); - assertThat(fooTrigger).isNotNull(); - assertThat(((SimpleTrigger) fooTrigger).getRepeatInterval()).isEqualTo(30000); - }); + .withPropertyValues("spring.quartz.overwrite-existing-jobs=true") + .run((context) -> { + assertThat(context).hasSingleBean(Scheduler.class); + Scheduler scheduler = context.getBean(Scheduler.class); + Trigger fooTrigger = scheduler.getTrigger(TriggerKey.triggerKey("fooTrigger")); + assertThat(fooTrigger).isNotNull(); + assertThat(((SimpleTrigger) fooTrigger).getRepeatInterval()).isEqualTo(30000); + }); } @Test void withConfiguredJobAndTrigger(CapturedOutput output) { this.contextRunner.withUserConfiguration(QuartzFullConfiguration.class) - .withPropertyValues("test-name=withConfiguredJobAndTrigger").run((context) -> { - assertThat(context).hasSingleBean(Scheduler.class); - Scheduler scheduler = context.getBean(Scheduler.class); - assertThat(scheduler.getJobDetail(JobKey.jobKey("fooJob"))).isNotNull(); - assertThat(scheduler.getTrigger(TriggerKey.triggerKey("fooTrigger"))).isNotNull(); - Awaitility.waitAtMost(Duration.ofSeconds(5)).untilAsserted( + .withPropertyValues("test-name=withConfiguredJobAndTrigger") + .run((context) -> { + assertThat(context).hasSingleBean(Scheduler.class); + Scheduler scheduler = context.getBean(Scheduler.class); + assertThat(scheduler.getJobDetail(JobKey.jobKey("fooJob"))).isNotNull(); + assertThat(scheduler.getTrigger(TriggerKey.triggerKey("fooTrigger"))).isNotNull(); + Awaitility.waitAtMost(Duration.ofSeconds(5)) + .untilAsserted( () -> assertThat(output).contains("withConfiguredJobAndTrigger").contains("jobDataValue")); - }); + }); } @Test @@ -207,11 +215,11 @@ class QuartzAutoConfigurationTests { @Test void withQuartzProperties() { this.contextRunner.withPropertyValues("spring.quartz.properties.org.quartz.scheduler.instanceId=FOO") - .run((context) -> { - assertThat(context).hasSingleBean(Scheduler.class); - Scheduler scheduler = context.getBean(Scheduler.class); - assertThat(scheduler.getSchedulerInstanceId()).isEqualTo("FOO"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Scheduler.class); + Scheduler scheduler = context.getBean(Scheduler.class); + assertThat(scheduler.getSchedulerInstanceId()).isEqualTo("FOO"); + }); } @Test @@ -243,27 +251,29 @@ class QuartzAutoConfigurationTests { @Test void withCustomConfiguration() { - this.contextRunner.withPropertyValues("spring.quartz.auto-startup=false", "spring.quartz.startup-delay=1m", - "spring.quartz.wait-for-jobs-to-complete-on-shutdown=true", - "spring.quartz.overwrite-existing-jobs=true").run((context) -> { - assertThat(context).hasSingleBean(SchedulerFactoryBean.class); - SchedulerFactoryBean schedulerFactory = context.getBean(SchedulerFactoryBean.class); - assertThat(schedulerFactory.isAutoStartup()).isFalse(); - assertThat(schedulerFactory).hasFieldOrPropertyWithValue("startupDelay", 60); - assertThat(schedulerFactory).hasFieldOrPropertyWithValue("waitForJobsToCompleteOnShutdown", true); - assertThat(schedulerFactory).hasFieldOrPropertyWithValue("overwriteExistingJobs", true); - }); + this.contextRunner + .withPropertyValues("spring.quartz.auto-startup=false", "spring.quartz.startup-delay=1m", + "spring.quartz.wait-for-jobs-to-complete-on-shutdown=true", + "spring.quartz.overwrite-existing-jobs=true") + .run((context) -> { + assertThat(context).hasSingleBean(SchedulerFactoryBean.class); + SchedulerFactoryBean schedulerFactory = context.getBean(SchedulerFactoryBean.class); + assertThat(schedulerFactory.isAutoStartup()).isFalse(); + assertThat(schedulerFactory).hasFieldOrPropertyWithValue("startupDelay", 60); + assertThat(schedulerFactory).hasFieldOrPropertyWithValue("waitForJobsToCompleteOnShutdown", true); + assertThat(schedulerFactory).hasFieldOrPropertyWithValue("overwriteExistingJobs", true); + }); } @Test void withLiquibase() { this.contextRunner.withUserConfiguration(QuartzJobsConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, LiquibaseAutoConfiguration.class)) - .withPropertyValues("spring.quartz.job-store-type=jdbc", "spring.quartz.jdbc.initialize-schema=never", - "spring.liquibase.change-log=classpath:org/quartz/impl/jdbcjobstore/liquibase.quartz.init.xml") - .run(assertDataSourceInitialized("dataSource").andThen((context) -> assertThat(context) - .doesNotHaveBean(QuartzDataSourceScriptDatabaseInitializer.class))); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, LiquibaseAutoConfiguration.class)) + .withPropertyValues("spring.quartz.job-store-type=jdbc", "spring.quartz.jdbc.initialize-schema=never", + "spring.liquibase.change-log=classpath:org/quartz/impl/jdbcjobstore/liquibase.quartz.init.xml") + .run(assertDataSourceInitialized("dataSource").andThen( + (context) -> assertThat(context).doesNotHaveBean(QuartzDataSourceScriptDatabaseInitializer.class))); } @Test @@ -273,34 +283,33 @@ class QuartzAutoConfigurationTests { Files.copy(stream, flywayLocation.resolve("V2__quartz.sql")); } this.contextRunner.withUserConfiguration(QuartzJobsConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, FlywayAutoConfiguration.class)) - .withPropertyValues("spring.quartz.job-store-type=jdbc", "spring.quartz.jdbc.initialize-schema=never", - "spring.flyway.locations=filesystem:" + flywayLocation, - "spring.flyway.baseline-on-migrate=true") - .run(assertDataSourceInitialized("dataSource").andThen((context) -> assertThat(context) - .doesNotHaveBean(QuartzDataSourceScriptDatabaseInitializer.class))); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, FlywayAutoConfiguration.class)) + .withPropertyValues("spring.quartz.job-store-type=jdbc", "spring.quartz.jdbc.initialize-schema=never", + "spring.flyway.locations=filesystem:" + flywayLocation, "spring.flyway.baseline-on-migrate=true") + .run(assertDataSourceInitialized("dataSource").andThen( + (context) -> assertThat(context).doesNotHaveBean(QuartzDataSourceScriptDatabaseInitializer.class))); } @Test void schedulerNameWithDedicatedProperty() { this.contextRunner.withPropertyValues("spring.quartz.scheduler-name=testScheduler") - .run(assertSchedulerName("testScheduler")); + .run(assertSchedulerName("testScheduler")); } @Test void schedulerNameWithQuartzProperty() { this.contextRunner - .withPropertyValues("spring.quartz.properties.org.quartz.scheduler.instanceName=testScheduler") - .run(assertSchedulerName("testScheduler")); + .withPropertyValues("spring.quartz.properties.org.quartz.scheduler.instanceName=testScheduler") + .run(assertSchedulerName("testScheduler")); } @Test void schedulerNameWithDedicatedPropertyTakesPrecedence() { this.contextRunner - .withPropertyValues("spring.quartz.scheduler-name=specificTestScheduler", - "spring.quartz.properties.org.quartz.scheduler.instanceName=testScheduler") - .run(assertSchedulerName("specificTestScheduler")); + .withPropertyValues("spring.quartz.scheduler-name=specificTestScheduler", + "spring.quartz.properties.org.quartz.scheduler.instanceName=testScheduler") + .run(assertSchedulerName("specificTestScheduler")); } @Test @@ -311,11 +320,12 @@ class QuartzAutoConfigurationTests { @Test void whenTheUserDefinesTheirOwnQuartzDatabaseInitializerThenTheAutoConfiguredInitializerBacksOff() { this.contextRunner.withUserConfiguration(CustomQuartzDatabaseInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withPropertyValues("spring.quartz.job-store-type=jdbc") - .run((context) -> assertThat(context).hasSingleBean(QuartzDataSourceScriptDatabaseInitializer.class) - .doesNotHaveBean("quartzDataSourceScriptDatabaseInitializer").hasBean("customInitializer")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withPropertyValues("spring.quartz.job-store-type=jdbc") + .run((context) -> assertThat(context).hasSingleBean(QuartzDataSourceScriptDatabaseInitializer.class) + .doesNotHaveBean("quartzDataSourceScriptDatabaseInitializer") + .hasBean("customInitializer")); } @Test @@ -323,20 +333,22 @@ class QuartzAutoConfigurationTests { @SuppressWarnings("deprecation") void whenTheUserDefinesTheirOwnQuartzDataSourceInitializerThenTheAutoConfiguredInitializerBacksOff() { this.contextRunner.withUserConfiguration(CustomQuartzDataSourceInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withPropertyValues("spring.quartz.job-store-type=jdbc") - .run((context) -> assertThat(context).doesNotHaveBean(QuartzDataSourceScriptDatabaseInitializer.class) - .hasSingleBean(QuartzDataSourceInitializer.class).hasBean("customInitializer")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withPropertyValues("spring.quartz.job-store-type=jdbc") + .run((context) -> assertThat(context).doesNotHaveBean(QuartzDataSourceScriptDatabaseInitializer.class) + .hasSingleBean(QuartzDataSourceInitializer.class) + .hasBean("customInitializer")); } @Test void whenTheUserDefinesTheirOwnDatabaseInitializerThenTheAutoConfiguredQuartzInitializerRemains() { this.contextRunner.withUserConfiguration(CustomDatabaseInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withPropertyValues("spring.quartz.job-store-type=jdbc").run((context) -> assertThat(context) - .hasSingleBean(QuartzDataSourceScriptDatabaseInitializer.class).hasBean("customInitializer")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withPropertyValues("spring.quartz.job-store-type=jdbc") + .run((context) -> assertThat(context).hasSingleBean(QuartzDataSourceScriptDatabaseInitializer.class) + .hasBean("customInitializer")); } private ContextConsumer assertDataSourceInitialized(String dataSourceName) { @@ -346,9 +358,9 @@ class QuartzAutoConfigurationTests { assertThat(scheduler.getMetaData().getJobStoreClass()).isAssignableFrom(LocalDataSourceJobStore.class); JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getBean(dataSourceName, DataSource.class)); assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM QRTZ_JOB_DETAILS", Integer.class)) - .isEqualTo(2); + .isEqualTo(2); assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM QRTZ_SIMPLE_TRIGGERS", Integer.class)) - .isEqualTo(0); + .isEqualTo(0); }; } @@ -357,7 +369,7 @@ class QuartzAutoConfigurationTests { return assertDataSourceInitialized(dataSourceName).andThen((context) -> { assertThat(context).hasSingleBean(QuartzDataSourceScriptDatabaseInitializer.class); QuartzDataSourceScriptDatabaseInitializer initializer = context - .getBean(QuartzDataSourceScriptDatabaseInitializer.class); + .getBean(QuartzDataSourceScriptDatabaseInitializer.class); assertThat(initializer).hasFieldOrPropertyWithValue("dataSource", context.getBean(dataSourceName)); }); } @@ -396,17 +408,25 @@ class QuartzAutoConfigurationTests { @Bean JobDetail fooJob() { - return JobBuilder.newJob().ofType(FooJob.class).withIdentity("fooJob") - .usingJobData("jobDataKey", "jobDataValue").storeDurably().build(); + return JobBuilder.newJob() + .ofType(FooJob.class) + .withIdentity("fooJob") + .usingJobData("jobDataKey", "jobDataValue") + .storeDurably() + .build(); } @Bean Trigger fooTrigger(JobDetail jobDetail) { - SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10) - .repeatForever(); - - return TriggerBuilder.newTrigger().forJob(jobDetail).withIdentity("fooTrigger") - .withSchedule(scheduleBuilder).build(); + SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() + .withIntervalInSeconds(10) + .repeatForever(); + + return TriggerBuilder.newTrigger() + .forJob(jobDetail) + .withIdentity("fooTrigger") + .withSchedule(scheduleBuilder) + .build(); } } @@ -417,11 +437,15 @@ class QuartzAutoConfigurationTests { @Bean Trigger anotherFooTrigger(JobDetail fooJob) { - SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(30) - .repeatForever(); - - return TriggerBuilder.newTrigger().forJob(fooJob).withIdentity("fooTrigger").withSchedule(scheduleBuilder) - .build(); + SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() + .withIntervalInSeconds(30) + .repeatForever(); + + return TriggerBuilder.newTrigger() + .forJob(fooJob) + .withIdentity("fooTrigger") + .withSchedule(scheduleBuilder) + .build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceInitializerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceInitializerTests.java index be5656f172..46d2314cd4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceInitializerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,10 +47,10 @@ import static org.mockito.Mockito.mock; class QuartzDataSourceInitializerTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class)) - .withPropertyValues("spring.datasource.url=" + String.format( - "jdbc:h2:mem:test-%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE", UUID.randomUUID().toString())); + .withConfiguration( + AutoConfigurations.of(DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class)) + .withPropertyValues("spring.datasource.url=" + String + .format("jdbc:h2:mem:test-%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE", UUID.randomUUID().toString())); @Test void getDatabaseNameWithPlatformDoesNotTouchDataSource() { @@ -65,24 +65,26 @@ class QuartzDataSourceInitializerTests { @Test void hashIsUsedAsACommentPrefixByDefault() { - this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues( - "spring.quartz.jdbc.schema=classpath:org/springframework/boot/autoconfigure/quartz/tables_#_comments.sql") - .run(this::assertThatDataSourceHasBeenInitialized); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues( + "spring.quartz.jdbc.schema=classpath:org/springframework/boot/autoconfigure/quartz/tables_#_comments.sql") + .run(this::assertThatDataSourceHasBeenInitialized); } @Test void doubleDashIsUsedAsACommentPrefixByDefault() { - this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues( - "spring.quartz.jdbc.schema=classpath:org/springframework/boot/autoconfigure/quartz/tables_--_comments.sql") - .run(this::assertThatDataSourceHasBeenInitialized); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues( + "spring.quartz.jdbc.schema=classpath:org/springframework/boot/autoconfigure/quartz/tables_--_comments.sql") + .run(this::assertThatDataSourceHasBeenInitialized); } @Test void commentPrefixCanBeCustomized() { - this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues( - "spring.quartz.jdbc.comment-prefix=**", - "spring.quartz.jdbc.schema=classpath:org/springframework/boot/autoconfigure/quartz/tables_custom_comment_prefix.sql") - .run(this::assertThatDataSourceHasBeenInitialized); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.quartz.jdbc.comment-prefix=**", + "spring.quartz.jdbc.schema=classpath:org/springframework/boot/autoconfigure/quartz/tables_custom_comment_prefix.sql") + .run(this::assertThatDataSourceHasBeenInitialized); } private void assertThatDataSourceHasBeenInitialized(AssertableApplicationContext context) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceScriptDatabaseInitializerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceScriptDatabaseInitializerTests.java index c1408c97f5..6ed299543d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceScriptDatabaseInitializerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceScriptDatabaseInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ class QuartzDataSourceScriptDatabaseInitializerTests { DatabaseInitializationSettings settings = QuartzDataSourceScriptDatabaseInitializer.getSettings(dataSource, properties); assertThat(settings.getSchemaLocations()) - .containsOnly("classpath:org/quartz/impl/jdbcjobstore/tables_test.sql"); + .containsOnly("classpath:org/quartz/impl/jdbcjobstore/tables_test.sql"); then(dataSource).shouldHaveNoInteractions(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/NoConnectionFactoryBeanFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/NoConnectionFactoryBeanFailureAnalyzerTests.java index 8407735a94..4b45915fc4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/NoConnectionFactoryBeanFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/NoConnectionFactoryBeanFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,20 +41,20 @@ class NoConnectionFactoryBeanFailureAnalyzerTests { void analyzeWhenNoSuchBeanDefinitionExceptionForDifferentTypeShouldReturnNull() { assertThat( new NoConnectionFactoryBeanFailureAnalyzer().analyze(new NoSuchBeanDefinitionException(String.class))) - .isNull(); + .isNull(); } @Test void analyzeWhenNoSuchBeanDefinitionExceptionButProviderIsAvailableShouldReturnNull() { assertThat(new NoConnectionFactoryBeanFailureAnalyzer() - .analyze(new NoSuchBeanDefinitionException(ConnectionFactory.class))).isNull(); + .analyze(new NoSuchBeanDefinitionException(ConnectionFactory.class))).isNull(); } @Test void analyzeWhenNoSuchBeanDefinitionExceptionAndNoProviderShouldAnalyze() { assertThat(new NoConnectionFactoryBeanFailureAnalyzer( new FilteredClassLoader(("META-INF/services/" + ConnectionFactoryProvider.class.getName())::equals)) - .analyze(new NoSuchBeanDefinitionException(ConnectionFactory.class))).isNotNull(); + .analyze(new NoSuchBeanDefinitionException(ConnectionFactory.class))).isNotNull(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcAutoConfigurationTests.java index 7a092d4b9b..8c475362c1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,173 +58,191 @@ import static org.assertj.core.api.Assertions.assertThat; class R2dbcAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)); @Test void configureWithUrlCreateConnectionPoolByDefault() { this.contextRunner.withPropertyValues("spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName()) - .run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class); - assertThat(context.getBean(ConnectionPool.class)).extracting(ConnectionPool::unwrap) - .satisfies((connectionFactory) -> assertThat(connectionFactory) - .asInstanceOf(type(OptionsCapableConnectionFactory.class)) - .extracting(Wrapped::unwrap) - .isExactlyInstanceOf(H2ConnectionFactory.class)); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class); + assertThat(context.getBean(ConnectionPool.class)).extracting(ConnectionPool::unwrap) + .satisfies((connectionFactory) -> assertThat(connectionFactory) + .asInstanceOf(type(OptionsCapableConnectionFactory.class)) + .extracting(Wrapped::unwrap) + .isExactlyInstanceOf(H2ConnectionFactory.class)); + }); } @Test void configureWithUrlAndPoolPropertiesApplyProperties() { - this.contextRunner.withPropertyValues("spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName(), - "spring.r2dbc.pool.max-size=15", "spring.r2dbc.pool.max-acquire-time=3m").run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class) - .hasSingleBean(R2dbcProperties.class); - ConnectionPool connectionPool = context.getBean(ConnectionPool.class); - PoolMetrics poolMetrics = connectionPool.getMetrics().get(); - assertThat(poolMetrics.getMaxAllocatedSize()).isEqualTo(15); - assertThat(connectionPool).hasFieldOrPropertyWithValue("maxAcquireTime", Duration.ofMinutes(3)); - }); + this.contextRunner + .withPropertyValues("spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName(), + "spring.r2dbc.pool.max-size=15", "spring.r2dbc.pool.max-acquire-time=3m") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(ConnectionPool.class) + .hasSingleBean(R2dbcProperties.class); + ConnectionPool connectionPool = context.getBean(ConnectionPool.class); + PoolMetrics poolMetrics = connectionPool.getMetrics().get(); + assertThat(poolMetrics.getMaxAllocatedSize()).isEqualTo(15); + assertThat(connectionPool).hasFieldOrPropertyWithValue("maxAcquireTime", Duration.ofMinutes(3)); + }); } @Test void configureWithUrlAndDefaultDoNotOverrideDefaultTimeouts() { this.contextRunner.withPropertyValues("spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName()) - .run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class) - .hasSingleBean(R2dbcProperties.class); - ConnectionPool connectionPool = context.getBean(ConnectionPool.class); - assertThat(connectionPool).hasFieldOrPropertyWithValue("maxAcquireTime", Duration.ofMillis(-1)); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(ConnectionPool.class) + .hasSingleBean(R2dbcProperties.class); + ConnectionPool connectionPool = context.getBean(ConnectionPool.class); + assertThat(connectionPool).hasFieldOrPropertyWithValue("maxAcquireTime", Duration.ofMillis(-1)); + }); } @Test void configureWithUrlPoolAndPoolPropertiesFails() { this.contextRunner - .withPropertyValues("spring.r2dbc.url:r2dbc:pool:h2:mem:///" + randomDatabaseName() + "?maxSize=12", - "spring.r2dbc.pool.max-size=15") - .run((context) -> assertThat(context).getFailure().getRootCause() - .isInstanceOf(MultipleConnectionPoolConfigurationsException.class)); + .withPropertyValues("spring.r2dbc.url:r2dbc:pool:h2:mem:///" + randomDatabaseName() + "?maxSize=12", + "spring.r2dbc.pool.max-size=15") + .run((context) -> assertThat(context).getFailure() + .getRootCause() + .isInstanceOf(MultipleConnectionPoolConfigurationsException.class)); } @Test void configureWithUrlPoolAndPropertyBasedPoolingDisabledFails() { this.contextRunner - .withPropertyValues("spring.r2dbc.url:r2dbc:pool:h2:mem:///" + randomDatabaseName() + "?maxSize=12", - "spring.r2dbc.pool.enabled=false") - .run((context) -> assertThat(context).getFailure().getRootCause() - .isInstanceOf(MultipleConnectionPoolConfigurationsException.class)); + .withPropertyValues("spring.r2dbc.url:r2dbc:pool:h2:mem:///" + randomDatabaseName() + "?maxSize=12", + "spring.r2dbc.pool.enabled=false") + .run((context) -> assertThat(context).getFailure() + .getRootCause() + .isInstanceOf(MultipleConnectionPoolConfigurationsException.class)); } @Test void configureWithUrlPoolAndNoPoolPropertiesCreatesPool() { this.contextRunner - .withPropertyValues("spring.r2dbc.url:r2dbc:pool:h2:mem:///" + randomDatabaseName() + "?maxSize=12") - .run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class); - ConnectionPool connectionPool = context.getBean(ConnectionPool.class); - assertThat(connectionPool.getMetrics().get().getMaxAllocatedSize()).isEqualTo(12); - }); + .withPropertyValues("spring.r2dbc.url:r2dbc:pool:h2:mem:///" + randomDatabaseName() + "?maxSize=12") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class); + ConnectionPool connectionPool = context.getBean(ConnectionPool.class); + assertThat(connectionPool.getMetrics().get().getMaxAllocatedSize()).isEqualTo(12); + }); } @Test void configureWithPoolEnabledCreateConnectionPool() { this.contextRunner - .withPropertyValues("spring.r2dbc.pool.enabled=true", - "spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName() - + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") - .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) - .hasSingleBean(ConnectionPool.class)); + .withPropertyValues("spring.r2dbc.pool.enabled=true", + "spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName() + + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") + .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(ConnectionPool.class)); } @Test void configureWithPoolDisabledCreateGenericConnectionFactory() { - this.contextRunner.withPropertyValues("spring.r2dbc.pool.enabled=false", "spring.r2dbc.url:r2dbc:h2:mem:///" - + randomDatabaseName() + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE").run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).doesNotHaveBean(ConnectionPool.class); - assertThat(context.getBean(ConnectionFactory.class)) - .asInstanceOf(type(OptionsCapableConnectionFactory.class)) - .extracting(Wrapped::unwrap) - .isExactlyInstanceOf(H2ConnectionFactory.class); - }); + this.contextRunner + .withPropertyValues("spring.r2dbc.pool.enabled=false", + "spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName() + + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class).doesNotHaveBean(ConnectionPool.class); + assertThat(context.getBean(ConnectionFactory.class)) + .asInstanceOf(type(OptionsCapableConnectionFactory.class)) + .extracting(Wrapped::unwrap) + .isExactlyInstanceOf(H2ConnectionFactory.class); + }); } @Test void configureWithoutPoolInvokeOptionCustomizer() { this.contextRunner - .withPropertyValues("spring.r2dbc.pool.enabled=false", "spring.r2dbc.url:r2dbc:simple://host/database") - .withUserConfiguration(CustomizerConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).doesNotHaveBean(ConnectionPool.class); - ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class); - assertThat(connectionFactory).asInstanceOf(type(OptionsCapableConnectionFactory.class)) - .extracting(OptionsCapableConnectionFactory::getOptions) - .satisfies((options) -> assertThat(options.getRequiredValue(Option.valueOf("customized"))) - .isEqualTo(Boolean.TRUE)); - }); + .withPropertyValues("spring.r2dbc.pool.enabled=false", "spring.r2dbc.url:r2dbc:simple://host/database") + .withUserConfiguration(CustomizerConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class).doesNotHaveBean(ConnectionPool.class); + ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class); + assertThat(connectionFactory).asInstanceOf(type(OptionsCapableConnectionFactory.class)) + .extracting(OptionsCapableConnectionFactory::getOptions) + .satisfies((options) -> assertThat(options.getRequiredValue(Option.valueOf("customized"))) + .isEqualTo(Boolean.TRUE)); + }); } @Test void configureWithPoolInvokeOptionCustomizer() { this.contextRunner.withPropertyValues("spring.r2dbc.url:r2dbc:simple://host/database") - .withUserConfiguration(CustomizerConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class); - ConnectionFactory pool = context.getBean(ConnectionFactory.class); - ConnectionFactory connectionFactory = ((ConnectionPool) pool).unwrap(); - assertThat(connectionFactory).asInstanceOf(type(OptionsCapableConnectionFactory.class)) - .extracting(OptionsCapableConnectionFactory::getOptions) - .satisfies((options) -> assertThat(options.getRequiredValue(Option.valueOf("customized"))) - .isEqualTo(Boolean.TRUE)); - }); + .withUserConfiguration(CustomizerConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class); + ConnectionFactory pool = context.getBean(ConnectionFactory.class); + ConnectionFactory connectionFactory = ((ConnectionPool) pool).unwrap(); + assertThat(connectionFactory).asInstanceOf(type(OptionsCapableConnectionFactory.class)) + .extracting(OptionsCapableConnectionFactory::getOptions) + .satisfies((options) -> assertThat(options.getRequiredValue(Option.valueOf("customized"))) + .isEqualTo(Boolean.TRUE)); + }); } @Test void configureWithInvalidUrlThrowsAppropriateException() { this.contextRunner.withPropertyValues("spring.r2dbc.url:r2dbc:not-going-to-work") - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); } @Test void configureWithoutSpringJdbcCreateConnectionFactory() { this.contextRunner.withPropertyValues("spring.r2dbc.pool.enabled=false", "spring.r2dbc.url:r2dbc:simple://foo") - .withClassLoader(new FilteredClassLoader("org.springframework.jdbc")).run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class); - assertThat(context.getBean(ConnectionFactory.class)) - .asInstanceOf(type(OptionsCapableConnectionFactory.class)) - .extracting(Wrapped::unwrap) - .isExactlyInstanceOf(SimpleTestConnectionFactory.class); - }); + .withClassLoader(new FilteredClassLoader("org.springframework.jdbc")) + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class); + assertThat(context.getBean(ConnectionFactory.class)) + .asInstanceOf(type(OptionsCapableConnectionFactory.class)) + .extracting(Wrapped::unwrap) + .isExactlyInstanceOf(SimpleTestConnectionFactory.class); + }); } @Test void configureWithoutPoolShouldApplyAdditionalProperties() { - this.contextRunner.withPropertyValues("spring.r2dbc.pool.enabled=false", "spring.r2dbc.url:r2dbc:simple://foo", - "spring.r2dbc.properties.test=value", "spring.r2dbc.properties.another=2").run((context) -> { - ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class); - assertThat(connectionFactory).asInstanceOf(type(OptionsCapableConnectionFactory.class)) - .extracting(OptionsCapableConnectionFactory::getOptions).satisfies((options) -> { - assertThat(options.getRequiredValue(Option.valueOf("test"))).isEqualTo("value"); - assertThat(options.getRequiredValue(Option.valueOf("another"))).isEqualTo("2"); - }); - }); + this.contextRunner + .withPropertyValues("spring.r2dbc.pool.enabled=false", "spring.r2dbc.url:r2dbc:simple://foo", + "spring.r2dbc.properties.test=value", "spring.r2dbc.properties.another=2") + .run((context) -> { + ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class); + assertThat(connectionFactory).asInstanceOf(type(OptionsCapableConnectionFactory.class)) + .extracting(OptionsCapableConnectionFactory::getOptions) + .satisfies((options) -> { + assertThat(options.getRequiredValue(Option.valueOf("test"))).isEqualTo("value"); + assertThat(options.getRequiredValue(Option.valueOf("another"))).isEqualTo("2"); + }); + }); } @Test void configureWithPoolShouldApplyAdditionalProperties() { - this.contextRunner.withPropertyValues("spring.r2dbc.url:r2dbc:simple://foo", - "spring.r2dbc.properties.test=value", "spring.r2dbc.properties.another=2").run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class); - ConnectionFactory connectionFactory = context.getBean(ConnectionPool.class).unwrap(); - assertThat(connectionFactory).asInstanceOf(type(OptionsCapableConnectionFactory.class)) - .extracting(OptionsCapableConnectionFactory::getOptions).satisfies((options) -> { - assertThat(options.getRequiredValue(Option.valueOf("test"))).isEqualTo("value"); - assertThat(options.getRequiredValue(Option.valueOf("another"))).isEqualTo("2"); - }); - }); + this.contextRunner + .withPropertyValues("spring.r2dbc.url:r2dbc:simple://foo", "spring.r2dbc.properties.test=value", + "spring.r2dbc.properties.another=2") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class); + ConnectionFactory connectionFactory = context.getBean(ConnectionPool.class).unwrap(); + assertThat(connectionFactory).asInstanceOf(type(OptionsCapableConnectionFactory.class)) + .extracting(OptionsCapableConnectionFactory::getOptions) + .satisfies((options) -> { + assertThat(options.getRequiredValue(Option.valueOf("test"))).isEqualTo("value"); + assertThat(options.getRequiredValue(Option.valueOf("another"))).isEqualTo("2"); + }); + }); } @Test void configureWithoutUrlShouldCreateEmbeddedConnectionPoolByDefault() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) - .hasSingleBean(ConnectionPool.class)); + .hasSingleBean(ConnectionPool.class)); } @Test @@ -232,58 +250,60 @@ class R2dbcAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.r2dbc.pool.enabled=false").run((context) -> { assertThat(context).hasSingleBean(ConnectionFactory.class).doesNotHaveBean(ConnectionPool.class); assertThat(context.getBean(ConnectionFactory.class)) - .asInstanceOf(type(OptionsCapableConnectionFactory.class)) - .extracting(Wrapped::unwrap).isExactlyInstanceOf(H2ConnectionFactory.class); + .asInstanceOf(type(OptionsCapableConnectionFactory.class)) + .extracting(Wrapped::unwrap) + .isExactlyInstanceOf(H2ConnectionFactory.class); }); } @Test void configureWithoutUrlAndSprigJdbcCreateEmbeddedConnectionFactory() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.jdbc")) - .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) - .hasSingleBean(ConnectionPool.class)); + .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(ConnectionPool.class)); } @Test void configureWithoutUrlAndEmbeddedCandidateFails() { this.contextRunner.withClassLoader(new DisableEmbeddedDatabaseClassLoader()).run((context) -> { assertThat(context).hasFailed(); - assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("Failed to determine a suitable R2DBC Connection URL"); + assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("Failed to determine a suitable R2DBC Connection URL"); }); } @Test void configureWithoutUrlAndNoConnectionFactoryProviderBacksOff() { this.contextRunner - .withClassLoader(new FilteredClassLoader( - ("META-INF/services/" + ConnectionFactoryProvider.class.getName())::equals)) - .run((context) -> assertThat(context).doesNotHaveBean(R2dbcAutoConfiguration.class)); + .withClassLoader( + new FilteredClassLoader(("META-INF/services/" + ConnectionFactoryProvider.class.getName())::equals)) + .run((context) -> assertThat(context).doesNotHaveBean(R2dbcAutoConfiguration.class)); } @Test void configureWithDataSourceAutoConfigurationDoesNotCreateDataSource() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) - .doesNotHaveBean(DataSource.class)); + .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) + .doesNotHaveBean(DataSource.class)); } @Test void databaseClientIsConfigured() { this.contextRunner.withPropertyValues("spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName()) - .run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(DatabaseClient.class); - assertThat(context.getBean(DatabaseClient.class).getConnectionFactory()) - .isSameAs(context.getBean(ConnectionFactory.class)); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(DatabaseClient.class); + assertThat(context.getBean(DatabaseClient.class).getConnectionFactory()) + .isSameAs(context.getBean(ConnectionFactory.class)); + }); } @Test void databaseClientBacksOffIfSpringR2dbcIsNotAvailable() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.r2dbc")) - .withPropertyValues("spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName()) - .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) - .doesNotHaveBean(DatabaseClient.class)); + .withPropertyValues("spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName()) + .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) + .doesNotHaveBean(DatabaseClient.class)); } private InstanceOfAssertFactory> type(Class type) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcAutoConfigurationWithoutConnectionPoolTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcAutoConfigurationWithoutConnectionPoolTests.java index e9ef7bf097..cdf1fc63b8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcAutoConfigurationWithoutConnectionPoolTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcAutoConfigurationWithoutConnectionPoolTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,37 +43,41 @@ import static org.assertj.core.api.Assertions.assertThat; class R2dbcAutoConfigurationWithoutConnectionPoolTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)); @Test void configureWithoutR2dbcPoolCreateGenericConnectionFactory() { - this.contextRunner.withPropertyValues("spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName() - + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE").run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class); - assertThat(context.getBean(ConnectionFactory.class)) - .asInstanceOf(type(OptionsCapableConnectionFactory.class)) - .extracting(Wrapped::unwrap) - .isExactlyInstanceOf(H2ConnectionFactory.class); - }); + this.contextRunner + .withPropertyValues("spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName() + + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class); + assertThat(context.getBean(ConnectionFactory.class)) + .asInstanceOf(type(OptionsCapableConnectionFactory.class)) + .extracting(Wrapped::unwrap) + .isExactlyInstanceOf(H2ConnectionFactory.class); + }); } @Test void configureWithoutR2dbcPoolAndPoolEnabledShouldFail() { this.contextRunner - .withPropertyValues("spring.r2dbc.pool.enabled=true", - "spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName() - + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") - .run((context) -> assertThat(context).getFailure().getRootCause() - .isInstanceOf(MissingR2dbcPoolDependencyException.class)); + .withPropertyValues("spring.r2dbc.pool.enabled=true", + "spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName() + + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") + .run((context) -> assertThat(context).getFailure() + .getRootCause() + .isInstanceOf(MissingR2dbcPoolDependencyException.class)); } @Test void configureWithoutR2dbcPoolAndPoolUrlShouldFail() { this.contextRunner - .withPropertyValues("spring.r2dbc.url:r2dbc:pool:h2:mem:///" + randomDatabaseName() - + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") - .run((context) -> assertThat(context).getFailure().getRootCause() - .isInstanceOf(MissingR2dbcPoolDependencyException.class)); + .withPropertyValues("spring.r2dbc.url:r2dbc:pool:h2:mem:///" + randomDatabaseName() + + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") + .run((context) -> assertThat(context).getFailure() + .getRootCause() + .isInstanceOf(MissingR2dbcPoolDependencyException.class)); } private InstanceOfAssertFactory> type(Class type) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcTransactionManagerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcTransactionManagerAutoConfigurationTests.java index 7b1cdf0dd6..379a1b6e67 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcTransactionManagerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcTransactionManagerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,17 +56,17 @@ class R2dbcTransactionManagerAutoConfigurationTests { @Test void singleTransactionManager() { this.contextRunner.withUserConfiguration(SingleConnectionFactoryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(TransactionalOperator.class) - .hasSingleBean(ReactiveTransactionManager.class)); + .run((context) -> assertThat(context).hasSingleBean(TransactionalOperator.class) + .hasSingleBean(ReactiveTransactionManager.class)); } @Test void transactionManagerEnabled() { this.contextRunner.withUserConfiguration(SingleConnectionFactoryConfiguration.class, BaseConfiguration.class) - .run((context) -> { - TransactionalService bean = context.getBean(TransactionalService.class); - bean.isTransactionActive().as(StepVerifier::create).expectNext(true).verifyComplete(); - }); + .run((context) -> { + TransactionalService bean = context.getBean(TransactionalService.class); + bean.isTransactionActive().as(StepVerifier::create).expectNext(true).verifyComplete(); + }); } @Configuration(proxyBeanMethods = false) @@ -108,7 +108,7 @@ class R2dbcTransactionManagerAutoConfigurationTests { @Override public Mono isTransactionActive() { return TransactionSynchronizationManager.forCurrentTransaction() - .map(TransactionSynchronizationManager::isActualTransactionActive); + .map(TransactionSynchronizationManager::isActualTransactionActive); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfigurationTests.java index aee5e0f705..5040842595 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,8 @@ import static org.assertj.core.api.Assertions.assertThat; class RSocketMessagingAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RSocketMessagingAutoConfiguration.class)) - .withUserConfiguration(BaseConfiguration.class); + .withConfiguration(AutoConfigurations.of(RSocketMessagingAutoConfiguration.class)) + .withUserConfiguration(BaseConfiguration.class); @Test void shouldCreateDefaultBeans() { @@ -50,17 +50,18 @@ class RSocketMessagingAutoConfigurationTests { @Test void shouldFailOnMissingStrategies() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(RSocketMessagingAutoConfiguration.class)) - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure().getMessage()).contains("No qualifying bean of type " - + "'org.springframework.messaging.rsocket.RSocketStrategies' available"); - }); + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure().getMessage()).contains("No qualifying bean of type " + + "'org.springframework.messaging.rsocket.RSocketStrategies' available"); + }); } @Test void shouldUseCustomSocketAcceptor() { - this.contextRunner.withUserConfiguration(CustomMessageHandler.class).run((context) -> assertThat(context) - .getBeanNames(RSocketMessageHandler.class).containsOnly("customMessageHandler")); + this.contextRunner.withUserConfiguration(CustomMessageHandler.class) + .run((context) -> assertThat(context).getBeanNames(RSocketMessageHandler.class) + .containsOnly("customMessageHandler")); } @Test @@ -76,8 +77,10 @@ class RSocketMessagingAutoConfigurationTests { @Bean RSocketStrategies rSocketStrategies() { - return RSocketStrategies.builder().encoder(CharSequenceEncoder.textPlainOnly()) - .decoder(StringDecoder.allMimeTypes()).build(); + return RSocketStrategies.builder() + .encoder(CharSequenceEncoder.textPlainOnly()) + .decoder(StringDecoder.allMimeTypes()) + .build(); } } @@ -88,8 +91,10 @@ class RSocketMessagingAutoConfigurationTests { @Bean RSocketMessageHandler customMessageHandler() { RSocketMessageHandler messageHandler = new RSocketMessageHandler(); - RSocketStrategies strategies = RSocketStrategies.builder().encoder(CharSequenceEncoder.textPlainOnly()) - .decoder(StringDecoder.allMimeTypes()).build(); + RSocketStrategies strategies = RSocketStrategies.builder() + .encoder(CharSequenceEncoder.textPlainOnly()) + .decoder(StringDecoder.allMimeTypes()) + .build(); messageHandler.setRSocketStrategies(strategies); return messageHandler; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfigurationTests.java index 46971f1e49..d675d51286 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,12 +68,13 @@ class RSocketRequesterAutoConfigurationTests { RSocketConnectorConfigurer first = mock(RSocketConnectorConfigurer.class); RSocketConnectorConfigurer second = mock(RSocketConnectorConfigurer.class); this.contextRunner.withBean("first", RSocketConnectorConfigurer.class, () -> first) - .withBean("second", RSocketConnectorConfigurer.class, () -> second).run((context) -> { - assertThat(context).getBeans(RSocketConnectorConfigurer.class).hasSize(2); - RSocketRequester.Builder builder = context.getBean(RSocketRequester.Builder.class); - assertThat(builder).extracting("rsocketConnectorConfigurers", as(InstanceOfAssertFactories.LIST)) - .containsExactly(first, second); - }); + .withBean("second", RSocketConnectorConfigurer.class, () -> second) + .run((context) -> { + assertThat(context).getBeans(RSocketConnectorConfigurer.class).hasSize(2); + RSocketRequester.Builder builder = context.getBean(RSocketRequester.Builder.class); + assertThat(builder).extracting("rsocketConnectorConfigurers", as(InstanceOfAssertFactories.LIST)) + .containsExactly(first, second); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfigurationTests.java index 91bbe8a37d..ace10a95e7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,114 +50,121 @@ class RSocketServerAutoConfigurationTests { @Test void shouldNotCreateBeansByDefault() { contextRunner().run((context) -> assertThat(context).doesNotHaveBean(WebServerFactoryCustomizer.class) - .doesNotHaveBean(RSocketServerFactory.class).doesNotHaveBean(RSocketServerBootstrap.class)); + .doesNotHaveBean(RSocketServerFactory.class) + .doesNotHaveBean(RSocketServerBootstrap.class)); } @Test void shouldNotCreateDefaultBeansForReactiveWebAppWithoutMapping() { reactiveWebContextRunner() - .run((context) -> assertThat(context).doesNotHaveBean(WebServerFactoryCustomizer.class) - .doesNotHaveBean(RSocketServerFactory.class).doesNotHaveBean(RSocketServerBootstrap.class)); + .run((context) -> assertThat(context).doesNotHaveBean(WebServerFactoryCustomizer.class) + .doesNotHaveBean(RSocketServerFactory.class) + .doesNotHaveBean(RSocketServerBootstrap.class)); } @Test void shouldNotCreateDefaultBeansForReactiveWebAppWithWrongTransport() { reactiveWebContextRunner() - .withPropertyValues("spring.rsocket.server.transport=tcp", - "spring.rsocket.server.mapping-path=/rsocket") - .run((context) -> assertThat(context).doesNotHaveBean(WebServerFactoryCustomizer.class) - .doesNotHaveBean(RSocketServerFactory.class).doesNotHaveBean(RSocketServerBootstrap.class)); + .withPropertyValues("spring.rsocket.server.transport=tcp", "spring.rsocket.server.mapping-path=/rsocket") + .run((context) -> assertThat(context).doesNotHaveBean(WebServerFactoryCustomizer.class) + .doesNotHaveBean(RSocketServerFactory.class) + .doesNotHaveBean(RSocketServerBootstrap.class)); } @Test void shouldCreateDefaultBeansForReactiveWebApp() { reactiveWebContextRunner() - .withPropertyValues("spring.rsocket.server.transport=websocket", - "spring.rsocket.server.mapping-path=/rsocket") - .run((context) -> assertThat(context).hasSingleBean(RSocketWebSocketNettyRouteProvider.class)); + .withPropertyValues("spring.rsocket.server.transport=websocket", + "spring.rsocket.server.mapping-path=/rsocket") + .run((context) -> assertThat(context).hasSingleBean(RSocketWebSocketNettyRouteProvider.class)); } @Test void shouldCreateDefaultBeansForRSocketServerWhenPortIsSet() { reactiveWebContextRunner().withPropertyValues("spring.rsocket.server.port=0") - .run((context) -> assertThat(context).hasSingleBean(RSocketServerFactory.class) - .hasSingleBean(RSocketServerBootstrap.class).hasSingleBean(RSocketServerCustomizer.class)); + .run((context) -> assertThat(context).hasSingleBean(RSocketServerFactory.class) + .hasSingleBean(RSocketServerBootstrap.class) + .hasSingleBean(RSocketServerCustomizer.class)); } @Test void shouldSetLocalServerPortWhenRSocketServerPortIsSet() { reactiveWebContextRunner().withPropertyValues("spring.rsocket.server.port=0") - .withInitializer(new RSocketPortInfoApplicationContextInitializer()).run((context) -> { - assertThat(context).hasSingleBean(RSocketServerFactory.class) - .hasSingleBean(RSocketServerBootstrap.class).hasSingleBean(RSocketServerCustomizer.class); - assertThat(context.getEnvironment().getProperty("local.rsocket.server.port")).isNotNull(); - }); + .withInitializer(new RSocketPortInfoApplicationContextInitializer()) + .run((context) -> { + assertThat(context).hasSingleBean(RSocketServerFactory.class) + .hasSingleBean(RSocketServerBootstrap.class) + .hasSingleBean(RSocketServerCustomizer.class); + assertThat(context.getEnvironment().getProperty("local.rsocket.server.port")).isNotNull(); + }); } @Test void shouldSetFragmentWhenRSocketServerFragmentSizeIsSet() { reactiveWebContextRunner() - .withPropertyValues("spring.rsocket.server.port=0", "spring.rsocket.server.fragment-size=12KB") - .run((context) -> { - assertThat(context).hasSingleBean(RSocketServerFactory.class); - RSocketServerFactory factory = context.getBean(RSocketServerFactory.class); - assertThat(factory).hasFieldOrPropertyWithValue("fragmentSize", DataSize.ofKilobytes(12)); - }); + .withPropertyValues("spring.rsocket.server.port=0", "spring.rsocket.server.fragment-size=12KB") + .run((context) -> { + assertThat(context).hasSingleBean(RSocketServerFactory.class); + RSocketServerFactory factory = context.getBean(RSocketServerFactory.class); + assertThat(factory).hasFieldOrPropertyWithValue("fragmentSize", DataSize.ofKilobytes(12)); + }); } @Test void shouldFailToSetFragmentWhenRSocketServerFragmentSizeIsBelow64() { reactiveWebContextRunner() - .withPropertyValues("spring.rsocket.server.port=0", "spring.rsocket.server.fragment-size=60B") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasMessageContaining("The smallest allowed mtu size is 64 bytes, provided: 60"); - }); + .withPropertyValues("spring.rsocket.server.port=0", "spring.rsocket.server.fragment-size=60B") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasMessageContaining("The smallest allowed mtu size is 64 bytes, provided: 60"); + }); } @Test void shouldUseSslWhenRocketServerSslIsConfigured() { reactiveWebContextRunner() - .withPropertyValues("spring.rsocket.server.ssl.keyStore=classpath:rsocket/test.jks", - "spring.rsocket.server.ssl.keyPassword=password", "spring.rsocket.server.port=0") - .run((context) -> assertThat(context).hasSingleBean(RSocketServerFactory.class) - .hasSingleBean(RSocketServerBootstrap.class).hasSingleBean(RSocketServerCustomizer.class) - .getBean(RSocketServerFactory.class) - .hasFieldOrPropertyWithValue("ssl.keyStore", "classpath:rsocket/test.jks") - .hasFieldOrPropertyWithValue("ssl.keyPassword", "password")); + .withPropertyValues("spring.rsocket.server.ssl.keyStore=classpath:rsocket/test.jks", + "spring.rsocket.server.ssl.keyPassword=password", "spring.rsocket.server.port=0") + .run((context) -> assertThat(context).hasSingleBean(RSocketServerFactory.class) + .hasSingleBean(RSocketServerBootstrap.class) + .hasSingleBean(RSocketServerCustomizer.class) + .getBean(RSocketServerFactory.class) + .hasFieldOrPropertyWithValue("ssl.keyStore", "classpath:rsocket/test.jks") + .hasFieldOrPropertyWithValue("ssl.keyPassword", "password")); } @Test void shouldUseCustomServerBootstrap() { - contextRunner().withUserConfiguration(CustomServerBootstrapConfig.class).run((context) -> assertThat(context) - .getBeanNames(RSocketServerBootstrap.class).containsExactly("customServerBootstrap")); + contextRunner().withUserConfiguration(CustomServerBootstrapConfig.class) + .run((context) -> assertThat(context).getBeanNames(RSocketServerBootstrap.class) + .containsExactly("customServerBootstrap")); } @Test void shouldUseCustomNettyRouteProvider() { reactiveWebContextRunner().withUserConfiguration(CustomNettyRouteProviderConfig.class) - .withPropertyValues("spring.rsocket.server.transport=websocket", - "spring.rsocket.server.mapping-path=/rsocket") - .run((context) -> assertThat(context).getBeanNames(RSocketWebSocketNettyRouteProvider.class) - .containsExactly("customNettyRouteProvider")); + .withPropertyValues("spring.rsocket.server.transport=websocket", + "spring.rsocket.server.mapping-path=/rsocket") + .run((context) -> assertThat(context).getBeanNames(RSocketWebSocketNettyRouteProvider.class) + .containsExactly("customNettyRouteProvider")); } @Test void whenSpringWebIsNotPresentThenEmbeddedServerConfigurationBacksOff() { contextRunner().withClassLoader(new FilteredClassLoader(ReactorResourceFactory.class)) - .withPropertyValues("spring.rsocket.server.port=0") - .run((context) -> assertThat(context).doesNotHaveBean(RSocketServerFactory.class)); + .withPropertyValues("spring.rsocket.server.port=0") + .run((context) -> assertThat(context).doesNotHaveBean(RSocketServerFactory.class)); } private ApplicationContextRunner contextRunner() { return new ApplicationContextRunner().withUserConfiguration(BaseConfiguration.class) - .withConfiguration(AutoConfigurations.of(RSocketServerAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RSocketServerAutoConfiguration.class)); } private ReactiveWebApplicationContextRunner reactiveWebContextRunner() { return new ReactiveWebApplicationContextRunner().withUserConfiguration(BaseConfiguration.class) - .withConfiguration(AutoConfigurations.of(RSocketServerAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RSocketServerAutoConfiguration.class)); } @Configuration(proxyBeanMethods = false) @@ -166,8 +173,10 @@ class RSocketServerAutoConfigurationTests { @Bean RSocketMessageHandler messageHandler() { RSocketMessageHandler messageHandler = new RSocketMessageHandler(); - messageHandler.setRSocketStrategies(RSocketStrategies.builder().encoder(CharSequenceEncoder.textPlainOnly()) - .decoder(StringDecoder.allMimeTypes()).build()); + messageHandler.setRSocketStrategies(RSocketStrategies.builder() + .encoder(CharSequenceEncoder.textPlainOnly()) + .decoder(StringDecoder.allMimeTypes()) + .build()); return messageHandler; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfigurationTests.java index 3973470510..e2cb73b1a3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,9 +54,9 @@ class RSocketStrategiesAutoConfigurationTests { assertThat(context).getBeans(RSocketStrategies.class).hasSize(1); RSocketStrategies strategies = context.getBean(RSocketStrategies.class); assertThat(strategies.decoders()).hasAtLeastOneElementOfType(Jackson2CborDecoder.class) - .hasAtLeastOneElementOfType(Jackson2JsonDecoder.class); + .hasAtLeastOneElementOfType(Jackson2JsonDecoder.class); assertThat(strategies.encoders()).hasAtLeastOneElementOfType(Jackson2CborEncoder.class) - .hasAtLeastOneElementOfType(Jackson2JsonEncoder.class); + .hasAtLeastOneElementOfType(Jackson2JsonEncoder.class); assertThat(strategies.routeMatcher()).isInstanceOf(PathPatternRouteMatcher.class); }); } @@ -84,8 +84,10 @@ class RSocketStrategiesAutoConfigurationTests { @Bean RSocketStrategies customRSocketStrategies() { - return RSocketStrategies.builder().encoder(CharSequenceEncoder.textPlainOnly()) - .decoder(StringDecoder.textPlainOnly()).build(); + return RSocketStrategies.builder() + .encoder(CharSequenceEncoder.textPlainOnly()) + .decoder(StringDecoder.textPlainOnly()) + .build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProviderTests.java index e5272b4ef3..a16517fe97 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,38 +56,40 @@ class RSocketWebSocketNettyRouteProviderTests { @Test void webEndpointsShouldWork() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration( - AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, - ErrorWebFluxAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, - RSocketStrategiesAutoConfiguration.class, RSocketServerAutoConfiguration.class, - RSocketMessagingAutoConfiguration.class, RSocketRequesterAutoConfiguration.class)) - .withUserConfiguration(WebConfiguration.class) - .withPropertyValues("spring.rsocket.server.transport=websocket", - "spring.rsocket.server.mapping-path=/rsocket") - .run((context) -> { - ReactiveWebServerApplicationContext serverContext = (ReactiveWebServerApplicationContext) context - .getSourceApplicationContext(); - RSocketRequester requester = createRSocketRequester(context, serverContext.getWebServer()); - TestProtocol rsocketResponse = requester.route("websocket").data(new TestProtocol("rsocket")) - .retrieveMono(TestProtocol.class).block(Duration.ofSeconds(3)); - assertThat(rsocketResponse.getName()).isEqualTo("rsocket"); - WebTestClient client = createWebTestClient(serverContext.getWebServer()); - client.get().uri("/protocol").exchange().expectStatus().isOk().expectBody().jsonPath("name", - "http"); - }); + .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, + ErrorWebFluxAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, + RSocketStrategiesAutoConfiguration.class, RSocketServerAutoConfiguration.class, + RSocketMessagingAutoConfiguration.class, RSocketRequesterAutoConfiguration.class)) + .withUserConfiguration(WebConfiguration.class) + .withPropertyValues("spring.rsocket.server.transport=websocket", + "spring.rsocket.server.mapping-path=/rsocket") + .run((context) -> { + ReactiveWebServerApplicationContext serverContext = (ReactiveWebServerApplicationContext) context + .getSourceApplicationContext(); + RSocketRequester requester = createRSocketRequester(context, serverContext.getWebServer()); + TestProtocol rsocketResponse = requester.route("websocket") + .data(new TestProtocol("rsocket")) + .retrieveMono(TestProtocol.class) + .block(Duration.ofSeconds(3)); + assertThat(rsocketResponse.getName()).isEqualTo("rsocket"); + WebTestClient client = createWebTestClient(serverContext.getWebServer()); + client.get().uri("/protocol").exchange().expectStatus().isOk().expectBody().jsonPath("name", "http"); + }); } private WebTestClient createWebTestClient(WebServer server) { - return WebTestClient.bindToServer().baseUrl("http://localhost:" + server.getPort()) - .responseTimeout(Duration.ofMinutes(5)).build(); + return WebTestClient.bindToServer() + .baseUrl("http://localhost:" + server.getPort()) + .responseTimeout(Duration.ofMinutes(5)) + .build(); } private RSocketRequester createRSocketRequester(ApplicationContext context, WebServer server) { int port = server.getPort(); RSocketRequester.Builder builder = context.getBean(RSocketRequester.Builder.class); return builder.dataMimeType(MediaType.APPLICATION_CBOR) - .websocket(URI.create("ws://localhost:" + port + "/rsocket")); + .websocket(URI.create("ws://localhost:" + port + "/rsocket")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java index ec888e0c6e..cb629a67b9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,7 +71,7 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { properties.getRegistration().put("registration", registration); properties.getProvider().put("provider", provider); Map registrations = OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(properties); + .getClientRegistrations(properties); ClientRegistration adapted = registrations.get("registration"); ProviderDetails adaptedProvider = adapted.getProviderDetails(); assertThat(adaptedProvider.getAuthorizationUri()).isEqualTo("https://example.com/auth"); @@ -79,16 +79,16 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { UserInfoEndpoint userInfoEndpoint = adaptedProvider.getUserInfoEndpoint(); assertThat(userInfoEndpoint.getUri()).isEqualTo("https://example.com/info"); assertThat(userInfoEndpoint.getAuthenticationMethod()) - .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.FORM); + .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.FORM); assertThat(userInfoEndpoint.getUserNameAttributeName()).isEqualTo("sub"); assertThat(adaptedProvider.getJwkSetUri()).isEqualTo("https://example.com/jwk"); assertThat(adapted.getRegistrationId()).isEqualTo("registration"); assertThat(adapted.getClientId()).isEqualTo("clientId"); assertThat(adapted.getClientSecret()).isEqualTo("clientSecret"); assertThat(adapted.getClientAuthenticationMethod()) - .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_POST); + .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_POST); assertThat(adapted.getAuthorizationGrantType()) - .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); + .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); assertThat(adapted.getRedirectUri()).isEqualTo("https://example.com/redirect"); assertThat(adapted.getScopes()).containsExactly("user"); assertThat(adapted.getClientName()).isEqualTo("clientName"); @@ -103,7 +103,7 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { registration.setClientSecret("clientSecret"); properties.getRegistration().put("registration", registration); Map registrations = OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(properties); + .getClientRegistrations(properties); ClientRegistration adapted = registrations.get("registration"); ProviderDetails adaptedProvider = adapted.getProviderDetails(); assertThat(adaptedProvider.getAuthorizationUri()).isEqualTo("https://accounts.google.com/o/oauth2/v2/auth"); @@ -116,9 +116,9 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { assertThat(adapted.getClientId()).isEqualTo("clientId"); assertThat(adapted.getClientSecret()).isEqualTo("clientSecret"); assertThat(adapted.getClientAuthenticationMethod()) - .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_BASIC); + .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_BASIC); assertThat(adapted.getAuthorizationGrantType()) - .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); + .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); assertThat(adapted.getRedirectUri()).isEqualTo("{baseUrl}/{action}/oauth2/code/{registrationId}"); assertThat(adapted.getScopes()).containsExactly("openid", "profile", "email"); assertThat(adapted.getClientName()).isEqualTo("Google"); @@ -131,7 +131,7 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { registration.setClientName("clientName"); properties.getRegistration().put("registration", registration); Map registrations = OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(properties); + .getClientRegistrations(properties); ClientRegistration adapted = registrations.get("registration"); ProviderDetails adaptedProvider = adapted.getProviderDetails(); assertThat(adaptedProvider.getAuthorizationUri()).isEqualTo("https://accounts.google.com/o/oauth2/v2/auth"); @@ -140,15 +140,15 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { assertThat(userInfoEndpoint.getUri()).isEqualTo("https://www.googleapis.com/oauth2/v3/userinfo"); assertThat(userInfoEndpoint.getUserNameAttributeName()).isEqualTo(IdTokenClaimNames.SUB); assertThat(userInfoEndpoint.getAuthenticationMethod()) - .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.HEADER); + .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.HEADER); assertThat(adaptedProvider.getJwkSetUri()).isEqualTo("https://www.googleapis.com/oauth2/v3/certs"); assertThat(adapted.getRegistrationId()).isEqualTo("registration"); assertThat(adapted.getClientId()).isEqualTo("clientId"); assertThat(adapted.getClientSecret()).isEqualTo("clientSecret"); assertThat(adapted.getClientAuthenticationMethod()) - .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_POST); + .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_POST); assertThat(adapted.getAuthorizationGrantType()) - .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); + .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); assertThat(adapted.getRedirectUri()).isEqualTo("https://example.com/redirect"); assertThat(adapted.getScopes()).containsExactly("user"); assertThat(adapted.getClientName()).isEqualTo("clientName"); @@ -161,8 +161,8 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { registration.setProvider("missing"); properties.getRegistration().put("registration", registration); assertThatIllegalStateException() - .isThrownBy(() -> OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties)) - .withMessageContaining("Unknown provider ID 'missing'"); + .isThrownBy(() -> OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties)) + .withMessageContaining("Unknown provider ID 'missing'"); } @Test @@ -173,7 +173,7 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { registration.setClientSecret("clientSecret"); properties.getRegistration().put("google", registration); Map registrations = OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(properties); + .getClientRegistrations(properties); ClientRegistration adapted = registrations.get("google"); ProviderDetails adaptedProvider = adapted.getProviderDetails(); assertThat(adaptedProvider.getAuthorizationUri()).isEqualTo("https://accounts.google.com/o/oauth2/v2/auth"); @@ -181,15 +181,15 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { UserInfoEndpoint userInfoEndpoint = adaptedProvider.getUserInfoEndpoint(); assertThat(userInfoEndpoint.getUri()).isEqualTo("https://www.googleapis.com/oauth2/v3/userinfo"); assertThat(userInfoEndpoint.getAuthenticationMethod()) - .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.HEADER); + .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.HEADER); assertThat(adaptedProvider.getJwkSetUri()).isEqualTo("https://www.googleapis.com/oauth2/v3/certs"); assertThat(adapted.getRegistrationId()).isEqualTo("google"); assertThat(adapted.getClientId()).isEqualTo("clientId"); assertThat(adapted.getClientSecret()).isEqualTo("clientSecret"); assertThat(adapted.getClientAuthenticationMethod()) - .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_BASIC); + .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_BASIC); assertThat(adapted.getAuthorizationGrantType()) - .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); + .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); assertThat(adapted.getRedirectUri()).isEqualTo("{baseUrl}/{action}/oauth2/code/{registrationId}"); assertThat(adapted.getScopes()).containsExactly("openid", "profile", "email"); assertThat(adapted.getClientName()).isEqualTo("Google"); @@ -201,8 +201,8 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { OAuth2ClientProperties.Registration registration = new OAuth2ClientProperties.Registration(); properties.getRegistration().put("missing", registration); assertThatIllegalStateException() - .isThrownBy(() -> OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties)) - .withMessageContaining("Provider ID must be specified for client registration 'missing'"); + .isThrownBy(() -> OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties)) + .withMessageContaining("Provider ID must be specified for client registration 'missing'"); } @Test @@ -251,7 +251,7 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { properties.getProvider().put("okta-oidc", provider); properties.getRegistration().put("okta", registration); Map registrations = OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(properties); + .getClientRegistrations(properties); ClientRegistration adapted = registrations.get("okta"); ProviderDetails providerDetails = adapted.getProviderDetails(); assertThat(adapted.getClientAuthenticationMethod()).isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_POST); @@ -302,7 +302,7 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { properties.getProvider().put(providerId, provider); properties.getRegistration().put("okta", registration); Map registrations = OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(properties); + .getClientRegistrations(properties); ClientRegistration adapted = registrations.get("okta"); ProviderDetails providerDetails = adapted.getProviderDetails(); assertThat(adapted.getClientAuthenticationMethod()).isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC); @@ -316,14 +316,14 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { UserInfoEndpoint userInfoEndpoint = providerDetails.getUserInfoEndpoint(); assertThat(userInfoEndpoint.getUri()).isEqualTo("https://example.com/oauth2/v3/userinfo"); assertThat(userInfoEndpoint.getAuthenticationMethod()) - .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.HEADER); + .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.HEADER); assertThat(this.server.getRequestCount()).isEqualTo(numberOfRequests); } private void setupMockResponse(String issuer) throws JsonProcessingException { MockResponse mockResponse = new MockResponse().setResponseCode(HttpStatus.OK.value()) - .setBody(new ObjectMapper().writeValueAsString(getResponse(issuer))) - .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + .setBody(new ObjectMapper().writeValueAsString(getResponse(issuer))) + .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); this.server.enqueue(mockResponse); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesTests.java index 6b940ff5a3..ad121a4fca 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ class OAuth2ClientPropertiesTests { registration.setProvider("google"); this.properties.getRegistration().put("foo", registration); assertThatIllegalStateException().isThrownBy(this.properties::validate) - .withMessageContaining("Client id must not be empty."); + .withMessageContaining("Client id must not be empty."); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfigurationTests.java index 684d46f06c..270ac7029a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,16 +63,16 @@ import static org.assertj.core.api.Assertions.assertThat; class ReactiveOAuth2ClientAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class, - ReactiveSecurityAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class, + ReactiveSecurityAutoConfiguration.class)); private static final String REGISTRATION_PREFIX = "spring.security.oauth2.client.registration"; @Test void autoConfigurationShouldBackOffForServletEnvironments() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveOAuth2ClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveOAuth2ClientAutoConfiguration.class)); } @Test @@ -83,16 +83,15 @@ class ReactiveOAuth2ClientAutoConfigurationTests { @Test void clientRegistrationRepositoryBeanShouldBeCreatedWhenPropertiesPresent() { this.contextRunner - .withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd", - REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github") - .run((context) -> { - ReactiveClientRegistrationRepository repository = context - .getBean(ReactiveClientRegistrationRepository.class); - ClientRegistration registration = repository.findByRegistrationId("foo") - .block(Duration.ofSeconds(30)); - assertThat(registration).isNotNull(); - assertThat(registration.getClientSecret()).isEqualTo("secret"); - }); + .withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd", + REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github") + .run((context) -> { + ReactiveClientRegistrationRepository repository = context + .getBean(ReactiveClientRegistrationRepository.class); + ClientRegistration registration = repository.findByRegistrationId("foo").block(Duration.ofSeconds(30)); + assertThat(registration).isNotNull(); + assertThat(registration.getClientSecret()).isEqualTo("secret"); + }); } @Test @@ -114,50 +113,50 @@ class ReactiveOAuth2ClientAutoConfigurationTests { @Test void authorizedClientServiceBeanIsConditionalOnMissingBean() { this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientRepositoryConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveOAuth2AuthorizedClientService.class); - assertThat(context).hasBean("testAuthorizedClientService"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveOAuth2AuthorizedClientService.class); + assertThat(context).hasBean("testAuthorizedClientService"); + }); } @Test void authorizedClientRepositoryBeanIsConditionalOnAuthorizedClientService() { this.contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(ServerOAuth2AuthorizedClientRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ServerOAuth2AuthorizedClientRepository.class)); } @Test void configurationRegistersAuthorizedClientRepositoryBean() { this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientServiceConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository.class)); + .run((context) -> assertThat(context) + .hasSingleBean(AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository.class)); } @Test void authorizedClientRepositoryBeanIsConditionalOnMissingBean() { this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientRepositoryConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(ServerOAuth2AuthorizedClientRepository.class); - assertThat(context).hasBean("testAuthorizedClientRepository"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ServerOAuth2AuthorizedClientRepository.class); + assertThat(context).hasBean("testAuthorizedClientRepository"); + }); } @Test void securityWebFilterChainBeanConditionalOnWebApplication() { this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientRepositoryConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(SecurityWebFilterChain.class)); + .run((context) -> assertThat(context).doesNotHaveBean(SecurityWebFilterChain.class)); } @Test void configurationRegistersSecurityWebFilterChainBean() { // gh-17949 new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class)) - .withUserConfiguration(ReactiveOAuth2AuthorizedClientServiceConfiguration.class, - ServerHttpSecurityConfiguration.class) - .run((context) -> { - assertThat(hasFilter(context, OAuth2LoginAuthenticationWebFilter.class)).isTrue(); - assertThat(hasFilter(context, OAuth2AuthorizationCodeGrantWebFilter.class)).isTrue(); - }); + .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class)) + .withUserConfiguration(ReactiveOAuth2AuthorizedClientServiceConfiguration.class, + ServerHttpSecurityConfiguration.class) + .run((context) -> { + assertThat(hasFilter(context, OAuth2LoginAuthenticationWebFilter.class)).isTrue(); + assertThat(hasFilter(context, OAuth2AuthorizationCodeGrantWebFilter.class)).isTrue(); + }); } @Test @@ -178,15 +177,15 @@ class ReactiveOAuth2ClientAutoConfigurationTests { private void assertWhenClassNotPresent(Class classToFilter) { FilteredClassLoader classLoader = new FilteredClassLoader(classToFilter); this.contextRunner.withClassLoader(classLoader) - .withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd", - REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveOAuth2ClientAutoConfiguration.class)); + .withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd", + REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveOAuth2ClientAutoConfiguration.class)); } @SuppressWarnings("unchecked") private boolean hasFilter(AssertableReactiveWebApplicationContext context, Class filter) { SecurityWebFilterChain filterChain = (SecurityWebFilterChain) context - .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); + .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); List filters = (List) ReflectionTestUtils.getField(filterChain, "filters"); return filters.stream().anyMatch(filter::isInstance); } @@ -204,13 +203,18 @@ class ReactiveOAuth2ClientAutoConfigurationTests { private ClientRegistration getClientRegistration(String id, String userInfoUri) { ClientRegistration.Builder builder = ClientRegistration.withRegistrationId(id); - builder.clientName("foo").clientId("foo") - .clientAuthenticationMethod( - org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).scope("read") - .clientSecret("secret").redirectUri("https://redirect-uri.com") - .authorizationUri("https://authorization-uri.com").tokenUri("https://token-uri.com") - .userInfoUri(userInfoUri).userNameAttributeName("login"); + builder.clientName("foo") + .clientId("foo") + .clientAuthenticationMethod( + org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .scope("read") + .clientSecret("secret") + .redirectUri("https://redirect-uri.com") + .authorizationUri("https://authorization-uri.com") + .tokenUri("https://token-uri.com") + .userInfoUri(userInfoUri) + .userNameAttributeName("login"); return builder.build(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfigurationTests.java index ddaf275d2c..ba567dbc58 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,20 +38,20 @@ class OAuth2ClientRegistrationRepositoryConfigurationTests { @Test void clientRegistrationRepositoryBeanShouldNotBeCreatedWhenPropertiesAbsent() { this.contextRunner.withUserConfiguration(OAuth2ClientRegistrationRepositoryConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(ClientRegistrationRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ClientRegistrationRepository.class)); } @Test void clientRegistrationRepositoryBeanShouldBeCreatedWhenPropertiesPresent() { this.contextRunner.withUserConfiguration(OAuth2ClientRegistrationRepositoryConfiguration.class) - .withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd", - REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github") - .run((context) -> { - ClientRegistrationRepository repository = context.getBean(ClientRegistrationRepository.class); - ClientRegistration registration = repository.findByRegistrationId("foo"); - assertThat(registration).isNotNull(); - assertThat(registration.getClientSecret()).isEqualTo("secret"); - }); + .withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd", + REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github") + .run((context) -> { + ClientRegistrationRepository repository = context.getBean(ClientRegistrationRepository.class); + ClientRegistration registration = repository.findByRegistrationId("foo"); + assertThat(registration).isNotNull(); + assertThat(registration.getClientSecret()).isEqualTo("secret"); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfigurationTests.java index 390c2780c3..a3650bd87d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,108 +62,117 @@ class OAuth2WebSecurityConfigurationTests { @Test void securityConfigurerConfiguresOAuth2Login() { - this.contextRunner.withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, - OAuth2WebSecurityConfiguration.class).run((context) -> { - ClientRegistrationRepository expected = context.getBean(ClientRegistrationRepository.class); - ClientRegistrationRepository actual = (ClientRegistrationRepository) ReflectionTestUtils.getField( - getFilters(context, OAuth2LoginAuthenticationFilter.class).get(0), - "clientRegistrationRepository"); - assertThat(isEqual(expected.findByRegistrationId("first"), actual.findByRegistrationId("first"))) - .isTrue(); - assertThat(isEqual(expected.findByRegistrationId("second"), actual.findByRegistrationId("second"))) - .isTrue(); - }); + this.contextRunner + .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, + OAuth2WebSecurityConfiguration.class) + .run((context) -> { + ClientRegistrationRepository expected = context.getBean(ClientRegistrationRepository.class); + ClientRegistrationRepository actual = (ClientRegistrationRepository) ReflectionTestUtils.getField( + getFilters(context, OAuth2LoginAuthenticationFilter.class).get(0), + "clientRegistrationRepository"); + assertThat(isEqual(expected.findByRegistrationId("first"), actual.findByRegistrationId("first"))) + .isTrue(); + assertThat(isEqual(expected.findByRegistrationId("second"), actual.findByRegistrationId("second"))) + .isTrue(); + }); } @Test void securityConfigurerConfiguresAuthorizationCode() { - this.contextRunner.withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, - OAuth2WebSecurityConfiguration.class).run((context) -> { - ClientRegistrationRepository expected = context.getBean(ClientRegistrationRepository.class); - ClientRegistrationRepository actual = (ClientRegistrationRepository) ReflectionTestUtils.getField( - getFilters(context, OAuth2AuthorizationCodeGrantFilter.class).get(0), - "clientRegistrationRepository"); - assertThat(isEqual(expected.findByRegistrationId("first"), actual.findByRegistrationId("first"))) - .isTrue(); - assertThat(isEqual(expected.findByRegistrationId("second"), actual.findByRegistrationId("second"))) - .isTrue(); - }); + this.contextRunner + .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, + OAuth2WebSecurityConfiguration.class) + .run((context) -> { + ClientRegistrationRepository expected = context.getBean(ClientRegistrationRepository.class); + ClientRegistrationRepository actual = (ClientRegistrationRepository) ReflectionTestUtils.getField( + getFilters(context, OAuth2AuthorizationCodeGrantFilter.class).get(0), + "clientRegistrationRepository"); + assertThat(isEqual(expected.findByRegistrationId("first"), actual.findByRegistrationId("first"))) + .isTrue(); + assertThat(isEqual(expected.findByRegistrationId("second"), actual.findByRegistrationId("second"))) + .isTrue(); + }); } @Test void securityConfigurerBacksOffWhenClientRegistrationBeanAbsent() { this.contextRunner.withUserConfiguration(TestConfig.class, OAuth2WebSecurityConfiguration.class) - .run((context) -> { - assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)).isEmpty(); - assertThat(getFilters(context, OAuth2AuthorizationCodeGrantFilter.class)).isEmpty(); - }); + .run((context) -> { + assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)).isEmpty(); + assertThat(getFilters(context, OAuth2AuthorizationCodeGrantFilter.class)).isEmpty(); + }); } @Test void configurationRegistersAuthorizedClientServiceBean() { this.contextRunner - .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, - OAuth2WebSecurityConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(OAuth2AuthorizedClientService.class)); + .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, + OAuth2WebSecurityConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(OAuth2AuthorizedClientService.class)); } @Test void configurationRegistersAuthorizedClientRepositoryBean() { this.contextRunner - .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, - OAuth2WebSecurityConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(OAuth2AuthorizedClientRepository.class)); + .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, + OAuth2WebSecurityConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(OAuth2AuthorizedClientRepository.class)); } @Test void securityFilterChainConfigBacksOffWhenOtherWebSecurityAdapterPresent() { this.contextRunner - .withUserConfiguration(TestWebSecurityConfigurerConfig.class, OAuth2WebSecurityConfiguration.class) - .run((context) -> { - assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)).isEmpty(); - assertThat(getFilters(context, OAuth2AuthorizationCodeGrantFilter.class)).isEmpty(); - assertThat(context).getBean(OAuth2AuthorizedClientService.class).isNotNull(); - }); + .withUserConfiguration(TestWebSecurityConfigurerConfig.class, OAuth2WebSecurityConfiguration.class) + .run((context) -> { + assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)).isEmpty(); + assertThat(getFilters(context, OAuth2AuthorizationCodeGrantFilter.class)).isEmpty(); + assertThat(context).getBean(OAuth2AuthorizedClientService.class).isNotNull(); + }); } @Test void securityFilterChainConfigBacksOffWhenOtherSecurityFilterChainBeanPresent() { this.contextRunner - .withUserConfiguration(TestSecurityFilterChainConfig.class, OAuth2WebSecurityConfiguration.class) - .run((context) -> { - assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)).isEmpty(); - assertThat(getFilters(context, OAuth2AuthorizationCodeGrantFilter.class)).isEmpty(); - assertThat(context).getBean(OAuth2AuthorizedClientService.class).isNotNull(); - }); + .withUserConfiguration(TestSecurityFilterChainConfig.class, OAuth2WebSecurityConfiguration.class) + .run((context) -> { + assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)).isEmpty(); + assertThat(getFilters(context, OAuth2AuthorizationCodeGrantFilter.class)).isEmpty(); + assertThat(context).getBean(OAuth2AuthorizedClientService.class).isNotNull(); + }); } @Test void securityFilterChainConfigConditionalOnSecurityFilterChainClass() { this.contextRunner - .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, - OAuth2WebSecurityConfiguration.class) - .withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)).run((context) -> { - assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)).isEmpty(); - assertThat(getFilters(context, OAuth2AuthorizationCodeGrantFilter.class)).isEmpty(); - }); + .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, + OAuth2WebSecurityConfiguration.class) + .withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)) + .run((context) -> { + assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)).isEmpty(); + assertThat(getFilters(context, OAuth2AuthorizationCodeGrantFilter.class)).isEmpty(); + }); } @Test void authorizedClientServiceBeanIsConditionalOnMissingBean() { - this.contextRunner.withUserConfiguration(OAuth2AuthorizedClientServiceConfiguration.class, - OAuth2WebSecurityConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(OAuth2AuthorizedClientService.class); - assertThat(context).hasBean("testAuthorizedClientService"); - }); + this.contextRunner + .withUserConfiguration(OAuth2AuthorizedClientServiceConfiguration.class, + OAuth2WebSecurityConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(OAuth2AuthorizedClientService.class); + assertThat(context).hasBean("testAuthorizedClientService"); + }); } @Test void authorizedClientRepositoryBeanIsConditionalOnMissingBean() { - this.contextRunner.withUserConfiguration(OAuth2AuthorizedClientRepositoryConfiguration.class, - OAuth2WebSecurityConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(OAuth2AuthorizedClientRepository.class); - assertThat(context).hasBean("testAuthorizedClientRepository"); - }); + this.contextRunner + .withUserConfiguration(OAuth2AuthorizedClientRepositoryConfiguration.class, + OAuth2WebSecurityConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(OAuth2AuthorizedClientRepository.class); + assertThat(context).hasBean("testAuthorizedClientRepository"); + }); } private List getFilters(AssertableApplicationContext context, Class filter) { @@ -216,13 +225,18 @@ class OAuth2WebSecurityConfigurationTests { private ClientRegistration getClientRegistration(String id, String userInfoUri) { ClientRegistration.Builder builder = ClientRegistration.withRegistrationId(id); - builder.clientName("foo").clientId("foo") - .clientAuthenticationMethod( - org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).scope("read") - .clientSecret("secret").redirectUri("https://redirect-uri.com") - .authorizationUri("https://authorization-uri.com").tokenUri("https://token-uri.com") - .userInfoUri(userInfoUri).userNameAttributeName("login"); + builder.clientName("foo") + .clientId("foo") + .clientAuthenticationMethod( + org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .scope("read") + .clientSecret("secret") + .redirectUri("https://redirect-uri.com") + .authorizationUri("https://authorization-uri.com") + .tokenUri("https://token-uri.com") + .userInfoUri(userInfoUri) + .userNameAttributeName("login"); return builder.build(); } @@ -242,8 +256,9 @@ class OAuth2WebSecurityConfigurationTests { @Bean SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception { - return http.antMatcher("/**").authorizeRequests((authorize) -> authorize.anyRequest().authenticated()) - .build(); + return http.antMatcher("/**") + .authorizeRequests((authorize) -> authorize.anyRequest().authenticated()) + .build(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java index cb339cbd7d..0144f0295c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,8 +85,8 @@ import static org.mockito.Mockito.mock; class ReactiveOAuth2ResourceServerAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ResourceServerAutoConfiguration.class)) - .withUserConfiguration(TestConfig.class); + .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ResourceServerAutoConfiguration.class)) + .withUserConfiguration(TestConfig.class); private MockWebServer server; @@ -106,11 +106,11 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { @Test void autoConfigurationShouldConfigureResourceServer() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .run((context) -> { - assertThat(context).hasSingleBean(NimbusReactiveJwtDecoder.class); - assertFilterConfiguredWithJwtAuthenticationManager(context); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .run((context) -> { + assertThat(context).hasSingleBean(NimbusReactiveJwtDecoder.class); + assertFilterConfiguredWithJwtAuthenticationManager(context); + }); } @SuppressWarnings("unchecked") @@ -118,74 +118,80 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { @Deprecated void autoConfigurationUsingJwkSetUriShouldConfigureResourceServerUsingJwsAlgorithm() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.jwt.jws-algorithm=RS512") - .run((context) -> { - NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = context.getBean(NimbusReactiveJwtDecoder.class); - assertThat(nimbusReactiveJwtDecoder).extracting("jwtProcessor.arg$2.arg$1.jwsAlgs") - .matches((algorithms) -> ((Set) algorithms).contains(JWSAlgorithm.RS512)); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.jwt.jws-algorithm=RS512") + .run((context) -> { + NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = context.getBean(NimbusReactiveJwtDecoder.class); + assertThat(nimbusReactiveJwtDecoder).extracting("jwtProcessor.arg$2.arg$1.jwsAlgs") + .matches((algorithms) -> ((Set) algorithms).contains(JWSAlgorithm.RS512)); + }); } @Test void autoConfigurationUsingJwkSetUriShouldConfigureResourceServerUsingSingleJwsAlgorithm() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS512") - .run((context) -> { - NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = context.getBean(NimbusReactiveJwtDecoder.class); - assertThat(nimbusReactiveJwtDecoder).extracting("jwtProcessor.arg$2.arg$1.jwsAlgs") - .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) - .containsExactlyInAnyOrder(JWSAlgorithm.RS512); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS512") + .run((context) -> { + NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = context.getBean(NimbusReactiveJwtDecoder.class); + assertThat(nimbusReactiveJwtDecoder).extracting("jwtProcessor.arg$2.arg$1.jwsAlgs") + .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) + .containsExactlyInAnyOrder(JWSAlgorithm.RS512); + }); } @Test void autoConfigurationUsingJwkSetUriShouldConfigureResourceServerUsingMultipleJwsAlgorithms() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS256, RS384, RS512") - .run((context) -> { - NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = context.getBean(NimbusReactiveJwtDecoder.class); - assertThat(nimbusReactiveJwtDecoder).extracting("jwtProcessor.arg$2.arg$1.jwsAlgs") - .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) - .containsExactlyInAnyOrder(JWSAlgorithm.RS256, JWSAlgorithm.RS384, JWSAlgorithm.RS512); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS256, RS384, RS512") + .run((context) -> { + NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = context.getBean(NimbusReactiveJwtDecoder.class); + assertThat(nimbusReactiveJwtDecoder).extracting("jwtProcessor.arg$2.arg$1.jwsAlgs") + .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) + .containsExactlyInAnyOrder(JWSAlgorithm.RS256, JWSAlgorithm.RS384, JWSAlgorithm.RS512); + }); } @Test @Deprecated void autoConfigurationUsingPublicKeyValueShouldConfigureResourceServerUsingJwsAlgorithm() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", - "spring.security.oauth2.resourceserver.jwt.jws-algorithm=RS384").run((context) -> { - NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = context.getBean(NimbusReactiveJwtDecoder.class); - assertThat(nimbusReactiveJwtDecoder).extracting("jwtProcessor.arg$1.jwsKeySelector.expectedJWSAlg") - .isEqualTo(JWSAlgorithm.RS384); - }); + this.contextRunner + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", + "spring.security.oauth2.resourceserver.jwt.jws-algorithm=RS384") + .run((context) -> { + NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = context.getBean(NimbusReactiveJwtDecoder.class); + assertThat(nimbusReactiveJwtDecoder).extracting("jwtProcessor.arg$1.jwsKeySelector.expectedJWSAlg") + .isEqualTo(JWSAlgorithm.RS384); + }); } @Test void autoConfigurationUsingPublicKeyValueShouldConfigureResourceServerUsingSingleJwsAlgorithm() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", - "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS384").run((context) -> { - NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = context.getBean(NimbusReactiveJwtDecoder.class); - assertThat(nimbusReactiveJwtDecoder).extracting("jwtProcessor.arg$1.jwsKeySelector.expectedJWSAlg") - .isEqualTo(JWSAlgorithm.RS384); - }); + this.contextRunner + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", + "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS384") + .run((context) -> { + NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = context.getBean(NimbusReactiveJwtDecoder.class); + assertThat(nimbusReactiveJwtDecoder).extracting("jwtProcessor.arg$1.jwsKeySelector.expectedJWSAlg") + .isEqualTo(JWSAlgorithm.RS384); + }); } @Test void autoConfigurationUsingPublicKeyValueWithMultipleJwsAlgorithmsShouldFail() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", - "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RSA256,RS384").run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()).hasRootCauseMessage( - "Creating a JWT decoder using a public key requires exactly one JWS algorithm but 2 were " - + "configured"); - }); + this.contextRunner + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", + "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RSA256,RS384") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()).hasRootCauseMessage( + "Creating a JWT decoder using a public key requires exactly one JWS algorithm but 2 were " + + "configured"); + }); } @Test @@ -197,17 +203,19 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { String issuer = this.server.url(path).toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); - this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" - + this.server.getHostName() + ":" + this.server.getPort() + "/" + path).run((context) -> { - assertThat(context).hasSingleBean(SupplierReactiveJwtDecoder.class); - assertFilterConfiguredWithJwtAuthenticationManager(context); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); - SupplierReactiveJwtDecoder supplierReactiveJwtDecoder = context - .getBean(SupplierReactiveJwtDecoder.class); - Mono reactiveJwtDecoderSupplier = (Mono) ReflectionTestUtils - .getField(supplierReactiveJwtDecoder, "jwtDecoderMono"); - reactiveJwtDecoderSupplier.block(); - }); + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + + this.server.getHostName() + ":" + this.server.getPort() + "/" + path) + .run((context) -> { + assertThat(context).hasSingleBean(SupplierReactiveJwtDecoder.class); + assertFilterConfiguredWithJwtAuthenticationManager(context); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); + SupplierReactiveJwtDecoder supplierReactiveJwtDecoder = context + .getBean(SupplierReactiveJwtDecoder.class); + Mono reactiveJwtDecoderSupplier = (Mono) ReflectionTestUtils + .getField(supplierReactiveJwtDecoder, "jwtDecoderMono"); + reactiveJwtDecoderSupplier.block(); + }); // The last request is to the JWK Set endpoint to look up the algorithm assertThat(this.server.getRequestCount()).isEqualTo(1); } @@ -220,17 +228,19 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { String issuer = this.server.url("").toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponsesWithErrors(cleanIssuerPath, 1); - this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" - + this.server.getHostName() + ":" + this.server.getPort()).run((context) -> { - assertThat(context).hasSingleBean(SupplierReactiveJwtDecoder.class); - assertFilterConfiguredWithJwtAuthenticationManager(context); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); - SupplierReactiveJwtDecoder supplierReactiveJwtDecoder = context - .getBean(SupplierReactiveJwtDecoder.class); - Mono reactiveJwtDecoderSupplier = (Mono) ReflectionTestUtils - .getField(supplierReactiveJwtDecoder, "jwtDecoderMono"); - reactiveJwtDecoderSupplier.block(); - }); + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + + this.server.getHostName() + ":" + this.server.getPort()) + .run((context) -> { + assertThat(context).hasSingleBean(SupplierReactiveJwtDecoder.class); + assertFilterConfiguredWithJwtAuthenticationManager(context); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); + SupplierReactiveJwtDecoder supplierReactiveJwtDecoder = context + .getBean(SupplierReactiveJwtDecoder.class); + Mono reactiveJwtDecoderSupplier = (Mono) ReflectionTestUtils + .getField(supplierReactiveJwtDecoder, "jwtDecoderMono"); + reactiveJwtDecoderSupplier.block(); + }); // The last request is to the JWK Set endpoint to look up the algorithm assertThat(this.server.getRequestCount()).isEqualTo(2); } @@ -243,17 +253,19 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { String issuer = this.server.url("").toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponsesWithErrors(cleanIssuerPath, 2); - this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" - + this.server.getHostName() + ":" + this.server.getPort()).run((context) -> { - assertThat(context).hasSingleBean(SupplierReactiveJwtDecoder.class); - assertFilterConfiguredWithJwtAuthenticationManager(context); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); - SupplierReactiveJwtDecoder supplierReactiveJwtDecoder = context - .getBean(SupplierReactiveJwtDecoder.class); - Mono reactiveJwtDecoderSupplier = (Mono) ReflectionTestUtils - .getField(supplierReactiveJwtDecoder, "jwtDecoderMono"); - reactiveJwtDecoderSupplier.block(); - }); + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + + this.server.getHostName() + ":" + this.server.getPort()) + .run((context) -> { + assertThat(context).hasSingleBean(SupplierReactiveJwtDecoder.class); + assertFilterConfiguredWithJwtAuthenticationManager(context); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); + SupplierReactiveJwtDecoder supplierReactiveJwtDecoder = context + .getBean(SupplierReactiveJwtDecoder.class); + Mono reactiveJwtDecoderSupplier = (Mono) ReflectionTestUtils + .getField(supplierReactiveJwtDecoder, "jwtDecoderMono"); + reactiveJwtDecoderSupplier.block(); + }); // The last request is to the JWK Set endpoint to look up the algorithm assertThat(this.server.getRequestCount()).isEqualTo(3); } @@ -261,36 +273,37 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { @Test void autoConfigurationShouldConfigureResourceServerUsingPublicKeyValue() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") - .run((context) -> { - assertThat(context).hasSingleBean(NimbusReactiveJwtDecoder.class); - assertFilterConfiguredWithJwtAuthenticationManager(context); - }); + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") + .run((context) -> { + assertThat(context).hasSingleBean(NimbusReactiveJwtDecoder.class); + assertFilterConfiguredWithJwtAuthenticationManager(context); + }); } @Test void autoConfigurationShouldFailIfPublicKeyLocationDoesNotExist() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:does-not-exist") - .run((context) -> assertThat(context).hasFailed().getFailure() - .hasMessageContaining("class path resource [does-not-exist]") - .hasMessageContaining("Public key location does not exist")); + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:does-not-exist") + .run((context) -> assertThat(context).hasFailed() + .getFailure() + .hasMessageContaining("class path resource [does-not-exist]") + .hasMessageContaining("Public key location does not exist")); } @Test void autoConfigurationWhenSetUriKeyLocationIssuerUriPresentShouldUseSetUri() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", - "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") - .run((context) -> { - assertThat(context).hasSingleBean(NimbusReactiveJwtDecoder.class); - assertFilterConfiguredWithJwtAuthenticationManager(context); - assertThat(context.containsBean("jwtDecoder")).isTrue(); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isFalse(); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", + "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") + .run((context) -> { + assertThat(context).hasSingleBean(NimbusReactiveJwtDecoder.class); + assertFilterConfiguredWithJwtAuthenticationManager(context); + assertThat(context.containsBean("jwtDecoder")).isTrue(); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isFalse(); + }); } @Test @@ -301,15 +314,15 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" - + this.server.getPort(), - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") - .run((context) -> { - assertThat(context).hasSingleBean(SupplierReactiveJwtDecoder.class); - assertFilterConfiguredWithJwtAuthenticationManager(context); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); - }); + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" + + this.server.getPort(), + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") + .run((context) -> { + assertThat(context).hasSingleBean(SupplierReactiveJwtDecoder.class); + assertFilterConfiguredWithJwtAuthenticationManager(context); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); + }); } @Test @@ -320,105 +333,107 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { @Test void jwtDecoderBeanIsConditionalOnMissingBean() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(JwtDecoderConfig.class) - .run((this::assertFilterConfiguredWithJwtAuthenticationManager)); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(JwtDecoderConfig.class) + .run((this::assertFilterConfiguredWithJwtAuthenticationManager)); } @Test void jwtDecoderByIssuerUriBeanIsConditionalOnMissingBean() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") - .withUserConfiguration(JwtDecoderConfig.class) - .run((this::assertFilterConfiguredWithJwtAuthenticationManager)); + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") + .withUserConfiguration(JwtDecoderConfig.class) + .run((this::assertFilterConfiguredWithJwtAuthenticationManager)); } @Test void autoConfigurationShouldBeConditionalOnBearerTokenAuthenticationTokenClass() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(JwtDecoderConfig.class) - .withClassLoader(new FilteredClassLoader(BearerTokenAuthenticationToken.class)) - .run((context) -> assertThat(context).doesNotHaveBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(JwtDecoderConfig.class) + .withClassLoader(new FilteredClassLoader(BearerTokenAuthenticationToken.class)) + .run((context) -> assertThat(context).doesNotHaveBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)); } @Test void autoConfigurationShouldBeConditionalOnReactiveJwtDecoderClass() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(JwtDecoderConfig.class) - .withClassLoader(new FilteredClassLoader(ReactiveJwtDecoder.class)) - .run((context) -> assertThat(context).doesNotHaveBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(JwtDecoderConfig.class) + .withClassLoader(new FilteredClassLoader(ReactiveJwtDecoder.class)) + .run((context) -> assertThat(context).doesNotHaveBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)); } @Test void autoConfigurationWhenSecurityWebFilterChainConfigPresentShouldNotAddOne() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(SecurityWebFilterChainConfig.class).run((context) -> { - assertThat(context).hasSingleBean(SecurityWebFilterChain.class); - assertThat(context).hasBean("testSpringSecurityFilterChain"); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(SecurityWebFilterChainConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(SecurityWebFilterChain.class); + assertThat(context).hasBean("testSpringSecurityFilterChain"); + }); } @Test void autoConfigurationWhenIntrospectionUriAvailableShouldConfigureIntrospectionClient() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", - "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", - "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveOpaqueTokenIntrospector.class); - assertFilterConfiguredWithOpaqueTokenAuthenticationManager(context); - }); + .withPropertyValues( + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", + "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", + "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveOpaqueTokenIntrospector.class); + assertFilterConfiguredWithOpaqueTokenAuthenticationManager(context); + }); } @Test void autoConfigurationWhenJwkSetUriAndIntrospectionUriAvailable() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", - "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", - "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveOpaqueTokenIntrospector.class); - assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); - assertFilterConfiguredWithJwtAuthenticationManager(context); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", + "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", + "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveOpaqueTokenIntrospector.class); + assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); + assertFilterConfiguredWithJwtAuthenticationManager(context); + }); } @Test void opaqueTokenIntrospectorIsConditionalOnMissingBean() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com") - .withUserConfiguration(OpaqueTokenIntrospectorConfig.class) - .run((this::assertFilterConfiguredWithOpaqueTokenAuthenticationManager)); + .withPropertyValues( + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com") + .withUserConfiguration(OpaqueTokenIntrospectorConfig.class) + .run((this::assertFilterConfiguredWithOpaqueTokenAuthenticationManager)); } @Test void autoConfigurationForOpaqueTokenWhenSecurityWebFilterChainConfigPresentShouldNotAddOne() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", - "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", - "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") - .withUserConfiguration(SecurityWebFilterChainConfig.class).run((context) -> { - assertThat(context).hasSingleBean(SecurityWebFilterChain.class); - assertThat(context).hasBean("testSpringSecurityFilterChain"); - }); + .withPropertyValues( + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", + "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", + "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") + .withUserConfiguration(SecurityWebFilterChainConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(SecurityWebFilterChain.class); + assertThat(context).hasBean("testSpringSecurityFilterChain"); + }); } @Test void autoConfigurationWhenIntrospectionUriAvailableShouldBeConditionalOnClass() { this.contextRunner.withClassLoader(new FilteredClassLoader(BearerTokenAuthenticationToken.class)) - .withPropertyValues( - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", - "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", - "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveOpaqueTokenIntrospector.class)); + .withPropertyValues( + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", + "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", + "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveOpaqueTokenIntrospector.class)); } @SuppressWarnings("unchecked") @@ -431,18 +446,18 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" - + this.server.getPort() + "/" + path) - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); - ReactiveJwtDecoder reactiveJwtDecoder = context.getBean(ReactiveJwtDecoder.class); - DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils - .getField(reactiveJwtDecoder, "jwtValidator"); - Collection> tokenValidators = (Collection>) ReflectionTestUtils - .getField(jwtValidator, "tokenValidators"); - assertThat(tokenValidators).hasAtLeastOneElementOfType(JwtIssuerValidator.class); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" + + this.server.getPort() + "/" + path) + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); + ReactiveJwtDecoder reactiveJwtDecoder = context.getBean(ReactiveJwtDecoder.class); + DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils + .getField(reactiveJwtDecoder, "jwtValidator"); + Collection> tokenValidators = (Collection>) ReflectionTestUtils + .getField(jwtValidator, "tokenValidators"); + assertThat(tokenValidators).hasAtLeastOneElementOfType(JwtIssuerValidator.class); + }); } @SuppressWarnings("unchecked") @@ -455,18 +470,18 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); - ReactiveJwtDecoder reactiveJwtDecoder = context.getBean(ReactiveJwtDecoder.class); - DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils - .getField(reactiveJwtDecoder, "jwtValidator"); - Collection> tokenValidators = (Collection>) ReflectionTestUtils - .getField(jwtValidator, "tokenValidators"); - assertThat(tokenValidators).hasExactlyElementsOfTypes(JwtTimestampValidator.class); - assertThat(tokenValidators).doesNotHaveAnyElementsOfTypes(JwtClaimValidator.class); - assertThat(tokenValidators).doesNotHaveAnyElementsOfTypes(JwtIssuerValidator.class); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); + ReactiveJwtDecoder reactiveJwtDecoder = context.getBean(ReactiveJwtDecoder.class); + DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils + .getField(reactiveJwtDecoder, "jwtValidator"); + Collection> tokenValidators = (Collection>) ReflectionTestUtils + .getField(jwtValidator, "tokenValidators"); + assertThat(tokenValidators).hasExactlyElementsOfTypes(JwtTimestampValidator.class); + assertThat(tokenValidators).doesNotHaveAnyElementsOfTypes(JwtClaimValidator.class); + assertThat(tokenValidators).doesNotHaveAnyElementsOfTypes(JwtIssuerValidator.class); + }); } @Test @@ -482,17 +497,17 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", "spring.security.oauth2.resourceserver.jwt.issuer-uri=" + issuerUri, "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com") - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); - ReactiveJwtDecoder reactiveJwtDecoder = context.getBean(ReactiveJwtDecoder.class); - validate(issuerUri, reactiveJwtDecoder); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); + ReactiveJwtDecoder reactiveJwtDecoder = context.getBean(ReactiveJwtDecoder.class); + validate(issuerUri, reactiveJwtDecoder); + }); } @SuppressWarnings("unchecked") private void validate(String issuerUri, ReactiveJwtDecoder jwtDecoder) throws MalformedURLException { DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils - .getField(jwtDecoder, "jwtValidator"); + .getField(jwtDecoder, "jwtValidator"); Jwt.Builder builder = jwt().claim("aud", Collections.singletonList("https://test-audience.com")); if (issuerUri != null) { builder.claim("iss", new URL(issuerUri)); @@ -500,7 +515,7 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { Jwt jwt = builder.build(); assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse(); Collection> delegates = (Collection>) ReflectionTestUtils - .getField(jwtValidator, "tokenValidators"); + .getField(jwtValidator, "tokenValidators"); validateDelegates(issuerUri, delegates); } @@ -508,9 +523,11 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { private void validateDelegates(String issuerUri, Collection> delegates) { assertThat(delegates).hasAtLeastOneElementOfType(JwtClaimValidator.class); OAuth2TokenValidator delegatingValidator = delegates.stream() - .filter((v) -> v instanceof DelegatingOAuth2TokenValidator).findFirst().get(); + .filter((v) -> v instanceof DelegatingOAuth2TokenValidator) + .findFirst() + .get(); Collection> nestedDelegates = (Collection>) ReflectionTestUtils - .getField(delegatingValidator, "tokenValidators"); + .getField(delegatingValidator, "tokenValidators"); if (issuerUri != null) { assertThat(nestedDelegates).hasAtLeastOneElementOfType(JwtIssuerValidator.class); } @@ -528,14 +545,13 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { String issuerUri = "http://" + this.server.getHostName() + ":" + this.server.getPort() + "/" + path; this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=" + issuerUri, "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com") - .run((context) -> { - SupplierReactiveJwtDecoder supplierJwtDecoderBean = context - .getBean(SupplierReactiveJwtDecoder.class); - Mono jwtDecoderSupplier = (Mono) ReflectionTestUtils - .getField(supplierJwtDecoderBean, "jwtDecoderMono"); - ReactiveJwtDecoder jwtDecoder = jwtDecoderSupplier.block(); - validate(issuerUri, jwtDecoder); - }); + .run((context) -> { + SupplierReactiveJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierReactiveJwtDecoder.class); + Mono jwtDecoderSupplier = (Mono) ReflectionTestUtils + .getField(supplierJwtDecoderBean, "jwtDecoderMono"); + ReactiveJwtDecoder jwtDecoder = jwtDecoderSupplier.block(); + validate(issuerUri, jwtDecoder); + }); } @Test @@ -549,11 +565,11 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { this.contextRunner.withPropertyValues( "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com") - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); - ReactiveJwtDecoder jwtDecoder = context.getBean(ReactiveJwtDecoder.class); - validate(null, jwtDecoder); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); + ReactiveJwtDecoder jwtDecoder = context.getBean(ReactiveJwtDecoder.class); + validate(null, jwtDecoder); + }); } @SuppressWarnings("unchecked") @@ -570,25 +586,28 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", "spring.security.oauth2.resourceserver.jwt.issuer-uri=" + issuerUri, "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com") - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); - ReactiveJwtDecoder jwtDecoder = context.getBean(ReactiveJwtDecoder.class); - DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils - .getField(jwtDecoder, "jwtValidator"); - Jwt jwt = jwt().claim("iss", new URL(issuerUri)) - .claim("aud", Collections.singletonList("https://other-audience.com")).build(); - assertThat(jwtValidator.validate(jwt).hasErrors()).isTrue(); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); + ReactiveJwtDecoder jwtDecoder = context.getBean(ReactiveJwtDecoder.class); + DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils + .getField(jwtDecoder, "jwtValidator"); + Jwt jwt = jwt().claim("iss", new URL(issuerUri)) + .claim("aud", Collections.singletonList("https://other-audience.com")) + .build(); + assertThat(jwtValidator.validate(jwt).hasErrors()).isTrue(); + }); } private void assertFilterConfiguredWithJwtAuthenticationManager(AssertableReactiveWebApplicationContext context) { MatcherSecurityWebFilterChain filterChain = (MatcherSecurityWebFilterChain) context - .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); + .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); Stream filters = filterChain.getWebFilters().toStream(); AuthenticationWebFilter webFilter = (AuthenticationWebFilter) filters - .filter((f) -> f instanceof AuthenticationWebFilter).findFirst().orElse(null); + .filter((f) -> f instanceof AuthenticationWebFilter) + .findFirst() + .orElse(null); ReactiveAuthenticationManagerResolver authenticationManagerResolver = (ReactiveAuthenticationManagerResolver) ReflectionTestUtils - .getField(webFilter, "authenticationManagerResolver"); + .getField(webFilter, "authenticationManagerResolver"); Object authenticationManager = authenticationManagerResolver.resolve(null).block(); assertThat(authenticationManager).isInstanceOf(JwtReactiveAuthenticationManager.class); } @@ -596,12 +615,14 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { private void assertFilterConfiguredWithOpaqueTokenAuthenticationManager( AssertableReactiveWebApplicationContext context) { MatcherSecurityWebFilterChain filterChain = (MatcherSecurityWebFilterChain) context - .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); + .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); Stream filters = filterChain.getWebFilters().toStream(); AuthenticationWebFilter webFilter = (AuthenticationWebFilter) filters - .filter((f) -> f instanceof AuthenticationWebFilter).findFirst().orElse(null); + .filter((f) -> f instanceof AuthenticationWebFilter) + .findFirst() + .orElse(null); ReactiveAuthenticationManagerResolver authenticationManagerResolver = (ReactiveAuthenticationManagerResolver) ReflectionTestUtils - .getField(webFilter, "authenticationManagerResolver"); + .getField(webFilter, "authenticationManagerResolver"); Object authenticationManager = authenticationManagerResolver.resolve(null).block(); assertThat(authenticationManager).isInstanceOf(OpaqueTokenReactiveAuthenticationManager.class); } @@ -615,8 +636,8 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { private void setupMockResponse(String issuer) throws JsonProcessingException { MockResponse mockResponse = new MockResponse().setResponseCode(HttpStatus.OK.value()) - .setBody(new ObjectMapper().writeValueAsString(getResponse(issuer))) - .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + .setBody(new ObjectMapper().writeValueAsString(getResponse(issuer))) + .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); this.server.enqueue(mockResponse); this.server.enqueue( new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json").setBody(JWK_SET)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfigurationTests.java index efc7724bf5..7b1fb56a72 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -80,8 +80,8 @@ import static org.mockito.Mockito.mock; class OAuth2ResourceServerAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(OAuth2ResourceServerAutoConfiguration.class)) - .withUserConfiguration(TestConfig.class); + .withConfiguration(AutoConfigurations.of(OAuth2ResourceServerAutoConfiguration.class)) + .withUserConfiguration(TestConfig.class); private MockWebServer server; @@ -101,102 +101,108 @@ class OAuth2ResourceServerAutoConfigurationTests { @Test void autoConfigurationShouldConfigureResourceServer() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - assertThat(getBearerTokenFilter(context)).isNotNull(); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + assertThat(getBearerTokenFilter(context)).isNotNull(); + }); } @Test void autoConfigurationShouldMatchDefaultJwsAlgorithm() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .run((context) -> { - JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - assertThat(jwtDecoder).extracting("jwtProcessor.jwsKeySelector.jwsAlgs") - .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) - .containsExactlyInAnyOrder(JWSAlgorithm.RS256); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .run((context) -> { + JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); + assertThat(jwtDecoder).extracting("jwtProcessor.jwsKeySelector.jwsAlgs") + .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) + .containsExactlyInAnyOrder(JWSAlgorithm.RS256); + }); } @Test @Deprecated void autoConfigurationShouldConfigureResourceServerWithJwsAlgorithm() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.jwt.jws-algorithm=RS384") - .run((context) -> { - JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - Object processor = ReflectionTestUtils.getField(jwtDecoder, "jwtProcessor"); - Object keySelector = ReflectionTestUtils.getField(processor, "jwsKeySelector"); - assertThat(keySelector).hasFieldOrPropertyWithValue("jwsAlgs", - Collections.singleton(JWSAlgorithm.RS384)); - assertThat(getBearerTokenFilter(context)).isNotNull(); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.jwt.jws-algorithm=RS384") + .run((context) -> { + JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); + Object processor = ReflectionTestUtils.getField(jwtDecoder, "jwtProcessor"); + Object keySelector = ReflectionTestUtils.getField(processor, "jwsKeySelector"); + assertThat(keySelector).hasFieldOrPropertyWithValue("jwsAlgs", + Collections.singleton(JWSAlgorithm.RS384)); + assertThat(getBearerTokenFilter(context)).isNotNull(); + }); } @Test void autoConfigurationShouldConfigureResourceServerWithSingleJwsAlgorithm() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS384") - .run((context) -> { - JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - assertThat(jwtDecoder).extracting("jwtProcessor.jwsKeySelector.jwsAlgs") - .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) - .containsExactlyInAnyOrder(JWSAlgorithm.RS384); - assertThat(getBearerTokenFilter(context)).isNotNull(); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS384") + .run((context) -> { + JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); + assertThat(jwtDecoder).extracting("jwtProcessor.jwsKeySelector.jwsAlgs") + .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) + .containsExactlyInAnyOrder(JWSAlgorithm.RS384); + assertThat(getBearerTokenFilter(context)).isNotNull(); + }); } @Test void autoConfigurationShouldConfigureResourceServerWithMultipleJwsAlgorithms() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS256, RS384, RS512") - .run((context) -> { - JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - assertThat(jwtDecoder).extracting("jwtProcessor.jwsKeySelector.jwsAlgs") - .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) - .containsExactlyInAnyOrder(JWSAlgorithm.RS256, JWSAlgorithm.RS384, JWSAlgorithm.RS512); - assertThat(getBearerTokenFilter(context)).isNotNull(); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS256, RS384, RS512") + .run((context) -> { + JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); + assertThat(jwtDecoder).extracting("jwtProcessor.jwsKeySelector.jwsAlgs") + .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) + .containsExactlyInAnyOrder(JWSAlgorithm.RS256, JWSAlgorithm.RS384, JWSAlgorithm.RS512); + assertThat(getBearerTokenFilter(context)).isNotNull(); + }); } @Test @Deprecated void autoConfigurationUsingPublicKeyValueShouldConfigureResourceServerUsingJwsAlgorithm() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", - "spring.security.oauth2.resourceserver.jwt.jws-algorithm=RS384").run((context) -> { - NimbusJwtDecoder nimbusJwtDecoder = context.getBean(NimbusJwtDecoder.class); - assertThat(nimbusJwtDecoder).extracting("jwtProcessor.jwsKeySelector.expectedJWSAlg") - .isEqualTo(JWSAlgorithm.RS384); - }); + this.contextRunner + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", + "spring.security.oauth2.resourceserver.jwt.jws-algorithm=RS384") + .run((context) -> { + NimbusJwtDecoder nimbusJwtDecoder = context.getBean(NimbusJwtDecoder.class); + assertThat(nimbusJwtDecoder).extracting("jwtProcessor.jwsKeySelector.expectedJWSAlg") + .isEqualTo(JWSAlgorithm.RS384); + }); } @Test void autoConfigurationUsingPublicKeyValueShouldConfigureResourceServerUsingSingleJwsAlgorithm() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", - "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS384").run((context) -> { - NimbusJwtDecoder nimbusJwtDecoder = context.getBean(NimbusJwtDecoder.class); - assertThat(nimbusJwtDecoder).extracting("jwtProcessor.jwsKeySelector.expectedJWSAlg") - .isEqualTo(JWSAlgorithm.RS384); - }); + this.contextRunner + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", + "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS384") + .run((context) -> { + NimbusJwtDecoder nimbusJwtDecoder = context.getBean(NimbusJwtDecoder.class); + assertThat(nimbusJwtDecoder).extracting("jwtProcessor.jwsKeySelector.expectedJWSAlg") + .isEqualTo(JWSAlgorithm.RS384); + }); } @Test void autoConfigurationUsingPublicKeyValueWithMultipleJwsAlgorithmsShouldFail() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", - "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RSA256,RS384").run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()).hasRootCauseMessage( - "Creating a JWT decoder using a public key requires exactly one JWS algorithm but 2 were " - + "configured"); - }); + this.contextRunner + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", + "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RSA256,RS384") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()).hasRootCauseMessage( + "Creating a JWT decoder using a public key requires exactly one JWS algorithm but 2 were " + + "configured"); + }); } @Test @@ -208,15 +214,17 @@ class OAuth2ResourceServerAutoConfigurationTests { String issuer = this.server.url(path).toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); - this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" - + this.server.getHostName() + ":" + this.server.getPort() + "/" + path).run((context) -> { - assertThat(context).hasSingleBean(SupplierJwtDecoder.class); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); - SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); - Supplier jwtDecoderSupplier = (Supplier) ReflectionTestUtils - .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); - jwtDecoderSupplier.get(); - }); + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + + this.server.getHostName() + ":" + this.server.getPort() + "/" + path) + .run((context) -> { + assertThat(context).hasSingleBean(SupplierJwtDecoder.class); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); + SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); + Supplier jwtDecoderSupplier = (Supplier) ReflectionTestUtils + .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); + jwtDecoderSupplier.get(); + }); // The last request is to the JWK Set endpoint to look up the algorithm assertThat(this.server.getRequestCount()).isEqualTo(2); } @@ -230,15 +238,17 @@ class OAuth2ResourceServerAutoConfigurationTests { String issuer = this.server.url(path).toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponsesWithErrors(cleanIssuerPath, 1); - this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" - + this.server.getHostName() + ":" + this.server.getPort() + "/" + path).run((context) -> { - assertThat(context).hasSingleBean(SupplierJwtDecoder.class); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); - SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); - Supplier jwtDecoderSupplier = (Supplier) ReflectionTestUtils - .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); - jwtDecoderSupplier.get(); - }); + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + + this.server.getHostName() + ":" + this.server.getPort() + "/" + path) + .run((context) -> { + assertThat(context).hasSingleBean(SupplierJwtDecoder.class); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); + SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); + Supplier jwtDecoderSupplier = (Supplier) ReflectionTestUtils + .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); + jwtDecoderSupplier.get(); + }); // The last request is to the JWK Set endpoint to look up the algorithm assertThat(this.server.getRequestCount()).isEqualTo(3); } @@ -253,15 +263,17 @@ class OAuth2ResourceServerAutoConfigurationTests { String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponsesWithErrors(cleanIssuerPath, 2); - this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" - + this.server.getHostName() + ":" + this.server.getPort() + "/" + path).run((context) -> { - assertThat(context).hasSingleBean(SupplierJwtDecoder.class); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); - SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); - Supplier jwtDecoderSupplier = (Supplier) ReflectionTestUtils - .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); - jwtDecoderSupplier.get(); - }); + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + + this.server.getHostName() + ":" + this.server.getPort() + "/" + path) + .run((context) -> { + assertThat(context).hasSingleBean(SupplierJwtDecoder.class); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); + SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); + Supplier jwtDecoderSupplier = (Supplier) ReflectionTestUtils + .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); + jwtDecoderSupplier.get(); + }); // The last request is to the JWK Set endpoint to look up the algorithm assertThat(this.server.getRequestCount()).isEqualTo(4); } @@ -274,46 +286,48 @@ class OAuth2ResourceServerAutoConfigurationTests { String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - assertThat(getBearerTokenFilter(context)).isNotNull(); - }); + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") + .run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + assertThat(getBearerTokenFilter(context)).isNotNull(); + }); } @Test void autoConfigurationShouldFailIfPublicKeyLocationDoesNotExist() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:does-not-exist") - .run((context) -> assertThat(context).hasFailed().getFailure() - .hasMessageContaining("class path resource [does-not-exist]") - .hasMessageContaining("Public key location does not exist")); + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:does-not-exist") + .run((context) -> assertThat(context).hasFailed() + .getFailure() + .hasMessageContaining("class path resource [does-not-exist]") + .hasMessageContaining("Public key location does not exist")); } @Test void autoConfigurationShouldFailIfAlgorithmIsInvalid() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", - "spring.security.oauth2.resourceserver.jwt.jws-algorithms=NOT_VALID") - .run((context) -> assertThat(context).hasFailed().getFailure() - .hasMessageContaining("signatureAlgorithm cannot be null")); + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", + "spring.security.oauth2.resourceserver.jwt.jws-algorithms=NOT_VALID") + .run((context) -> assertThat(context).hasFailed() + .getFailure() + .hasMessageContaining("signatureAlgorithm cannot be null")); } @Test void autoConfigurationWhenSetUriKeyLocationAndIssuerUriPresentShouldUseSetUri() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=https://issuer-uri.com", - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", - "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - assertThat(getBearerTokenFilter(context)).isNotNull(); - assertThat(context.containsBean("jwtDecoderByJwkKeySetUri")).isTrue(); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isFalse(); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=https://issuer-uri.com", + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", + "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + assertThat(getBearerTokenFilter(context)).isNotNull(); + assertThat(context.containsBean("jwtDecoderByJwkKeySetUri")).isTrue(); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isFalse(); + }); } @Test @@ -324,15 +338,15 @@ class OAuth2ResourceServerAutoConfigurationTests { String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" - + this.server.getPort(), - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - assertThat(getBearerTokenFilter(context)).isNotNull(); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); - }); + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" + + this.server.getPort(), + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") + .run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + assertThat(getBearerTokenFilter(context)).isNotNull(); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); + }); } @Test @@ -343,112 +357,116 @@ class OAuth2ResourceServerAutoConfigurationTests { @Test void jwtDecoderByJwkSetUriIsConditionalOnMissingBean() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(JwtDecoderConfig.class) - .run((context) -> assertThat(getBearerTokenFilter(context)).isNotNull()); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(JwtDecoderConfig.class) + .run((context) -> assertThat(getBearerTokenFilter(context)).isNotNull()); } @Test void jwtDecoderByOidcIssuerUriIsConditionalOnMissingBean() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") - .withUserConfiguration(JwtDecoderConfig.class) - .run((context) -> assertThat(getBearerTokenFilter(context)).isNotNull()); + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") + .withUserConfiguration(JwtDecoderConfig.class) + .run((context) -> assertThat(getBearerTokenFilter(context)).isNotNull()); } @Test void autoConfigurationShouldBeConditionalOnResourceServerClass() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(JwtDecoderConfig.class) - .withClassLoader(new FilteredClassLoader(BearerTokenAuthenticationToken.class)).run((context) -> { - assertThat(context).doesNotHaveBean(OAuth2ResourceServerAutoConfiguration.class); - assertThat(getBearerTokenFilter(context)).isNull(); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(JwtDecoderConfig.class) + .withClassLoader(new FilteredClassLoader(BearerTokenAuthenticationToken.class)) + .run((context) -> { + assertThat(context).doesNotHaveBean(OAuth2ResourceServerAutoConfiguration.class); + assertThat(getBearerTokenFilter(context)).isNull(); + }); } @Test void autoConfigurationForJwtShouldBeConditionalOnJwtDecoderClass() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(JwtDecoderConfig.class) - .withClassLoader(new FilteredClassLoader(JwtDecoder.class)).run((context) -> { - assertThat(context).hasSingleBean(OAuth2ResourceServerAutoConfiguration.class); - assertThat(getBearerTokenFilter(context)).isNull(); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(JwtDecoderConfig.class) + .withClassLoader(new FilteredClassLoader(JwtDecoder.class)) + .run((context) -> { + assertThat(context).hasSingleBean(OAuth2ResourceServerAutoConfiguration.class); + assertThat(getBearerTokenFilter(context)).isNull(); + }); } @Test void jwtSecurityFilterShouldBeConditionalOnSecurityFilterChainClass() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(JwtDecoderConfig.class) - .withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)).run((context) -> { - assertThat(context).hasSingleBean(OAuth2ResourceServerAutoConfiguration.class); - assertThat(getBearerTokenFilter(context)).isNull(); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(JwtDecoderConfig.class) + .withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)) + .run((context) -> { + assertThat(context).hasSingleBean(OAuth2ResourceServerAutoConfiguration.class); + assertThat(getBearerTokenFilter(context)).isNull(); + }); } @Test void opaqueTokenSecurityFilterShouldBeConditionalOnSecurityFilterChainClass() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", - "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", - "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") - .withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)).run((context) -> { - assertThat(context).hasSingleBean(OAuth2ResourceServerAutoConfiguration.class); - assertThat(getBearerTokenFilter(context)).isNull(); - }); + .withPropertyValues( + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", + "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", + "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") + .withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)) + .run((context) -> { + assertThat(context).hasSingleBean(OAuth2ResourceServerAutoConfiguration.class); + assertThat(getBearerTokenFilter(context)).isNull(); + }); } @Test void autoConfigurationWhenJwkSetUriAndIntrospectionUriAvailable() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", - "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", - "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") - .run((context) -> { - assertThat(context).hasSingleBean(OpaqueTokenIntrospector.class); - assertThat(context).hasSingleBean(JwtDecoder.class); - assertThat(getBearerTokenFilter(context)) - .extracting("authenticationManagerResolver.arg$1.providers").asList() - .hasAtLeastOneElementOfType(JwtAuthenticationProvider.class); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", + "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", + "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") + .run((context) -> { + assertThat(context).hasSingleBean(OpaqueTokenIntrospector.class); + assertThat(context).hasSingleBean(JwtDecoder.class); + assertThat(getBearerTokenFilter(context)).extracting("authenticationManagerResolver.arg$1.providers") + .asList() + .hasAtLeastOneElementOfType(JwtAuthenticationProvider.class); + }); } @Test void autoConfigurationWhenIntrospectionUriAvailableShouldConfigureIntrospectionClient() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", - "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", - "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") - .run((context) -> { - assertThat(context).hasSingleBean(OpaqueTokenIntrospector.class); - assertThat(getBearerTokenFilter(context)).isNotNull(); - }); + .withPropertyValues( + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", + "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", + "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") + .run((context) -> { + assertThat(context).hasSingleBean(OpaqueTokenIntrospector.class); + assertThat(getBearerTokenFilter(context)).isNotNull(); + }); } @Test void opaqueTokenIntrospectorIsConditionalOnMissingBean() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com") - .withUserConfiguration(OpaqueTokenIntrospectorConfig.class) - .run((context) -> assertThat(getBearerTokenFilter(context)).isNotNull()); + .withPropertyValues( + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com") + .withUserConfiguration(OpaqueTokenIntrospectorConfig.class) + .run((context) -> assertThat(getBearerTokenFilter(context)).isNotNull()); } @Test void autoConfigurationWhenIntrospectionUriAvailableShouldBeConditionalOnClass() { this.contextRunner.withClassLoader(new FilteredClassLoader(BearerTokenAuthenticationToken.class)) - .withPropertyValues( - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", - "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", - "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") - .run((context) -> assertThat(context).doesNotHaveBean(OpaqueTokenIntrospector.class)); + .withPropertyValues( + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", + "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", + "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") + .run((context) -> assertThat(context).doesNotHaveBean(OpaqueTokenIntrospector.class)); } @SuppressWarnings("unchecked") @@ -461,16 +479,16 @@ class OAuth2ResourceServerAutoConfigurationTests { String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" - + this.server.getPort() + "/" + path) - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - assertThat(jwtDecoder).extracting("jwtValidator.tokenValidators") - .asInstanceOf(InstanceOfAssertFactories.collection(OAuth2TokenValidator.class)) - .hasAtLeastOneElementOfType(JwtIssuerValidator.class); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" + + this.server.getPort() + "/" + path) + .run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); + assertThat(jwtDecoder).extracting("jwtValidator.tokenValidators") + .asInstanceOf(InstanceOfAssertFactories.collection(OAuth2TokenValidator.class)) + .hasAtLeastOneElementOfType(JwtIssuerValidator.class); + }); } @SuppressWarnings("unchecked") @@ -483,16 +501,16 @@ class OAuth2ResourceServerAutoConfigurationTests { String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - assertThat(jwtDecoder).extracting("jwtValidator.tokenValidators") - .asInstanceOf(InstanceOfAssertFactories.collection(OAuth2TokenValidator.class)) - .hasExactlyElementsOfTypes(JwtTimestampValidator.class) - .doesNotHaveAnyElementsOfTypes(JwtClaimValidator.class) - .doesNotHaveAnyElementsOfTypes(JwtIssuerValidator.class); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); + assertThat(jwtDecoder).extracting("jwtValidator.tokenValidators") + .asInstanceOf(InstanceOfAssertFactories.collection(OAuth2TokenValidator.class)) + .hasExactlyElementsOfTypes(JwtTimestampValidator.class) + .doesNotHaveAnyElementsOfTypes(JwtClaimValidator.class) + .doesNotHaveAnyElementsOfTypes(JwtIssuerValidator.class); + }); } @Test @@ -508,11 +526,11 @@ class OAuth2ResourceServerAutoConfigurationTests { "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", "spring.security.oauth2.resourceserver.jwt.issuer-uri=" + issuerUri, "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com") - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - validate(issuerUri, jwtDecoder); - }); + .run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); + validate(issuerUri, jwtDecoder); + }); } @SuppressWarnings("unchecked") @@ -527,19 +545,19 @@ class OAuth2ResourceServerAutoConfigurationTests { String issuerUri = "http://" + this.server.getHostName() + ":" + this.server.getPort() + "/" + path; this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=" + issuerUri, "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com") - .run((context) -> { - SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); - Supplier jwtDecoderSupplier = (Supplier) ReflectionTestUtils - .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); - JwtDecoder jwtDecoder = jwtDecoderSupplier.get(); - validate(issuerUri, jwtDecoder); - }); + .run((context) -> { + SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); + Supplier jwtDecoderSupplier = (Supplier) ReflectionTestUtils + .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); + JwtDecoder jwtDecoder = jwtDecoderSupplier.get(); + validate(issuerUri, jwtDecoder); + }); } @SuppressWarnings("unchecked") private void validate(String issuerUri, JwtDecoder jwtDecoder) throws MalformedURLException { DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils - .getField(jwtDecoder, "jwtValidator"); + .getField(jwtDecoder, "jwtValidator"); Jwt.Builder builder = jwt().claim("aud", Collections.singletonList("https://test-audience.com")); if (issuerUri != null) { builder.claim("iss", new URL(issuerUri)); @@ -547,7 +565,7 @@ class OAuth2ResourceServerAutoConfigurationTests { Jwt jwt = builder.build(); assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse(); Collection> delegates = (Collection>) ReflectionTestUtils - .getField(jwtValidator, "tokenValidators"); + .getField(jwtValidator, "tokenValidators"); validateDelegates(issuerUri, delegates); } @@ -555,11 +573,13 @@ class OAuth2ResourceServerAutoConfigurationTests { private void validateDelegates(String issuerUri, Collection> delegates) { assertThat(delegates).hasAtLeastOneElementOfType(JwtClaimValidator.class); OAuth2TokenValidator delegatingValidator = delegates.stream() - .filter((v) -> v instanceof DelegatingOAuth2TokenValidator).findFirst().get(); + .filter((v) -> v instanceof DelegatingOAuth2TokenValidator) + .findFirst() + .get(); if (issuerUri != null) { assertThat(delegatingValidator).extracting("tokenValidators") - .asInstanceOf(InstanceOfAssertFactories.collection(OAuth2TokenValidator.class)) - .hasAtLeastOneElementOfType(JwtIssuerValidator.class); + .asInstanceOf(InstanceOfAssertFactories.collection(OAuth2TokenValidator.class)) + .hasAtLeastOneElementOfType(JwtIssuerValidator.class); } } @@ -574,11 +594,11 @@ class OAuth2ResourceServerAutoConfigurationTests { this.contextRunner.withPropertyValues( "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,http://test-audience1.com") - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - validate(null, jwtDecoder); - }); + .run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); + validate(null, jwtDecoder); + }); } @SuppressWarnings("unchecked") @@ -595,33 +615,34 @@ class OAuth2ResourceServerAutoConfigurationTests { "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", "spring.security.oauth2.resourceserver.jwt.issuer-uri=" + issuerUri, "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com") - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils - .getField(jwtDecoder, "jwtValidator"); - Jwt jwt = jwt().claim("iss", new URL(issuerUri)) - .claim("aud", Collections.singletonList("https://other-audience.com")).build(); - assertThat(jwtValidator.validate(jwt).hasErrors()).isTrue(); - }); + .run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); + DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils + .getField(jwtDecoder, "jwtValidator"); + Jwt jwt = jwt().claim("iss", new URL(issuerUri)) + .claim("aud", Collections.singletonList("https://other-audience.com")) + .build(); + assertThat(jwtValidator.validate(jwt).hasErrors()).isTrue(); + }); } @Test void jwtSecurityConfigurerBacksOffWhenSecurityFilterChainBeanIsPresent() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(JwtDecoderConfig.class, TestSecurityFilterChainConfig.class) - .run((context) -> assertThat(context).hasSingleBean(SecurityFilterChain.class)); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(JwtDecoderConfig.class, TestSecurityFilterChainConfig.class) + .run((context) -> assertThat(context).hasSingleBean(SecurityFilterChain.class)); } @Test void opaqueTokenSecurityConfigurerBacksOffWhenSecurityFilterChainBeanIsPresent() { this.contextRunner.withUserConfiguration(TestSecurityFilterChainConfig.class) - .withPropertyValues( - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", - "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", - "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") - .run((context) -> assertThat(context).hasSingleBean(SecurityFilterChain.class)); + .withPropertyValues( + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", + "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", + "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") + .run((context) -> assertThat(context).hasSingleBean(SecurityFilterChain.class)); } private Filter getBearerTokenFilter(AssertableWebApplicationContext context) { @@ -640,8 +661,8 @@ class OAuth2ResourceServerAutoConfigurationTests { private void setupMockResponse(String issuer) throws JsonProcessingException { MockResponse mockResponse = new MockResponse().setResponseCode(HttpStatus.OK.value()) - .setBody(new ObjectMapper().writeValueAsString(getResponse(issuer))) - .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + .setBody(new ObjectMapper().writeValueAsString(getResponse(issuer))) + .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); this.server.enqueue(mockResponse); this.server.enqueue( new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json").setBody(JWK_SET)); @@ -721,8 +742,9 @@ class OAuth2ResourceServerAutoConfigurationTests { @Bean SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception { - return http.antMatcher("/**").authorizeRequests((authorize) -> authorize.anyRequest().authenticated()) - .build(); + return http.antMatcher("/**") + .authorizeRequests((authorize) -> authorize.anyRequest().authenticated()) + .build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfigurationTests.java index 59ce29e815..4436ab7360 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,26 +43,26 @@ class ReactiveSecurityAutoConfigurationTests { @Test void backsOffWhenWebFilterChainProxyBeanPresent() { this.contextRunner.withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class)) - .withUserConfiguration(WebFilterChainProxyConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(WebFilterChainProxy.class)); + .withUserConfiguration(WebFilterChainProxyConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(WebFilterChainProxy.class)); } @Test void enablesWebFluxSecurity() { this.contextRunner - .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, - ReactiveUserDetailsServiceAutoConfiguration.class)) - .run((context) -> assertThat(context).getBean(WebFilterChainProxy.class).isNotNull()); + .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, + ReactiveUserDetailsServiceAutoConfiguration.class)) + .run((context) -> assertThat(context).getBean(WebFilterChainProxy.class).isNotNull()); } @Test void autoConfigurationIsConditionalOnClass() { this.contextRunner - .withClassLoader(new FilteredClassLoader(Flux.class, EnableWebFluxSecurity.class, - WebFilterChainProxy.class, WebFluxConfigurer.class)) - .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, - ReactiveUserDetailsServiceAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(WebFilterChainProxy.class)); + .withClassLoader(new FilteredClassLoader(Flux.class, EnableWebFluxSecurity.class, WebFilterChainProxy.class, + WebFluxConfigurer.class)) + .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, + ReactiveUserDetailsServiceAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(WebFilterChainProxy.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java index 50eea54462..07d01d4113 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ import static org.mockito.Mockito.mock; class ReactiveUserDetailsServiceAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveUserDetailsServiceAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveUserDetailsServiceAutoConfiguration.class)); @Test void configuresADefaultUser() { @@ -66,12 +66,13 @@ class ReactiveUserDetailsServiceAutoConfigurationTests { @Test void userDetailsServiceWhenRSocketConfigured() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveUserDetailsServiceAutoConfiguration.class, - RSocketMessagingAutoConfiguration.class, RSocketStrategiesAutoConfiguration.class)) - .withUserConfiguration(TestRSocketSecurityConfiguration.class).run((context) -> { - ReactiveUserDetailsService userDetailsService = context.getBean(ReactiveUserDetailsService.class); - assertThat(userDetailsService.findByUsername("user").block(Duration.ofSeconds(30))).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(ReactiveUserDetailsServiceAutoConfiguration.class, + RSocketMessagingAutoConfiguration.class, RSocketStrategiesAutoConfiguration.class)) + .withUserConfiguration(TestRSocketSecurityConfiguration.class) + .run((context) -> { + ReactiveUserDetailsService userDetailsService = context.getBean(ReactiveUserDetailsService.class); + assertThat(userDetailsService.findByUsername("user").block(Duration.ofSeconds(30))).isNotNull(); + }); } @Test @@ -87,8 +88,8 @@ class ReactiveUserDetailsServiceAutoConfigurationTests { @Test void doesNotConfigureDefaultUserIfAuthenticationManagerAvailable() { this.contextRunner.withUserConfiguration(AuthenticationManagerConfig.class, TestSecurityConfiguration.class) - .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class)) - .run((context) -> assertThat(context).getBean(ReactiveUserDetailsService.class).isNull()); + .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class)) + .run((context) -> assertThat(context).getBean(ReactiveUserDetailsService.class).isNull()); } @Test @@ -134,13 +135,12 @@ class ReactiveUserDetailsServiceAutoConfigurationTests { private void testPasswordEncoding(Class configClass, String providedPassword, String expectedPassword) { this.contextRunner.withUserConfiguration(configClass) - .withPropertyValues("spring.security.user.password=" + providedPassword).run(((context) -> { - MapReactiveUserDetailsService userDetailsService = context - .getBean(MapReactiveUserDetailsService.class); - String password = userDetailsService.findByUsername("user").block(Duration.ofSeconds(30)) - .getPassword(); - assertThat(password).isEqualTo(expectedPassword); - })); + .withPropertyValues("spring.security.user.password=" + providedPassword) + .run(((context) -> { + MapReactiveUserDetailsService userDetailsService = context.getBean(MapReactiveUserDetailsService.class); + String password = userDetailsService.findByUsername("user").block(Duration.ofSeconds(30)).getPassword(); + assertThat(password).isEqualTo(expectedPassword); + })); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java index 556a1d94e6..c8db5e8741 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,7 +63,7 @@ class StaticResourceRequestTests { @Test void atCommonLocationsWithExcludeShouldNotMatchExcluded() { ServerWebExchangeMatcher matcher = this.resourceRequest.atCommonLocations() - .excluding(StaticResourceLocation.CSS); + .excluding(StaticResourceLocation.CSS); assertMatcher(matcher).doesNotMatch("/css/file.css"); assertMatcher(matcher).matches("/js/file.js"); } @@ -78,13 +78,13 @@ class StaticResourceRequestTests { @Test void atLocationsFromSetWhenSetIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.resourceRequest.at(null)) - .withMessageContaining("Locations must not be null"); + .withMessageContaining("Locations must not be null"); } @Test void excludeFromSetWhenSetIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.resourceRequest.atCommonLocations().excluding(null)) - .withMessageContaining("Locations must not be null"); + .withMessageContaining("Locations must not be null"); } private RequestMatcherAssert assertMatcher(ServerWebExchangeMatcher matcher) { @@ -112,7 +112,8 @@ class StaticResourceRequestTests { private void matches(ServerWebExchange exchange) { assertThat(this.matcher.matches(exchange).block(Duration.ofSeconds(30)).isMatch()) - .as("Matches " + getRequestPath(exchange)).isTrue(); + .as("Matches " + getRequestPath(exchange)) + .isTrue(); } void doesNotMatch(String path) { @@ -123,7 +124,8 @@ class StaticResourceRequestTests { private void doesNotMatch(ServerWebExchange exchange) { assertThat(this.matcher.matches(exchange).block(Duration.ofSeconds(30)).isMatch()) - .as("Does not match " + getRequestPath(exchange)).isFalse(); + .as("Does not match " + getRequestPath(exchange)) + .isFalse(); } private TestHttpWebHandlerAdapter webHandler() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/rsocket/RSocketSecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/rsocket/RSocketSecurityAutoConfigurationTests.java index c86748bc1f..14ffe03c00 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/rsocket/RSocketSecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/rsocket/RSocketSecurityAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,9 +42,9 @@ import static org.assertj.core.api.Assertions.assertThat; class RSocketSecurityAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveUserDetailsServiceAutoConfiguration.class, - RSocketSecurityAutoConfiguration.class, RSocketMessagingAutoConfiguration.class, - RSocketStrategiesAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveUserDetailsServiceAutoConfiguration.class, + RSocketSecurityAutoConfiguration.class, RSocketMessagingAutoConfiguration.class, + RSocketStrategiesAutoConfiguration.class)); @Test void autoConfigurationEnablesRSocketSecurity() { @@ -54,7 +54,7 @@ class RSocketSecurityAutoConfigurationTests { @Test void autoConfigurationIsConditionalOnSecuritySocketAcceptorInterceptorClass() { this.contextRunner.withClassLoader(new FilteredClassLoader(SecuritySocketAcceptorInterceptor.class)) - .run((context) -> assertThat(context).doesNotHaveBean(RSocketSecurity.class)); + .run((context) -> assertThat(context).doesNotHaveBean(RSocketSecurity.class)); } @Test @@ -66,7 +66,7 @@ class RSocketSecurityAutoConfigurationTests { server.interceptors((registry) -> registry.forSocketAcceptor((interceptors) -> { assertThat(interceptors).isNotEmpty(); assertThat(interceptors) - .anyMatch((interceptor) -> interceptor instanceof SecuritySocketAcceptorInterceptor); + .anyMatch((interceptor) -> interceptor instanceof SecuritySocketAcceptorInterceptor); })); }); } @@ -77,7 +77,7 @@ class RSocketSecurityAutoConfigurationTests { assertThat(context).hasSingleBean(RSocketMessageHandler.class); RSocketMessageHandler handler = context.getBean(RSocketMessageHandler.class); assertThat(handler.getArgumentResolverConfigurer().getCustomResolvers()).isNotEmpty() - .anyMatch((customResolver) -> customResolver instanceof AuthenticationPrincipalArgumentResolver); + .anyMatch((customResolver) -> customResolver instanceof AuthenticationPrincipalArgumentResolver); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyAutoConfigurationTests.java index 4d040c3b32..d33ae6e952 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,40 +65,42 @@ class Saml2RelyingPartyAutoConfigurationTests { @Test void autoConfigurationShouldBeConditionalOnRelyingPartyRegistrationRepositoryClass() { - this.contextRunner.withPropertyValues(getPropertyValues(false)).withClassLoader(new FilteredClassLoader( - "org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository")) - .run((context) -> assertThat(context).doesNotHaveBean(RelyingPartyRegistrationRepository.class)); + this.contextRunner.withPropertyValues(getPropertyValues(false)) + .withClassLoader(new FilteredClassLoader( + "org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository")) + .run((context) -> assertThat(context).doesNotHaveBean(RelyingPartyRegistrationRepository.class)); } @Test @Deprecated void autoConfigurationShouldBeConditionalOnRelyingPartyRegistrationRepositoryClassDeprecated() { - this.contextRunner.withPropertyValues(getPropertyValues(true)).withClassLoader(new FilteredClassLoader( - "org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository")) - .run((context) -> assertThat(context).doesNotHaveBean(RelyingPartyRegistrationRepository.class)); + this.contextRunner.withPropertyValues(getPropertyValues(true)) + .withClassLoader(new FilteredClassLoader( + "org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository")) + .run((context) -> assertThat(context).doesNotHaveBean(RelyingPartyRegistrationRepository.class)); } @Test void autoConfigurationShouldBeConditionalOnServletWebApplication() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(Saml2RelyingPartyAutoConfiguration.class)) - .withPropertyValues(getPropertyValues(false)) - .run((context) -> assertThat(context).doesNotHaveBean(RelyingPartyRegistrationRepository.class)); + .withConfiguration(AutoConfigurations.of(Saml2RelyingPartyAutoConfiguration.class)) + .withPropertyValues(getPropertyValues(false)) + .run((context) -> assertThat(context).doesNotHaveBean(RelyingPartyRegistrationRepository.class)); } @Test @Deprecated void autoConfigurationShouldBeConditionalOnServletWebApplicationDeprecated() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(Saml2RelyingPartyAutoConfiguration.class)) - .withPropertyValues(getPropertyValues(true)) - .run((context) -> assertThat(context).doesNotHaveBean(RelyingPartyRegistrationRepository.class)); + .withConfiguration(AutoConfigurations.of(Saml2RelyingPartyAutoConfiguration.class)) + .withPropertyValues(getPropertyValues(true)) + .run((context) -> assertThat(context).doesNotHaveBean(RelyingPartyRegistrationRepository.class)); } @Test void relyingPartyRegistrationRepositoryBeanShouldNotBeCreatedWhenPropertiesAbsent() { this.contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(RelyingPartyRegistrationRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(RelyingPartyRegistrationRepository.class)); } @Test @@ -108,14 +110,14 @@ class Saml2RelyingPartyAutoConfigurationTests { RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceLocation()) - .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SSOService.php"); + .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SSOService.php"); assertThat(registration.getAssertingPartyDetails().getEntityId()) - .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/metadata.php"); + .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/metadata.php"); assertThat(registration.getAssertionConsumerServiceLocation()) - .isEqualTo("{baseUrl}/login/saml2/foo-entity-id"); + .isEqualTo("{baseUrl}/login/saml2/foo-entity-id"); assertThat(registration.getAssertionConsumerServiceBinding()).isEqualTo(Saml2MessageBinding.REDIRECT); assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) - .isEqualTo(Saml2MessageBinding.POST); + .isEqualTo(Saml2MessageBinding.POST); assertThat(registration.getAssertingPartyDetails().getWantAuthnRequestsSigned()).isEqualTo(false); assertThat(registration.getSigningX509Credentials()).hasSize(1); assertThat(registration.getDecryptionX509Credentials()).hasSize(1); @@ -132,41 +134,41 @@ class Saml2RelyingPartyAutoConfigurationTests { RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceLocation()) - .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SSOService.php"); + .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SSOService.php"); assertThat(registration.getAssertingPartyDetails().getEntityId()) - .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/metadata.php"); + .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/metadata.php"); assertThat(registration.getAssertionConsumerServiceLocation()) - .isEqualTo("{baseUrl}/login/saml2/foo-entity-id"); + .isEqualTo("{baseUrl}/login/saml2/foo-entity-id"); assertThat(registration.getAssertionConsumerServiceBinding()).isEqualTo(Saml2MessageBinding.REDIRECT); assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) - .isEqualTo(Saml2MessageBinding.POST); + .isEqualTo(Saml2MessageBinding.POST); assertThat(registration.getAssertingPartyDetails().getWantAuthnRequestsSigned()).isEqualTo(false); assertThat(registration.getSigningX509Credentials()).hasSize(1); assertThat(registration.getDecryptionX509Credentials()).hasSize(1); assertThat(registration.getAssertingPartyDetails().getVerificationX509Credentials()).isNotNull(); assertThat(registration.getEntityId()).isEqualTo("{baseUrl}/saml2/foo-entity-id"); assertThat(registration.getSingleLogoutServiceLocation()) - .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SLOService.php"); + .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SLOService.php"); assertThat(registration.getSingleLogoutServiceResponseLocation()) - .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/"); + .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/"); assertThat(registration.getSingleLogoutServiceBinding()).isEqualTo(Saml2MessageBinding.POST); assertThat(registration.getAssertingPartyDetails().getSingleLogoutServiceLocation()) - .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SLOService.php"); + .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SLOService.php"); assertThat(registration.getAssertingPartyDetails().getSingleLogoutServiceResponseLocation()) - .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/"); + .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/"); assertThat(registration.getAssertingPartyDetails().getSingleLogoutServiceBinding()) - .isEqualTo(Saml2MessageBinding.POST); + .isEqualTo(Saml2MessageBinding.POST); }); } @Test void autoConfigurationWhenSignRequestsTrueAndNoSigningCredentialsShouldThrowException() { this.contextRunner.withPropertyValues(getPropertyValuesWithoutSigningCredentials(true, false)) - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()).hasMessageContaining( - "Signing credentials must not be empty when authentication requests require signing."); - }); + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()).hasMessageContaining( + "Signing credentials must not be empty when authentication requests require signing."); + }); } @Test @@ -182,14 +184,14 @@ class Saml2RelyingPartyAutoConfigurationTests { @Test void autoConfigurationWhenSignRequestsFalseAndNoSigningCredentialsShouldNotThrowException() { this.contextRunner.withPropertyValues(getPropertyValuesWithoutSigningCredentials(false, false)) - .run((context) -> assertThat(context).hasSingleBean(RelyingPartyRegistrationRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(RelyingPartyRegistrationRepository.class)); } @Test @Deprecated void autoConfigurationWhenSignRequestsFalseAndNoSigningCredentialsShouldNotThrowExceptionDeprecated() { this.contextRunner.withPropertyValues(getPropertyValuesWithoutSigningCredentials(false, true)) - .run((context) -> assertThat(context).hasSingleBean(RelyingPartyRegistrationRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(RelyingPartyRegistrationRepository.class)); } @Test @@ -199,10 +201,10 @@ class Saml2RelyingPartyAutoConfigurationTests { String metadataUrl = server.url("").toString(); setupMockResponse(server, new ClassPathResource("saml/idp-metadata")); this.contextRunner.withPropertyValues(PREFIX + ".foo.assertingparty.metadata-uri=" + metadataUrl) - .run((context) -> { - assertThat(context).hasSingleBean(RelyingPartyRegistrationRepository.class); - assertThat(server.getRequestCount()).isEqualTo(1); - }); + .run((context) -> { + assertThat(context).hasSingleBean(RelyingPartyRegistrationRepository.class); + assertThat(server.getRequestCount()).isEqualTo(1); + }); } } @@ -214,10 +216,10 @@ class Saml2RelyingPartyAutoConfigurationTests { String metadataUrl = server.url("").toString(); setupMockResponse(server, new ClassPathResource("saml/idp-metadata")); this.contextRunner.withPropertyValues(PREFIX + ".foo.identityprovider.metadata-uri=" + metadataUrl) - .run((context) -> { - assertThat(context).hasSingleBean(RelyingPartyRegistrationRepository.class); - assertThat(server.getRequestCount()).isEqualTo(1); - }); + .run((context) -> { + assertThat(context).hasSingleBean(RelyingPartyRegistrationRepository.class); + assertThat(server.getRequestCount()).isEqualTo(1); + }); } } @@ -228,13 +230,13 @@ class Saml2RelyingPartyAutoConfigurationTests { String metadataUrl = server.url("").toString(); setupMockResponse(server, new ClassPathResource("saml/idp-metadata")); this.contextRunner.withPropertyValues(PREFIX + ".foo.assertingparty.metadata-uri=" + metadataUrl) - .run((context) -> { - RelyingPartyRegistrationRepository repository = context - .getBean(RelyingPartyRegistrationRepository.class); - RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); - assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) - .isEqualTo(Saml2MessageBinding.POST); - }); + .run((context) -> { + RelyingPartyRegistrationRepository repository = context + .getBean(RelyingPartyRegistrationRepository.class); + RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); + assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) + .isEqualTo(Saml2MessageBinding.POST); + }); } } @@ -246,13 +248,13 @@ class Saml2RelyingPartyAutoConfigurationTests { String metadataUrl = server.url("").toString(); setupMockResponse(server, new ClassPathResource("saml/idp-metadata")); this.contextRunner.withPropertyValues(PREFIX + ".foo.identityprovider.metadata-uri=" + metadataUrl) - .run((context) -> { - RelyingPartyRegistrationRepository repository = context - .getBean(RelyingPartyRegistrationRepository.class); - RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); - assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) - .isEqualTo(Saml2MessageBinding.POST); - }); + .run((context) -> { + RelyingPartyRegistrationRepository repository = context + .getBean(RelyingPartyRegistrationRepository.class); + RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); + assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) + .isEqualTo(Saml2MessageBinding.POST); + }); } } @@ -262,14 +264,16 @@ class Saml2RelyingPartyAutoConfigurationTests { server.start(); String metadataUrl = server.url("").toString(); setupMockResponse(server, new ClassPathResource("saml/idp-metadata")); - this.contextRunner.withPropertyValues(PREFIX + ".foo.assertingparty.metadata-uri=" + metadataUrl, - PREFIX + ".foo.assertingparty.singlesignon.binding=redirect").run((context) -> { - RelyingPartyRegistrationRepository repository = context - .getBean(RelyingPartyRegistrationRepository.class); - RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); - assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) - .isEqualTo(Saml2MessageBinding.REDIRECT); - }); + this.contextRunner + .withPropertyValues(PREFIX + ".foo.assertingparty.metadata-uri=" + metadataUrl, + PREFIX + ".foo.assertingparty.singlesignon.binding=redirect") + .run((context) -> { + RelyingPartyRegistrationRepository repository = context + .getBean(RelyingPartyRegistrationRepository.class); + RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); + assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) + .isEqualTo(Saml2MessageBinding.REDIRECT); + }); } } @@ -280,14 +284,16 @@ class Saml2RelyingPartyAutoConfigurationTests { server.start(); String metadataUrl = server.url("").toString(); setupMockResponse(server, new ClassPathResource("saml/idp-metadata")); - this.contextRunner.withPropertyValues(PREFIX + ".foo.identityprovider.metadata-uri=" + metadataUrl, - PREFIX + ".foo.identityprovider.singlesignon.binding=redirect").run((context) -> { - RelyingPartyRegistrationRepository repository = context - .getBean(RelyingPartyRegistrationRepository.class); - RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); - assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) - .isEqualTo(Saml2MessageBinding.REDIRECT); - }); + this.contextRunner + .withPropertyValues(PREFIX + ".foo.identityprovider.metadata-uri=" + metadataUrl, + PREFIX + ".foo.identityprovider.singlesignon.binding=redirect") + .run((context) -> { + RelyingPartyRegistrationRepository repository = context + .getBean(RelyingPartyRegistrationRepository.class); + RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); + assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) + .isEqualTo(Saml2MessageBinding.REDIRECT); + }); } } @@ -297,7 +303,7 @@ class Saml2RelyingPartyAutoConfigurationTests { RelyingPartyRegistrationRepository repository = context.getBean(RelyingPartyRegistrationRepository.class); RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) - .isEqualTo(Saml2MessageBinding.REDIRECT); + .isEqualTo(Saml2MessageBinding.REDIRECT); }); } @@ -308,91 +314,93 @@ class Saml2RelyingPartyAutoConfigurationTests { RelyingPartyRegistrationRepository repository = context.getBean(RelyingPartyRegistrationRepository.class); RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) - .isEqualTo(Saml2MessageBinding.REDIRECT); + .isEqualTo(Saml2MessageBinding.REDIRECT); }); } @Test void relyingPartyRegistrationRepositoryShouldBeConditionalOnMissingBean() { this.contextRunner.withPropertyValues(getPropertyValues(false)) - .withUserConfiguration(RegistrationRepositoryConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(RelyingPartyRegistrationRepository.class); - assertThat(context).hasBean("testRegistrationRepository"); - }); + .withUserConfiguration(RegistrationRepositoryConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(RelyingPartyRegistrationRepository.class); + assertThat(context).hasBean("testRegistrationRepository"); + }); } @Test @Deprecated void relyingPartyRegistrationRepositoryShouldBeConditionalOnMissingBeanDeprecated() { this.contextRunner.withPropertyValues(getPropertyValues(true)) - .withUserConfiguration(RegistrationRepositoryConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(RelyingPartyRegistrationRepository.class); - assertThat(context).hasBean("testRegistrationRepository"); - }); + .withUserConfiguration(RegistrationRepositoryConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(RelyingPartyRegistrationRepository.class); + assertThat(context).hasBean("testRegistrationRepository"); + }); } @Test void samlLoginShouldBeConfigured() { this.contextRunner.withPropertyValues(getPropertyValues(false)) - .run((context) -> assertThat(hasFilter(context, Saml2WebSsoAuthenticationFilter.class)).isTrue()); + .run((context) -> assertThat(hasFilter(context, Saml2WebSsoAuthenticationFilter.class)).isTrue()); } @Test @Deprecated void samlLoginShouldBeConfiguredDeprecated() { this.contextRunner.withPropertyValues(getPropertyValues(true)) - .run((context) -> assertThat(hasFilter(context, Saml2WebSsoAuthenticationFilter.class)).isTrue()); + .run((context) -> assertThat(hasFilter(context, Saml2WebSsoAuthenticationFilter.class)).isTrue()); } @Test void samlLoginShouldBackOffWhenAWebSecurityConfigurerAdapterIsDefined() { this.contextRunner.withUserConfiguration(WebSecurityConfigurerAdapterConfiguration.class) - .withPropertyValues(getPropertyValues(false)) - .run((context) -> assertThat(hasFilter(context, Saml2WebSsoAuthenticationFilter.class)).isFalse()); + .withPropertyValues(getPropertyValues(false)) + .run((context) -> assertThat(hasFilter(context, Saml2WebSsoAuthenticationFilter.class)).isFalse()); } @Test @Deprecated void samlLoginShouldBackOffWhenAWebSecurityConfigurerAdapterIsDefinedDeprecated() { this.contextRunner.withUserConfiguration(WebSecurityConfigurerAdapterConfiguration.class) - .withPropertyValues(getPropertyValues(true)) - .run((context) -> assertThat(hasFilter(context, Saml2WebSsoAuthenticationFilter.class)).isFalse()); + .withPropertyValues(getPropertyValues(true)) + .run((context) -> assertThat(hasFilter(context, Saml2WebSsoAuthenticationFilter.class)).isFalse()); } @Test void samlLoginShouldBackOffWhenASecurityFilterChainBeanIsPresent() { this.contextRunner.withUserConfiguration(TestSecurityFilterChainConfig.class) - .withPropertyValues(getPropertyValues(false)) - .run((context) -> assertThat(hasFilter(context, Saml2WebSsoAuthenticationFilter.class)).isFalse()); + .withPropertyValues(getPropertyValues(false)) + .run((context) -> assertThat(hasFilter(context, Saml2WebSsoAuthenticationFilter.class)).isFalse()); } @Test @Deprecated void samlLoginShouldBackOffWhenASecurityFilterChainBeanIsPresentDeprecated() { this.contextRunner.withUserConfiguration(TestSecurityFilterChainConfig.class) - .withPropertyValues(getPropertyValues(true)) - .run((context) -> assertThat(hasFilter(context, Saml2WebSsoAuthenticationFilter.class)).isFalse()); + .withPropertyValues(getPropertyValues(true)) + .run((context) -> assertThat(hasFilter(context, Saml2WebSsoAuthenticationFilter.class)).isFalse()); } @Test void samlLoginShouldShouldBeConditionalOnSecurityWebFilterClass() { this.contextRunner.withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)) - .withPropertyValues(getPropertyValues(false)) - .run((context) -> assertThat(context).doesNotHaveBean(SecurityFilterChain.class)); + .withPropertyValues(getPropertyValues(false)) + .run((context) -> assertThat(context).doesNotHaveBean(SecurityFilterChain.class)); } @Test @Deprecated void samlLoginShouldShouldBeConditionalOnSecurityWebFilterClassDeprecated() { this.contextRunner.withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)) - .withPropertyValues(getPropertyValues(true)) - .run((context) -> assertThat(context).doesNotHaveBean(SecurityFilterChain.class)); + .withPropertyValues(getPropertyValues(true)) + .run((context) -> assertThat(context).doesNotHaveBean(SecurityFilterChain.class)); } @Test void samlLogoutShouldBeConfigured() { this.contextRunner.withPropertyValues(getPropertyValues(false)) - .run((context) -> assertThat(hasFilter(context, Saml2LogoutRequestFilter.class)).isTrue()); + .run((context) -> assertThat(hasFilter(context, Saml2LogoutRequestFilter.class)).isTrue()); } private String[] getPropertyValuesWithoutSigningCredentials(boolean signRequests, boolean useDeprecated) { @@ -496,8 +504,9 @@ class Saml2RelyingPartyAutoConfigurationTests { @Bean SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception { - return http.antMatcher("/**").authorizeRequests((authorize) -> authorize.anyRequest().authenticated()) - .build(); + return http.antMatcher("/**") + .authorizeRequests((authorize) -> authorize.anyRequest().authenticated()) + .build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyPropertiesTests.java index 4788203026..0ae281bedc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,23 +45,29 @@ class Saml2RelyingPartyPropertiesTests { "https://simplesaml-for-spring-saml/SSOService.php"); assertThat( this.properties.getRegistration().get("simplesamlphp").getAssertingparty().getSinglesignon().getUrl()) - .isEqualTo("https://simplesaml-for-spring-saml/SSOService.php"); + .isEqualTo("https://simplesaml-for-spring-saml/SSOService.php"); } @Test void customizeSsoBinding() { bind("spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.single-sign-on.binding", "post"); - assertThat(this.properties.getRegistration().get("simplesamlphp").getAssertingparty().getSinglesignon() - .getBinding()).isEqualTo(Saml2MessageBinding.POST); + assertThat(this.properties.getRegistration() + .get("simplesamlphp") + .getAssertingparty() + .getSinglesignon() + .getBinding()).isEqualTo(Saml2MessageBinding.POST); } @Test void customizeSsoSignRequests() { bind("spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.single-sign-on.sign-request", "false"); - assertThat(this.properties.getRegistration().get("simplesamlphp").getAssertingparty().getSinglesignon() - .getSignRequest()).isEqualTo(false); + assertThat(this.properties.getRegistration() + .get("simplesamlphp") + .getAssertingparty() + .getSinglesignon() + .getSignRequest()).isEqualTo(false); } @Test @@ -69,13 +75,13 @@ class Saml2RelyingPartyPropertiesTests { bind("spring.security.saml2.relyingparty.registration.simplesamlphp.entity-id", "{baseUrl}/saml2/custom-entity-id"); assertThat(this.properties.getRegistration().get("simplesamlphp").getEntityId()) - .isEqualTo("{baseUrl}/saml2/custom-entity-id"); + .isEqualTo("{baseUrl}/saml2/custom-entity-id"); } @Test void customizeRelyingPartyEntityIdDefaultsToServiceProviderMetadata() { assertThat(RelyingPartyRegistration.withRegistrationId("id")).extracting("entityId") - .isEqualTo(new Saml2RelyingPartyProperties.Registration().getEntityId()); + .isEqualTo(new Saml2RelyingPartyProperties.Registration().getEntityId()); } @Test @@ -83,7 +89,7 @@ class Saml2RelyingPartyPropertiesTests { bind("spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.metadata-uri", "https://idp.example.org/metadata"); assertThat(this.properties.getRegistration().get("simplesamlphp").getAssertingparty().getMetadataUri()) - .isEqualTo("https://idp.example.org/metadata"); + .isEqualTo("https://idp.example.org/metadata"); } private void bind(String name, String value) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfigurationTests.java index b62cdca523..dad21e78a8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -84,13 +84,13 @@ class SecurityAutoConfigurationTests { @Test void enableWebSecurityIsConditionalOnClass() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.security.config")) - .run((context) -> assertThat(context).doesNotHaveBean("springSecurityFilterChain")); + .run((context) -> assertThat(context).doesNotHaveBean("springSecurityFilterChain")); } @Test void filterChainBeanIsConditionalOnClassSecurityFilterChain() { this.contextRunner.withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)) - .run((context) -> assertThat(context).doesNotHaveBean(SecurityFilterChain.class)); + .run((context) -> assertThat(context).doesNotHaveBean(SecurityFilterChain.class)); } @Test @@ -107,7 +107,7 @@ class SecurityAutoConfigurationTests { this.contextRunner.withUserConfiguration(WebSecurity.class).run((context) -> { assertThat(context.getBeansOfType( org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.class) - .size()).isEqualTo(1); + .size()).isEqualTo(1); assertThat(context.containsBean("securityAutoConfigurationTests.WebSecurity")).isTrue(); }); } @@ -115,10 +115,11 @@ class SecurityAutoConfigurationTests { @Test void testDefaultFilterOrderWithSecurityAdapter() { this.contextRunner - .withConfiguration(AutoConfigurations.of(WebSecurity.class, SecurityFilterAutoConfiguration.class)) - .run((context) -> assertThat( - context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) - .getOrder()).isEqualTo(OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100)); + .withConfiguration(AutoConfigurations.of(WebSecurity.class, SecurityFilterAutoConfiguration.class)) + .run((context) -> assertThat( + context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) + .getOrder()) + .isEqualTo(OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100)); } @Test @@ -134,40 +135,42 @@ class SecurityAutoConfigurationTests { @Test void defaultAuthenticationEventPublisherRegistered() { this.contextRunner.run((context) -> assertThat(context.getBean(AuthenticationEventPublisher.class)) - .isInstanceOf(DefaultAuthenticationEventPublisher.class)); + .isInstanceOf(DefaultAuthenticationEventPublisher.class)); } @Test void defaultAuthenticationEventPublisherIsConditionalOnMissingBean() { this.contextRunner.withUserConfiguration(AuthenticationEventPublisherConfiguration.class) - .run((context) -> assertThat(context.getBean(AuthenticationEventPublisher.class)).isInstanceOf( - AuthenticationEventPublisherConfiguration.TestAuthenticationEventPublisher.class)); + .run((context) -> assertThat(context.getBean(AuthenticationEventPublisher.class)) + .isInstanceOf(AuthenticationEventPublisherConfiguration.TestAuthenticationEventPublisher.class)); } @Test void testDefaultFilterOrder() { this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) - .run((context) -> assertThat( - context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) - .getOrder()).isEqualTo(OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100)); + .run((context) -> assertThat( + context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) + .getOrder()) + .isEqualTo(OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100)); } @Test void testCustomFilterOrder() { this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) - .withPropertyValues("spring.security.filter.order:12345") - .run((context) -> assertThat( - context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) - .getOrder()).isEqualTo(12345)); + .withPropertyValues("spring.security.filter.order:12345") + .run((context) -> assertThat( + context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) + .getOrder()) + .isEqualTo(12345)); } @Test void testJpaCoexistsHappily() { this.contextRunner.withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:testsecdb") - .withUserConfiguration(EntityConfiguration.class) - .withConfiguration( - AutoConfigurations.of(HibernateJpaAutoConfiguration.class, DataSourceAutoConfiguration.class)) - .run((context) -> assertThat(context.getBean(JpaTransactionManager.class)).isNotNull()); + .withUserConfiguration(EntityConfiguration.class) + .withConfiguration( + AutoConfigurations.of(HibernateJpaAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .run((context) -> assertThat(context.getBean(JpaTransactionManager.class)).isNotNull()); // This can fail if security @Conditionals force early instantiation of the // HibernateJpaAutoConfiguration (e.g. the EntityManagerFactory is not found) } @@ -175,85 +178,84 @@ class SecurityAutoConfigurationTests { @Test void testSecurityEvaluationContextExtensionSupport() { this.contextRunner - .run((context) -> assertThat(context).getBean(SecurityEvaluationContextExtension.class).isNotNull()); + .run((context) -> assertThat(context).getBean(SecurityEvaluationContextExtension.class).isNotNull()); } @Test void defaultFilterDispatcherTypes() { this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) - .run((context) -> { - DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", - DelegatingFilterProxyRegistrationBean.class); - assertThat(bean) - .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) - .containsOnly(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST); - }); + .run((context) -> { + DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", + DelegatingFilterProxyRegistrationBean.class); + assertThat(bean).extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) + .containsOnly(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST); + }); } @Test void customFilterDispatcherTypes() { this.contextRunner.withPropertyValues("spring.security.filter.dispatcher-types:INCLUDE,ERROR") - .withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)).run((context) -> { - DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", - DelegatingFilterProxyRegistrationBean.class); - assertThat(bean) - .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) - .containsOnly(DispatcherType.INCLUDE, DispatcherType.ERROR); - }); + .withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) + .run((context) -> { + DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", + DelegatingFilterProxyRegistrationBean.class); + assertThat(bean).extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) + .containsOnly(DispatcherType.INCLUDE, DispatcherType.ERROR); + }); } @Test void emptyFilterDispatcherTypesDoNotThrowException() { this.contextRunner.withPropertyValues("spring.security.filter.dispatcher-types:") - .withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)).run((context) -> { - DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", - DelegatingFilterProxyRegistrationBean.class); - assertThat(bean) - .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) - .isEmpty(); - }); + .withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) + .run((context) -> { + DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", + DelegatingFilterProxyRegistrationBean.class); + assertThat(bean).extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) + .isEmpty(); + }); } @Test void whenAConfigurationPropertyBindingConverterIsDefinedThenBindingToAnRsaKeySucceeds() { this.contextRunner.withUserConfiguration(ConverterConfiguration.class, PropertiesConfiguration.class) - .withPropertyValues("jwt.public-key=classpath:public-key-location") - .run((context) -> assertThat(context.getBean(JwtProperties.class).getPublicKey()).isNotNull()); + .withPropertyValues("jwt.public-key=classpath:public-key-location") + .run((context) -> assertThat(context.getBean(JwtProperties.class).getPublicKey()).isNotNull()); } @Test void whenTheBeanFactoryHasAConversionServiceAndAConfigurationPropertyBindingConverterIsDefinedThenBindingToAnRsaKeySucceeds() { this.contextRunner - .withInitializer( - (context) -> context.getBeanFactory().setConversionService(new ApplicationConversionService())) - .withUserConfiguration(ConverterConfiguration.class, PropertiesConfiguration.class) - .withPropertyValues("jwt.public-key=classpath:public-key-location") - .run((context) -> assertThat(context.getBean(JwtProperties.class).getPublicKey()).isNotNull()); + .withInitializer( + (context) -> context.getBeanFactory().setConversionService(new ApplicationConversionService())) + .withUserConfiguration(ConverterConfiguration.class, PropertiesConfiguration.class) + .withPropertyValues("jwt.public-key=classpath:public-key-location") + .run((context) -> assertThat(context.getBean(JwtProperties.class).getPublicKey()).isNotNull()); } @Test @SuppressWarnings("unchecked") void filterRegistrationBeanForErrorPageSecurityInterceptor() { this.contextRunner.withInitializer((context) -> context.setServletContext(new MockServletContext())) - .run(((context) -> { - FilterRegistrationBean bean = context.getBean(FilterRegistrationBean.class); - assertThat(bean.getFilter()).isInstanceOf(ErrorPageSecurityFilter.class); - EnumSet dispatcherTypes = (EnumSet) ReflectionTestUtils - .getField(bean, "dispatcherTypes"); - assertThat(dispatcherTypes).containsExactly(DispatcherType.ERROR); - })); + .run(((context) -> { + FilterRegistrationBean bean = context.getBean(FilterRegistrationBean.class); + assertThat(bean.getFilter()).isInstanceOf(ErrorPageSecurityFilter.class); + EnumSet dispatcherTypes = (EnumSet) ReflectionTestUtils.getField(bean, + "dispatcherTypes"); + assertThat(dispatcherTypes).containsExactly(DispatcherType.ERROR); + })); } @Test void filterForErrorPageSecurityInterceptorWhenWebInvocationPrivilegeEvaluatorNotPresent() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.security.config")) - .run((context) -> assertThat(context).doesNotHaveBean("errorPageSecurityFilter")); + .run((context) -> assertThat(context).doesNotHaveBean("errorPageSecurityFilter")); } @Test void filterForErrorPageSecurityInterceptorConditionalOnClass() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.security.web")) - .run((context) -> assertThat(context).doesNotHaveBean("errorPageSecurityFilter")); + .run((context) -> assertThat(context).doesNotHaveBean("errorPageSecurityFilter")); } @Configuration(proxyBeanMethods = false) @@ -299,8 +301,9 @@ class SecurityAutoConfigurationTests { @Bean SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception { - return http.antMatcher("/**").authorizeRequests((authorize) -> authorize.anyRequest().authenticated()) - .build(); + return http.antMatcher("/**") + .authorizeRequests((authorize) -> authorize.anyRequest().authenticated()) + .build(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java index 26babb807d..b3e4026e53 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -88,13 +88,13 @@ class StaticResourceRequestTests { @Test void atLocationsFromSetWhenSetIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.resourceRequest.at(null)) - .withMessageContaining("Locations must not be null"); + .withMessageContaining("Locations must not be null"); } @Test void excludeFromSetWhenSetIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.resourceRequest.atCommonLocations().excluding(null)) - .withMessageContaining("Locations must not be null"); + .withMessageContaining("Locations must not be null"); } private RequestMatcherAssert assertMatcher(RequestMatcher matcher) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfigurationTests.java index 9fa64ddd8a..c2a495613c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,8 +60,8 @@ import static org.mockito.Mockito.mock; class UserDetailsServiceAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(TestSecurityConfiguration.class) - .withConfiguration(AutoConfigurations.of(UserDetailsServiceAutoConfiguration.class)); + .withUserConfiguration(TestSecurityConfiguration.class) + .withConfiguration(AutoConfigurations.of(UserDetailsServiceAutoConfiguration.class)); @Test void testDefaultUsernamePassword(CapturedOutput output) { @@ -77,7 +77,7 @@ class UserDetailsServiceAutoConfigurationTests { this.contextRunner.withUserConfiguration(TestAuthenticationManagerConfiguration.class).run((context) -> { AuthenticationManager manager = context.getBean(AuthenticationManager.class); assertThat(manager) - .isEqualTo(context.getBean(TestAuthenticationManagerConfiguration.class).authenticationManager); + .isEqualTo(context.getBean(TestAuthenticationManagerConfiguration.class).authenticationManager); assertThat(output).doesNotContain("Using generated security password: "); TestingAuthenticationToken token = new TestingAuthenticationToken("foo", "bar"); assertThat(manager.authenticate(token)).isNotNull(); @@ -87,7 +87,7 @@ class UserDetailsServiceAutoConfigurationTests { @Test void defaultUserNotCreatedIfAuthenticationManagerResolverBeanPresent(CapturedOutput output) { this.contextRunner.withUserConfiguration(TestAuthenticationManagerResolverConfiguration.class) - .run((context) -> assertThat(output).doesNotContain("Using generated security password: ")); + .run((context) -> assertThat(output).doesNotContain("Using generated security password: ")); } @Test @@ -153,30 +153,30 @@ class UserDetailsServiceAutoConfigurationTests { @Test void userDetailsServiceWhenClientRegistrationRepositoryBeanPresent() { this.contextRunner.withUserConfiguration(TestConfigWithClientRegistrationRepository.class) - .run(((context) -> assertThat(context).doesNotHaveBean(InMemoryUserDetailsManager.class))); + .run(((context) -> assertThat(context).doesNotHaveBean(InMemoryUserDetailsManager.class))); } @Test void userDetailsServiceWhenRelyingPartyRegistrationRepositoryBeanPresent() { this.contextRunner - .withBean(RelyingPartyRegistrationRepository.class, - () -> mock(RelyingPartyRegistrationRepository.class)) - .run(((context) -> assertThat(context).doesNotHaveBean(InMemoryUserDetailsManager.class))); + .withBean(RelyingPartyRegistrationRepository.class, () -> mock(RelyingPartyRegistrationRepository.class)) + .run(((context) -> assertThat(context).doesNotHaveBean(InMemoryUserDetailsManager.class))); } @Test void generatedPasswordShouldNotBePrintedIfAuthenticationManagerBuilderIsUsed(CapturedOutput output) { this.contextRunner.withUserConfiguration(TestConfigWithAuthenticationManagerBuilder.class) - .run(((context) -> assertThat(output).doesNotContain("Using generated security password: "))); + .run(((context) -> assertThat(output).doesNotContain("Using generated security password: "))); } private void testPasswordEncoding(Class configClass, String providedPassword, String expectedPassword) { this.contextRunner.withUserConfiguration(configClass) - .withPropertyValues("spring.security.user.password=" + providedPassword).run(((context) -> { - InMemoryUserDetailsManager userDetailsService = context.getBean(InMemoryUserDetailsManager.class); - String password = userDetailsService.loadUserByUsername("user").getPassword(); - assertThat(password).isEqualTo(expectedPassword); - })); + .withPropertyValues("spring.security.user.password=" + providedPassword) + .run(((context) -> { + InMemoryUserDetailsManager userDetailsService = context.getBean(InMemoryUserDetailsManager.class); + String password = userDetailsService.loadUserByUsername("user").getPassword(); + assertThat(password).isEqualTo(expectedPassword); + })); } @Configuration(proxyBeanMethods = false) @@ -274,8 +274,14 @@ class UserDetailsServiceAutoConfigurationTests { return new org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter() { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("hero").password("{noop}hero").roles("HERO", "USER").and() - .withUser("user").password("{noop}user").roles("USER"); + auth.inMemoryAuthentication() + .withUser("hero") + .password("{noop}hero") + .roles("HERO", "USER") + .and() + .withUser("user") + .password("{noop}user") + .roles("USER"); } }; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java index 287792d0f6..590897bd83 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,7 +59,7 @@ class SendGridAutoConfigurationTests { void autoConfigurationNotFiredWhenPropertiesNotSet() { loadContext(); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(SendGrid.class)); + .isThrownBy(() -> this.context.getBean(SendGrid.class)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/JdbcSessionDataSourceScriptDatabaseInitializerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/JdbcSessionDataSourceScriptDatabaseInitializerTests.java index 3b78e05e73..81c3359c83 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/JdbcSessionDataSourceScriptDatabaseInitializerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/JdbcSessionDataSourceScriptDatabaseInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ class JdbcSessionDataSourceScriptDatabaseInitializerTests { DatabaseInitializationSettings settings = JdbcSessionDataSourceScriptDatabaseInitializer.getSettings(dataSource, properties); assertThat(settings.getSchemaLocations()) - .containsOnly("classpath:org/springframework/session/jdbc/schema-test.sql"); + .containsOnly("classpath:org/springframework/session/jdbc/schema-test.sql"); then(dataSource).shouldHaveNoInteractions(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationMongoTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationMongoTests.java index fc30e246f2..ed00826b66 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationMongoTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationMongoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,66 +52,66 @@ class ReactiveSessionAutoConfigurationMongoTests extends AbstractSessionAutoConf @Container static final MongoDBContainer mongoDb = new MongoDBContainer(DockerImageNames.mongo()).withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(5)); + .withStartupTimeout(Duration.ofMinutes(5)); private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); @Test void defaultConfig() { this.contextRunner - .withPropertyValues("spring.session.store-type=mongodb", - "spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)) - .run(validateSpringSessionUsesMongo("sessions")); + .withPropertyValues("spring.session.store-type=mongodb", + "spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()) + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)) + .run(validateSpringSessionUsesMongo("sessions")); } @Test void defaultConfigWithUniqueStoreImplementation() { this.contextRunner.withClassLoader(new FilteredClassLoader(ReactiveRedisSessionRepository.class)) - .withPropertyValues("spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)) - .run(validateSpringSessionUsesMongo("sessions")); + .withPropertyValues("spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()) + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)) + .run(validateSpringSessionUsesMongo("sessions")); } @Test void defaultConfigWithCustomTimeout() { this.contextRunner - .withPropertyValues("spring.session.store-type=mongodb", "spring.session.timeout=1m", - "spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)) - .run((context) -> { - ReactiveMongoSessionRepository repository = validateSessionRepository(context, - ReactiveMongoSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("maxInactiveIntervalInSeconds", 60); - }); + .withPropertyValues("spring.session.store-type=mongodb", "spring.session.timeout=1m", + "spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()) + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)) + .run((context) -> { + ReactiveMongoSessionRepository repository = validateSessionRepository(context, + ReactiveMongoSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("maxInactiveIntervalInSeconds", 60); + }); } @Test void defaultConfigWithCustomSessionTimeout() { this.contextRunner - .withPropertyValues("spring.session.store-type=mongodb", "server.reactive.session.timeout=1m", - "spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)) - .run((context) -> { - ReactiveMongoSessionRepository repository = validateSessionRepository(context, - ReactiveMongoSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("maxInactiveIntervalInSeconds", 60); - }); + .withPropertyValues("spring.session.store-type=mongodb", "server.reactive.session.timeout=1m", + "spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()) + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)) + .run((context) -> { + ReactiveMongoSessionRepository repository = validateSessionRepository(context, + ReactiveMongoSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("maxInactiveIntervalInSeconds", 60); + }); } @Test void mongoSessionStoreWithCustomizations() { this.contextRunner - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)) - .withPropertyValues("spring.session.store-type=mongodb", "spring.session.mongodb.collection-name=foo", - "spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()) - .run(validateSpringSessionUsesMongo("foo")); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)) + .withPropertyValues("spring.session.store-type=mongodb", "spring.session.mongodb.collection-name=foo", + "spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()) + .run(validateSpringSessionUsesMongo("foo")); } @Test @@ -119,21 +119,24 @@ class ReactiveSessionAutoConfigurationMongoTests extends AbstractSessionAutoConf AutoConfigurations autoConfigurations = AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, WebSessionIdResolverAutoConfiguration.class); - this.contextRunner.withConfiguration(autoConfigurations).withUserConfiguration(Config.class).withPropertyValues( - "spring.session.store-type=mongodb", "server.reactive.session.cookie.name:JSESSIONID", - "server.reactive.session.cookie.domain:.example.com", "server.reactive.session.cookie.path:/example", - "server.reactive.session.cookie.max-age:60", "server.reactive.session.cookie.http-only:false", - "server.reactive.session.cookie.secure:false", "server.reactive.session.cookie.same-site:strict", - "spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()).run(assertExchangeWithSession((exchange) -> { - List cookies = exchange.getResponse().getCookies().get("JSESSIONID"); - assertThat(cookies).isNotEmpty(); - assertThat(cookies).allMatch((cookie) -> cookie.getDomain().equals(".example.com")); - assertThat(cookies).allMatch((cookie) -> cookie.getPath().equals("/example")); - assertThat(cookies).allMatch((cookie) -> cookie.getMaxAge().equals(Duration.ofSeconds(60))); - assertThat(cookies).allMatch((cookie) -> !cookie.isHttpOnly()); - assertThat(cookies).allMatch((cookie) -> !cookie.isSecure()); - assertThat(cookies).allMatch((cookie) -> cookie.getSameSite().equals("Strict")); - })); + this.contextRunner.withConfiguration(autoConfigurations) + .withUserConfiguration(Config.class) + .withPropertyValues("spring.session.store-type=mongodb", "server.reactive.session.cookie.name:JSESSIONID", + "server.reactive.session.cookie.domain:.example.com", + "server.reactive.session.cookie.path:/example", "server.reactive.session.cookie.max-age:60", + "server.reactive.session.cookie.http-only:false", "server.reactive.session.cookie.secure:false", + "server.reactive.session.cookie.same-site:strict", + "spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()) + .run(assertExchangeWithSession((exchange) -> { + List cookies = exchange.getResponse().getCookies().get("JSESSIONID"); + assertThat(cookies).isNotEmpty(); + assertThat(cookies).allMatch((cookie) -> cookie.getDomain().equals(".example.com")); + assertThat(cookies).allMatch((cookie) -> cookie.getPath().equals("/example")); + assertThat(cookies).allMatch((cookie) -> cookie.getMaxAge().equals(Duration.ofSeconds(60))); + assertThat(cookies).allMatch((cookie) -> !cookie.isHttpOnly()); + assertThat(cookies).allMatch((cookie) -> !cookie.isSecure()); + assertThat(cookies).allMatch((cookie) -> cookie.getSameSite().equals("Strict")); + })); } private ContextConsumer validateSpringSessionUsesMongo( diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationRedisTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationRedisTests.java index 6525a57201..06c344bec5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationRedisTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationRedisTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,85 +53,85 @@ class ReactiveSessionAutoConfigurationRedisTests extends AbstractSessionAutoConf @Container public static RedisContainer redis = new RedisContainer().withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(10)); + .withStartupTimeout(Duration.ofMinutes(10)); protected final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(SessionAutoConfiguration.class, WebSessionIdResolverAutoConfiguration.class)); + .withConfiguration( + AutoConfigurations.of(SessionAutoConfiguration.class, WebSessionIdResolverAutoConfiguration.class)); @Test void defaultConfig() { this.contextRunner.withPropertyValues("spring.session.store-type=redis") - .withConfiguration( - AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)) - .run(validateSpringSessionUsesRedis("spring:session:", SaveMode.ON_SET_ATTRIBUTE)); + .withConfiguration( + AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)) + .run(validateSpringSessionUsesRedis("spring:session:", SaveMode.ON_SET_ATTRIBUTE)); } @Test void defaultConfigWithUniqueStoreImplementation() { this.contextRunner.withClassLoader(new FilteredClassLoader(ReactiveMongoSessionRepository.class)) - .withConfiguration( - AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)) - .run(validateSpringSessionUsesRedis("spring:session:", SaveMode.ON_SET_ATTRIBUTE)); + .withConfiguration( + AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)) + .run(validateSpringSessionUsesRedis("spring:session:", SaveMode.ON_SET_ATTRIBUTE)); } @Test void defaultConfigWithCustomTimeout() { this.contextRunner.withPropertyValues("spring.session.store-type=redis", "spring.session.timeout=1m") - .withConfiguration( - AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)) - .run((context) -> { - ReactiveRedisSessionRepository repository = validateSessionRepository(context, - ReactiveRedisSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", 60); - }); + .withConfiguration( + AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)) + .run((context) -> { + ReactiveRedisSessionRepository repository = validateSessionRepository(context, + ReactiveRedisSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", 60); + }); } @Test void defaultConfigWithCustomWebFluxTimeout() { this.contextRunner.withPropertyValues("spring.session.store-type=redis", "server.reactive.session.timeout=1m") - .withConfiguration( - AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)) - .run((context) -> { - ReactiveRedisSessionRepository repository = validateSessionRepository(context, - ReactiveRedisSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", 60); - }); + .withConfiguration( + AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)) + .run((context) -> { + ReactiveRedisSessionRepository repository = validateSessionRepository(context, + ReactiveRedisSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", 60); + }); } @Test void redisSessionStoreWithCustomizations() { this.contextRunner - .withConfiguration( - AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)) - .withPropertyValues("spring.session.store-type=redis", "spring.session.redis.namespace=foo", - "spring.session.redis.save-mode=on-get-attribute") - .run(validateSpringSessionUsesRedis("foo:", SaveMode.ON_GET_ATTRIBUTE)); + .withConfiguration( + AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)) + .withPropertyValues("spring.session.store-type=redis", "spring.session.redis.namespace=foo", + "spring.session.redis.save-mode=on-get-attribute") + .run(validateSpringSessionUsesRedis("foo:", SaveMode.ON_GET_ATTRIBUTE)); } @Test void sessionCookieConfigurationIsAppliedToAutoConfiguredWebSessionIdResolver() { this.contextRunner - .withConfiguration( - AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)) - .withUserConfiguration(Config.class) - .withPropertyValues("spring.session.store-type=redis", "spring.redis.host=" + redis.getHost(), - "spring.redis.port=" + redis.getFirstMappedPort(), "spring.session.store-type=redis", - "server.reactive.session.cookie.name:JSESSIONID", - "server.reactive.session.cookie.domain:.example.com", - "server.reactive.session.cookie.path:/example", "server.reactive.session.cookie.max-age:60", - "server.reactive.session.cookie.http-only:false", "server.reactive.session.cookie.secure:false", - "server.reactive.session.cookie.same-site:strict") - .run(assertExchangeWithSession((exchange) -> { - List cookies = exchange.getResponse().getCookies().get("JSESSIONID"); - assertThat(cookies).isNotEmpty(); - assertThat(cookies).allMatch((cookie) -> cookie.getDomain().equals(".example.com")); - assertThat(cookies).allMatch((cookie) -> cookie.getPath().equals("/example")); - assertThat(cookies).allMatch((cookie) -> cookie.getMaxAge().equals(Duration.ofSeconds(60))); - assertThat(cookies).allMatch((cookie) -> !cookie.isHttpOnly()); - assertThat(cookies).allMatch((cookie) -> !cookie.isSecure()); - assertThat(cookies).allMatch((cookie) -> cookie.getSameSite().equals("Strict")); - })); + .withConfiguration( + AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)) + .withUserConfiguration(Config.class) + .withPropertyValues("spring.session.store-type=redis", "spring.redis.host=" + redis.getHost(), + "spring.redis.port=" + redis.getFirstMappedPort(), "spring.session.store-type=redis", + "server.reactive.session.cookie.name:JSESSIONID", + "server.reactive.session.cookie.domain:.example.com", + "server.reactive.session.cookie.path:/example", "server.reactive.session.cookie.max-age:60", + "server.reactive.session.cookie.http-only:false", "server.reactive.session.cookie.secure:false", + "server.reactive.session.cookie.same-site:strict") + .run(assertExchangeWithSession((exchange) -> { + List cookies = exchange.getResponse().getCookies().get("JSESSIONID"); + assertThat(cookies).isNotEmpty(); + assertThat(cookies).allMatch((cookie) -> cookie.getDomain().equals(".example.com")); + assertThat(cookies).allMatch((cookie) -> cookie.getPath().equals("/example")); + assertThat(cookies).allMatch((cookie) -> cookie.getMaxAge().equals(Duration.ofSeconds(60))); + assertThat(cookies).allMatch((cookie) -> !cookie.isHttpOnly()); + assertThat(cookies).allMatch((cookie) -> !cookie.isSecure()); + assertThat(cookies).allMatch((cookie) -> cookie.getSameSite().equals("Strict")); + })); } private ContextConsumer validateSpringSessionUsesRedis(String namespace, diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcast4Tests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcast4Tests.java index eb1261f139..b933108a24 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcast4Tests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcast4Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,9 +45,8 @@ import static org.assertj.core.api.Assertions.assertThat; class SessionAutoConfigurationHazelcast4Tests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class, SessionAutoConfiguration.class)) - .withPropertyValues( - "spring.hazelcast.config=org/springframework/boot/autoconfigure/session/hazelcast-4.xml"); + .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class, SessionAutoConfiguration.class)) + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/session/hazelcast-4.xml"); @Test void defaultConfig() { @@ -57,9 +56,9 @@ class SessionAutoConfigurationHazelcast4Tests extends AbstractSessionAutoConfigu @Test void defaultConfigWithUniqueStoreImplementation() { this.contextRunner - .withClassLoader(new FilteredClassLoader(JdbcIndexedSessionRepository.class, - RedisIndexedSessionRepository.class, MongoIndexedSessionRepository.class)) - .run(this::validateDefaultConfig); + .withClassLoader(new FilteredClassLoader(JdbcIndexedSessionRepository.class, + RedisIndexedSessionRepository.class, MongoIndexedSessionRepository.class)) + .run(this::validateDefaultConfig); } private void validateDefaultConfig(AssertableWebApplicationContext context) { @@ -69,29 +68,31 @@ class SessionAutoConfigurationHazelcast4Tests extends AbstractSessionAutoConfigu @Test void customMapName() { this.contextRunner - .withPropertyValues("spring.session.store-type=hazelcast", - "spring.session.hazelcast.map-name=foo:bar:biz") - .run((context) -> validateSessionRepository(context, Hazelcast4IndexedSessionRepository.class)); + .withPropertyValues("spring.session.store-type=hazelcast", "spring.session.hazelcast.map-name=foo:bar:biz") + .run((context) -> validateSessionRepository(context, Hazelcast4IndexedSessionRepository.class)); } @Test void customFlushMode() { - this.contextRunner.withPropertyValues("spring.session.store-type=hazelcast", - "spring.session.hazelcast.flush-mode=immediate").run((context) -> { - Hazelcast4IndexedSessionRepository repository = validateSessionRepository(context, - Hazelcast4IndexedSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("flushMode", FlushMode.IMMEDIATE); - }); + this.contextRunner + .withPropertyValues("spring.session.store-type=hazelcast", "spring.session.hazelcast.flush-mode=immediate") + .run((context) -> { + Hazelcast4IndexedSessionRepository repository = validateSessionRepository(context, + Hazelcast4IndexedSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("flushMode", FlushMode.IMMEDIATE); + }); } @Test void customSaveMode() { - this.contextRunner.withPropertyValues("spring.session.store-type=hazelcast", - "spring.session.hazelcast.save-mode=on-get-attribute").run((context) -> { - Hazelcast4IndexedSessionRepository repository = validateSessionRepository(context, - Hazelcast4IndexedSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("saveMode", SaveMode.ON_GET_ATTRIBUTE); - }); + this.contextRunner + .withPropertyValues("spring.session.store-type=hazelcast", + "spring.session.hazelcast.save-mode=on-get-attribute") + .run((context) -> { + Hazelcast4IndexedSessionRepository repository = validateSessionRepository(context, + Hazelcast4IndexedSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("saveMode", SaveMode.ON_GET_ATTRIBUTE); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java index 857a04505a..37076ad13e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,8 @@ import static org.mockito.Mockito.mock; class SessionAutoConfigurationHazelcastTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)) - .withUserConfiguration(HazelcastConfiguration.class); + .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)) + .withUserConfiguration(HazelcastConfiguration.class); @Test void defaultConfig() { @@ -58,19 +58,19 @@ class SessionAutoConfigurationHazelcastTests extends AbstractSessionAutoConfigur @Test void defaultConfigWithUniqueStoreImplementation() { this.contextRunner - .withClassLoader(new FilteredClassLoader(JdbcIndexedSessionRepository.class, - RedisIndexedSessionRepository.class, MongoIndexedSessionRepository.class)) - .run(this::validateDefaultConfig); + .withClassLoader(new FilteredClassLoader(JdbcIndexedSessionRepository.class, + RedisIndexedSessionRepository.class, MongoIndexedSessionRepository.class)) + .run(this::validateDefaultConfig); } @Test void defaultConfigWithCustomTimeout() { this.contextRunner.withPropertyValues("spring.session.store-type=hazelcast", "spring.session.timeout=1m") - .run((context) -> { - Hazelcast4IndexedSessionRepository repository = validateSessionRepository(context, - Hazelcast4IndexedSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", 60); - }); + .run((context) -> { + Hazelcast4IndexedSessionRepository repository = validateSessionRepository(context, + Hazelcast4IndexedSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", 60); + }); } private void validateDefaultConfig(AssertableWebApplicationContext context) { @@ -84,32 +84,36 @@ class SessionAutoConfigurationHazelcastTests extends AbstractSessionAutoConfigur @Test void customMapName() { - this.contextRunner.withPropertyValues("spring.session.store-type=hazelcast", - "spring.session.hazelcast.map-name=foo:bar:biz").run((context) -> { - validateSessionRepository(context, Hazelcast4IndexedSessionRepository.class); - HazelcastInstance hazelcastInstance = context.getBean(HazelcastInstance.class); - then(hazelcastInstance).should().getMap("foo:bar:biz"); - }); + this.contextRunner + .withPropertyValues("spring.session.store-type=hazelcast", "spring.session.hazelcast.map-name=foo:bar:biz") + .run((context) -> { + validateSessionRepository(context, Hazelcast4IndexedSessionRepository.class); + HazelcastInstance hazelcastInstance = context.getBean(HazelcastInstance.class); + then(hazelcastInstance).should().getMap("foo:bar:biz"); + }); } @Test void customFlushMode() { - this.contextRunner.withPropertyValues("spring.session.store-type=hazelcast", - "spring.session.hazelcast.flush-mode=immediate").run((context) -> { - Hazelcast4IndexedSessionRepository repository = validateSessionRepository(context, - Hazelcast4IndexedSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("flushMode", FlushMode.IMMEDIATE); - }); + this.contextRunner + .withPropertyValues("spring.session.store-type=hazelcast", "spring.session.hazelcast.flush-mode=immediate") + .run((context) -> { + Hazelcast4IndexedSessionRepository repository = validateSessionRepository(context, + Hazelcast4IndexedSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("flushMode", FlushMode.IMMEDIATE); + }); } @Test void customSaveMode() { - this.contextRunner.withPropertyValues("spring.session.store-type=hazelcast", - "spring.session.hazelcast.save-mode=on-get-attribute").run((context) -> { - Hazelcast4IndexedSessionRepository repository = validateSessionRepository(context, - Hazelcast4IndexedSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("saveMode", SaveMode.ON_GET_ATTRIBUTE); - }); + this.contextRunner + .withPropertyValues("spring.session.store-type=hazelcast", + "spring.session.hazelcast.save-mode=on-get-attribute") + .run((context) -> { + Hazelcast4IndexedSessionRepository repository = validateSessionRepository(context, + Hazelcast4IndexedSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("saveMode", SaveMode.ON_GET_ATTRIBUTE); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationIntegrationTests.java index 186f760209..25bf2ceb9d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,9 +40,9 @@ import static org.mockito.Mockito.mock; class SessionAutoConfigurationIntegrationTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, SessionAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true"); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, SessionAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test void severalCandidatesWithNoSessionStore() { @@ -50,29 +50,29 @@ class SessionAutoConfigurationIntegrationTests extends AbstractSessionAutoConfig assertThat(context).hasFailed(); assertThat(context).getFailure().hasRootCauseInstanceOf(NonUniqueSessionRepositoryException.class); assertThat(context).getFailure() - .hasMessageContaining("Multiple session repository candidates are available"); + .hasMessageContaining("Multiple session repository candidates are available"); assertThat(context).getFailure() - .hasMessageContaining("set the 'spring.session.store-type' property accordingly"); + .hasMessageContaining("set the 'spring.session.store-type' property accordingly"); }); } @Test void severalCandidatesWithWrongSessionStore() { this.contextRunner.withUserConfiguration(HazelcastConfiguration.class) - .withPropertyValues("spring.session.store-type=redis").run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasCauseInstanceOf(SessionRepositoryUnavailableException.class); - assertThat(context).getFailure() - .hasMessageContaining("No session repository could be auto-configured"); - assertThat(context).getFailure().hasMessageContaining("session store type is 'redis'"); - }); + .withPropertyValues("spring.session.store-type=redis") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().hasCauseInstanceOf(SessionRepositoryUnavailableException.class); + assertThat(context).getFailure().hasMessageContaining("No session repository could be auto-configured"); + assertThat(context).getFailure().hasMessageContaining("session store type is 'redis'"); + }); } @Test void severalCandidatesWithValidSessionStore() { this.contextRunner.withUserConfiguration(HazelcastConfiguration.class) - .withPropertyValues("spring.session.store-type=jdbc") - .run((context) -> validateSessionRepository(context, JdbcIndexedSessionRepository.class)); + .withPropertyValues("spring.session.store-type=jdbc") + .run((context) -> validateSessionRepository(context, JdbcIndexedSessionRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java index 069c2a782f..508e3ad3bf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,10 +63,10 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, - SessionAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true"); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, + SessionAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test void defaultConfig() { @@ -76,9 +76,9 @@ class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfiguration @Test void defaultConfigWithUniqueStoreImplementation() { this.contextRunner - .withClassLoader(new FilteredClassLoader(HazelcastIndexedSessionRepository.class, - MongoIndexedSessionRepository.class, RedisIndexedSessionRepository.class)) - .run(this::validateDefaultConfig); + .withClassLoader(new FilteredClassLoader(HazelcastIndexedSessionRepository.class, + MongoIndexedSessionRepository.class, RedisIndexedSessionRepository.class)) + .run(this::validateDefaultConfig); } private void validateDefaultConfig(AssertableWebApplicationContext context) { @@ -88,115 +88,115 @@ class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfiguration (int) new ServerProperties().getServlet().getSession().getTimeout().getSeconds()); assertThat(repository).hasFieldOrPropertyWithValue("tableName", "SPRING_SESSION"); assertThat(context.getBean(JdbcSessionProperties.class).getInitializeSchema()) - .isEqualTo(DatabaseInitializationMode.EMBEDDED); + .isEqualTo(DatabaseInitializationMode.EMBEDDED); assertThat(context.getBean(JdbcOperations.class).queryForList("select * from SPRING_SESSION")).isEmpty(); SpringBootJdbcHttpSessionConfiguration configuration = context - .getBean(SpringBootJdbcHttpSessionConfiguration.class); + .getBean(SpringBootJdbcHttpSessionConfiguration.class); assertThat(configuration).hasFieldOrPropertyWithValue("cleanupCron", "0 * * * * *"); } @Test void filterOrderCanBeCustomized() { this.contextRunner - .withPropertyValues("spring.session.store-type=jdbc", "spring.session.servlet.filter-order=123") - .run((context) -> { - FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); - assertThat(registration.getOrder()).isEqualTo(123); - }); + .withPropertyValues("spring.session.store-type=jdbc", "spring.session.servlet.filter-order=123") + .run((context) -> { + FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); + assertThat(registration.getOrder()).isEqualTo(123); + }); } @Test void disableDataSourceInitializer() { this.contextRunner - .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.initialize-schema=never") - .run((context) -> { - assertThat(context).doesNotHaveBean(JdbcSessionDataSourceScriptDatabaseInitializer.class); - JdbcIndexedSessionRepository repository = validateSessionRepository(context, - JdbcIndexedSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("tableName", "SPRING_SESSION"); - assertThat(context.getBean(JdbcSessionProperties.class).getInitializeSchema()) - .isEqualTo(DatabaseInitializationMode.NEVER); - assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy( - () -> context.getBean(JdbcOperations.class).queryForList("select * from SPRING_SESSION")); - }); + .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.initialize-schema=never") + .run((context) -> { + assertThat(context).doesNotHaveBean(JdbcSessionDataSourceScriptDatabaseInitializer.class); + JdbcIndexedSessionRepository repository = validateSessionRepository(context, + JdbcIndexedSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("tableName", "SPRING_SESSION"); + assertThat(context.getBean(JdbcSessionProperties.class).getInitializeSchema()) + .isEqualTo(DatabaseInitializationMode.NEVER); + assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy( + () -> context.getBean(JdbcOperations.class).queryForList("select * from SPRING_SESSION")); + }); } @Test void customTimeout() { this.contextRunner.withPropertyValues("spring.session.store-type=jdbc", "spring.session.timeout=1m") - .run((context) -> { - JdbcIndexedSessionRepository repository = validateSessionRepository(context, - JdbcIndexedSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", 60); - }); + .run((context) -> { + JdbcIndexedSessionRepository repository = validateSessionRepository(context, + JdbcIndexedSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", 60); + }); } @Test void customTableName() { this.contextRunner - .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.table-name=FOO_BAR", - "spring.session.jdbc.schema=classpath:session/custom-schema-h2.sql") - .run((context) -> { - JdbcIndexedSessionRepository repository = validateSessionRepository(context, - JdbcIndexedSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("tableName", "FOO_BAR"); - assertThat(context.getBean(JdbcSessionProperties.class).getInitializeSchema()) - .isEqualTo(DatabaseInitializationMode.EMBEDDED); - assertThat(context.getBean(JdbcOperations.class).queryForList("select * from FOO_BAR")).isEmpty(); - }); + .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.table-name=FOO_BAR", + "spring.session.jdbc.schema=classpath:session/custom-schema-h2.sql") + .run((context) -> { + JdbcIndexedSessionRepository repository = validateSessionRepository(context, + JdbcIndexedSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("tableName", "FOO_BAR"); + assertThat(context.getBean(JdbcSessionProperties.class).getInitializeSchema()) + .isEqualTo(DatabaseInitializationMode.EMBEDDED); + assertThat(context.getBean(JdbcOperations.class).queryForList("select * from FOO_BAR")).isEmpty(); + }); } @Test void customCleanupCron() { this.contextRunner - .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.cleanup-cron=0 0 12 * * *") - .run((context) -> { - assertThat(context.getBean(JdbcSessionProperties.class).getCleanupCron()).isEqualTo("0 0 12 * * *"); - SpringBootJdbcHttpSessionConfiguration configuration = context - .getBean(SpringBootJdbcHttpSessionConfiguration.class); - assertThat(configuration).hasFieldOrPropertyWithValue("cleanupCron", "0 0 12 * * *"); - }); + .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.cleanup-cron=0 0 12 * * *") + .run((context) -> { + assertThat(context.getBean(JdbcSessionProperties.class).getCleanupCron()).isEqualTo("0 0 12 * * *"); + SpringBootJdbcHttpSessionConfiguration configuration = context + .getBean(SpringBootJdbcHttpSessionConfiguration.class); + assertThat(configuration).hasFieldOrPropertyWithValue("cleanupCron", "0 0 12 * * *"); + }); } @Test void customFlushMode() { this.contextRunner - .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.flush-mode=immediate") - .run((context) -> { - assertThat(context.getBean(JdbcSessionProperties.class).getFlushMode()) - .isEqualTo(FlushMode.IMMEDIATE); - SpringBootJdbcHttpSessionConfiguration configuration = context - .getBean(SpringBootJdbcHttpSessionConfiguration.class); - assertThat(configuration).hasFieldOrPropertyWithValue("flushMode", FlushMode.IMMEDIATE); - }); + .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.flush-mode=immediate") + .run((context) -> { + assertThat(context.getBean(JdbcSessionProperties.class).getFlushMode()).isEqualTo(FlushMode.IMMEDIATE); + SpringBootJdbcHttpSessionConfiguration configuration = context + .getBean(SpringBootJdbcHttpSessionConfiguration.class); + assertThat(configuration).hasFieldOrPropertyWithValue("flushMode", FlushMode.IMMEDIATE); + }); } @Test void customSaveMode() { this.contextRunner - .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.save-mode=on-get-attribute") - .run((context) -> { - assertThat(context.getBean(JdbcSessionProperties.class).getSaveMode()) - .isEqualTo(SaveMode.ON_GET_ATTRIBUTE); - SpringBootJdbcHttpSessionConfiguration configuration = context - .getBean(SpringBootJdbcHttpSessionConfiguration.class); - assertThat(configuration).hasFieldOrPropertyWithValue("saveMode", SaveMode.ON_GET_ATTRIBUTE); - }); + .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.save-mode=on-get-attribute") + .run((context) -> { + assertThat(context.getBean(JdbcSessionProperties.class).getSaveMode()) + .isEqualTo(SaveMode.ON_GET_ATTRIBUTE); + SpringBootJdbcHttpSessionConfiguration configuration = context + .getBean(SpringBootJdbcHttpSessionConfiguration.class); + assertThat(configuration).hasFieldOrPropertyWithValue("saveMode", SaveMode.ON_GET_ATTRIBUTE); + }); } @Test void sessionDataSourceIsUsedWhenAvailable() { this.contextRunner.withUserConfiguration(SessionDataSourceConfiguration.class) - .withPropertyValues("spring.session.store-type=jdbc").run((context) -> { - JdbcIndexedSessionRepository repository = validateSessionRepository(context, - JdbcIndexedSessionRepository.class); - DataSource sessionDataSource = context.getBean("sessionDataSource", DataSource.class); - assertThat(repository).extracting("jdbcOperations.dataSource").isEqualTo(sessionDataSource); - assertThat(context.getBean(JdbcSessionDataSourceScriptDatabaseInitializer.class)) - .hasFieldOrPropertyWithValue("dataSource", sessionDataSource); - assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy( - () -> context.getBean(JdbcOperations.class).queryForList("select * from SPRING_SESSION")); - }); + .withPropertyValues("spring.session.store-type=jdbc") + .run((context) -> { + JdbcIndexedSessionRepository repository = validateSessionRepository(context, + JdbcIndexedSessionRepository.class); + DataSource sessionDataSource = context.getBean("sessionDataSource", DataSource.class); + assertThat(repository).extracting("jdbcOperations.dataSource").isEqualTo(sessionDataSource); + assertThat(context.getBean(JdbcSessionDataSourceScriptDatabaseInitializer.class)) + .hasFieldOrPropertyWithValue("dataSource", sessionDataSource); + assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy( + () -> context.getBean(JdbcOperations.class).queryForList("select * from SPRING_SESSION")); + }); } @Test @@ -207,7 +207,7 @@ class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfiguration assertThat(sessionRepositoryNames).isNotEmpty(); for (String sessionRepositoryName : sessionRepositoryNames) { assertThat(beanFactory.getBeanDefinition(sessionRepositoryName).getDependsOn()) - .contains("jdbcSessionDataSourceScriptDatabaseInitializer"); + .contains("jdbcSessionDataSourceScriptDatabaseInitializer"); } }); } @@ -215,45 +215,42 @@ class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfiguration @Test void sessionRepositoryBeansDependOnFlyway() { this.contextRunner.withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) - .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.initialize-schema=never") - .run((context) -> { - ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - String[] sessionRepositoryNames = beanFactory - .getBeanNamesForType(JdbcIndexedSessionRepository.class); - assertThat(sessionRepositoryNames).isNotEmpty(); - for (String sessionRepositoryName : sessionRepositoryNames) { - assertThat(beanFactory.getBeanDefinition(sessionRepositoryName).getDependsOn()) - .contains("flyway", "flywayInitializer"); - } - }); + .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.initialize-schema=never") + .run((context) -> { + ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); + String[] sessionRepositoryNames = beanFactory.getBeanNamesForType(JdbcIndexedSessionRepository.class); + assertThat(sessionRepositoryNames).isNotEmpty(); + for (String sessionRepositoryName : sessionRepositoryNames) { + assertThat(beanFactory.getBeanDefinition(sessionRepositoryName).getDependsOn()).contains("flyway", + "flywayInitializer"); + } + }); } @Test void sessionRepositoryBeansDependOnLiquibase() { this.contextRunner.withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)) - .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.initialize-schema=never") - .run((context) -> { - ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - String[] sessionRepositoryNames = beanFactory - .getBeanNamesForType(JdbcIndexedSessionRepository.class); - assertThat(sessionRepositoryNames).isNotEmpty(); - for (String sessionRepositoryName : sessionRepositoryNames) { - assertThat(beanFactory.getBeanDefinition(sessionRepositoryName).getDependsOn()) - .contains("liquibase"); - } - }); + .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.initialize-schema=never") + .run((context) -> { + ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); + String[] sessionRepositoryNames = beanFactory.getBeanNamesForType(JdbcIndexedSessionRepository.class); + assertThat(sessionRepositoryNames).isNotEmpty(); + for (String sessionRepositoryName : sessionRepositoryNames) { + assertThat(beanFactory.getBeanDefinition(sessionRepositoryName).getDependsOn()) + .contains("liquibase"); + } + }); } @Test void whenTheUserDefinesTheirOwnJdbcSessionDatabaseInitializerThenTheAutoConfiguredInitializerBacksOff() { this.contextRunner.withUserConfiguration(CustomJdbcSessionDatabaseInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withPropertyValues("spring.session.store-type=jdbc") - .run((context) -> assertThat(context) - .hasSingleBean(JdbcSessionDataSourceScriptDatabaseInitializer.class) - .doesNotHaveBean("jdbcSessionDataSourceScriptDatabaseInitializer") - .hasBean("customInitializer")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withPropertyValues("spring.session.store-type=jdbc") + .run((context) -> assertThat(context).hasSingleBean(JdbcSessionDataSourceScriptDatabaseInitializer.class) + .doesNotHaveBean("jdbcSessionDataSourceScriptDatabaseInitializer") + .hasBean("customInitializer")); } @Test @@ -261,23 +258,22 @@ class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfiguration @SuppressWarnings("deprecation") void whenTheUserDefinesTheirOwnJdbcSessionDataSourceInitializerThenTheAutoConfiguredInitializerBacksOff() { this.contextRunner.withUserConfiguration(CustomJdbcSessionDataSourceInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withPropertyValues("spring.session.store-type=jdbc") - .run((context) -> assertThat(context) - .doesNotHaveBean(JdbcSessionDataSourceScriptDatabaseInitializer.class) - .hasSingleBean(JdbcSessionDataSourceInitializer.class).hasBean("customInitializer")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withPropertyValues("spring.session.store-type=jdbc") + .run((context) -> assertThat(context).doesNotHaveBean(JdbcSessionDataSourceScriptDatabaseInitializer.class) + .hasSingleBean(JdbcSessionDataSourceInitializer.class) + .hasBean("customInitializer")); } @Test void whenTheUserDefinesTheirOwnDatabaseInitializerThenTheAutoConfiguredJdbcSessionInitializerRemains() { this.contextRunner.withUserConfiguration(CustomDatabaseInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withPropertyValues("spring.session.store-type=jdbc") - .run((context) -> assertThat(context) - .hasSingleBean(JdbcSessionDataSourceScriptDatabaseInitializer.class) - .hasBean("customInitializer")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withPropertyValues("spring.session.store-type=jdbc") + .run((context) -> assertThat(context).hasSingleBean(JdbcSessionDataSourceScriptDatabaseInitializer.class) + .hasBean("customInitializer")); } @Configuration diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationMongoTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationMongoTests.java index 0adbc0b8af..0740085792 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationMongoTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationMongoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,39 +49,39 @@ class SessionAutoConfigurationMongoTests extends AbstractSessionAutoConfiguratio @Container static final MongoDBContainer mongoDB = new MongoDBContainer(DockerImageNames.mongo()).withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(5)); + .withStartupTimeout(Duration.ofMinutes(5)); private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - SessionAutoConfiguration.class)) - .withPropertyValues("spring.data.mongodb.uri=" + mongoDB.getReplicaSetUrl(), - "spring.mongodb.embedded.version=3.5.5"); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + SessionAutoConfiguration.class)) + .withPropertyValues("spring.data.mongodb.uri=" + mongoDB.getReplicaSetUrl(), + "spring.mongodb.embedded.version=3.5.5"); @Test void defaultConfig() { this.contextRunner.withPropertyValues("spring.session.store-type=mongodb") - .run(validateSpringSessionUsesMongo("sessions")); + .run(validateSpringSessionUsesMongo("sessions")); } @Test void defaultConfigWithUniqueStoreImplementation() { this.contextRunner - .withClassLoader(new FilteredClassLoader(HazelcastIndexedSessionRepository.class, - JdbcIndexedSessionRepository.class, RedisIndexedSessionRepository.class)) - .run(validateSpringSessionUsesMongo("sessions")); + .withClassLoader(new FilteredClassLoader(HazelcastIndexedSessionRepository.class, + JdbcIndexedSessionRepository.class, RedisIndexedSessionRepository.class)) + .run(validateSpringSessionUsesMongo("sessions")); } @Test void defaultConfigWithCustomTimeout() { this.contextRunner.withPropertyValues("spring.session.store-type=mongodb", "spring.session.timeout=1m") - .run(validateSpringSessionUsesMongo("sessions", Duration.ofMinutes(1))); + .run(validateSpringSessionUsesMongo("sessions", Duration.ofMinutes(1))); } @Test void mongoSessionStoreWithCustomizations() { this.contextRunner - .withPropertyValues("spring.session.store-type=mongodb", "spring.session.mongodb.collection-name=foo") - .run(validateSpringSessionUsesMongo("foo")); + .withPropertyValues("spring.session.store-type=mongodb", "spring.session.mongodb.collection-name=foo") + .run(validateSpringSessionUsesMongo("foo")); } private ContextConsumer validateSpringSessionUsesMongo(String collectionName) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java index 418fd7f88b..25da13a270 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,80 +57,80 @@ class SessionAutoConfigurationRedisTests extends AbstractSessionAutoConfiguratio @Container public static RedisContainer redis = new RedisContainer().withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(10)); + .withStartupTimeout(Duration.ofMinutes(10)); protected final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); @Test void defaultConfig() { this.contextRunner - .withPropertyValues("spring.session.store-type=redis", "spring.redis.host=" + redis.getHost(), - "spring.redis.port=" + redis.getFirstMappedPort()) - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .run(validateSpringSessionUsesRedis("spring:session:event:0:created:", FlushMode.ON_SAVE, - SaveMode.ON_SET_ATTRIBUTE, "0 * * * * *")); + .withPropertyValues("spring.session.store-type=redis", "spring.redis.host=" + redis.getHost(), + "spring.redis.port=" + redis.getFirstMappedPort()) + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) + .run(validateSpringSessionUsesRedis("spring:session:event:0:created:", FlushMode.ON_SAVE, + SaveMode.ON_SET_ATTRIBUTE, "0 * * * * *")); } @Test void defaultConfigWithUniqueStoreImplementation() { this.contextRunner - .withClassLoader(new FilteredClassLoader(HazelcastIndexedSessionRepository.class, - JdbcIndexedSessionRepository.class, MongoIndexedSessionRepository.class)) - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .withPropertyValues("spring.redis.host=" + redis.getHost(), - "spring.redis.port=" + redis.getFirstMappedPort()) - .run(validateSpringSessionUsesRedis("spring:session:event:0:created:", FlushMode.ON_SAVE, - SaveMode.ON_SET_ATTRIBUTE, "0 * * * * *")); + .withClassLoader(new FilteredClassLoader(HazelcastIndexedSessionRepository.class, + JdbcIndexedSessionRepository.class, MongoIndexedSessionRepository.class)) + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) + .withPropertyValues("spring.redis.host=" + redis.getHost(), + "spring.redis.port=" + redis.getFirstMappedPort()) + .run(validateSpringSessionUsesRedis("spring:session:event:0:created:", FlushMode.ON_SAVE, + SaveMode.ON_SET_ATTRIBUTE, "0 * * * * *")); } @Test void defaultConfigWithCustomTimeout() { this.contextRunner - .withPropertyValues("spring.session.store-type=redis", "spring.redis.host=" + redis.getHost(), - "spring.redis.port=" + redis.getFirstMappedPort(), "spring.session.timeout=1m") - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)).run((context) -> { - RedisIndexedSessionRepository repository = validateSessionRepository(context, - RedisIndexedSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", 60); - }); + .withPropertyValues("spring.session.store-type=redis", "spring.redis.host=" + redis.getHost(), + "spring.redis.port=" + redis.getFirstMappedPort(), "spring.session.timeout=1m") + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) + .run((context) -> { + RedisIndexedSessionRepository repository = validateSessionRepository(context, + RedisIndexedSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", 60); + }); } @Test void redisSessionStoreWithCustomizations() { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .withPropertyValues("spring.session.store-type=redis", "spring.session.redis.namespace=foo", - "spring.session.redis.flush-mode=immediate", "spring.session.redis.save-mode=on-get-attribute", - "spring.session.redis.cleanup-cron=0 0 12 * * *", "spring.redis.host=" + redis.getHost(), - "spring.redis.port=" + redis.getFirstMappedPort()) - .run(validateSpringSessionUsesRedis("foo:event:0:created:", FlushMode.IMMEDIATE, - SaveMode.ON_GET_ATTRIBUTE, "0 0 12 * * *")); + .withPropertyValues("spring.session.store-type=redis", "spring.session.redis.namespace=foo", + "spring.session.redis.flush-mode=immediate", "spring.session.redis.save-mode=on-get-attribute", + "spring.session.redis.cleanup-cron=0 0 12 * * *", "spring.redis.host=" + redis.getHost(), + "spring.redis.port=" + redis.getFirstMappedPort()) + .run(validateSpringSessionUsesRedis("foo:event:0:created:", FlushMode.IMMEDIATE, SaveMode.ON_GET_ATTRIBUTE, + "0 0 12 * * *")); } @Test void redisSessionWithConfigureActionNone() { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .withPropertyValues("spring.session.store-type=redis", "spring.session.redis.configure-action=none", - "spring.redis.host=" + redis.getHost(), "spring.redis.port=" + redis.getFirstMappedPort()) - .run(validateStrategy(ConfigureRedisAction.NO_OP.getClass())); + .withPropertyValues("spring.session.store-type=redis", "spring.session.redis.configure-action=none", + "spring.redis.host=" + redis.getHost(), "spring.redis.port=" + redis.getFirstMappedPort()) + .run(validateStrategy(ConfigureRedisAction.NO_OP.getClass())); } @Test void redisSessionWithDefaultConfigureActionNone() { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .withPropertyValues("spring.session.store-type=redis", "spring.redis.host=" + redis.getHost(), - "spring.redis.port=" + redis.getFirstMappedPort()) - .run(validateStrategy(ConfigureNotifyKeyspaceEventsAction.class, - entry("notify-keyspace-events", "gxE"))); + .withPropertyValues("spring.session.store-type=redis", "spring.redis.host=" + redis.getHost(), + "spring.redis.port=" + redis.getFirstMappedPort()) + .run(validateStrategy(ConfigureNotifyKeyspaceEventsAction.class, entry("notify-keyspace-events", "gxE"))); } @Test void redisSessionWithCustomConfigureRedisActionBean() { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .withUserConfiguration(MaxEntriesRedisAction.class) - .withPropertyValues("spring.session.store-type=redis", "spring.redis.host=" + redis.getHost(), - "spring.redis.port=" + redis.getFirstMappedPort()) - .run(validateStrategy(MaxEntriesRedisAction.class, entry("set-max-intset-entries", "1024"))); + .withUserConfiguration(MaxEntriesRedisAction.class) + .withPropertyValues("spring.session.store-type=redis", "spring.redis.host=" + redis.getHost(), + "spring.redis.port=" + redis.getFirstMappedPort()) + .run(validateStrategy(MaxEntriesRedisAction.class, entry("set-max-intset-entries", "1024"))); } @@ -144,7 +144,7 @@ class SessionAutoConfigurationRedisTests extends AbstractSessionAutoConfiguratio assertThat(repository.getSessionCreatedChannelPrefix()).isEqualTo(sessionCreatedChannelPrefix); assertThat(repository).hasFieldOrPropertyWithValue("flushMode", flushMode); SpringBootRedisHttpSessionConfiguration configuration = context - .getBean(SpringBootRedisHttpSessionConfiguration.class); + .getBean(SpringBootRedisHttpSessionConfiguration.class); assertThat(configuration).hasFieldOrPropertyWithValue("cleanupCron", cleanupCron); assertThat(repository).hasFieldOrPropertyWithValue("saveMode", saveMode); }; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java index 4d559fb868..80e8b85db7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,7 +58,7 @@ import static org.mockito.Mockito.mock; class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); @Test void contextFailsIfMultipleStoresAreAvailable() { @@ -66,7 +66,7 @@ class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurationTest assertThat(context).hasFailed(); assertThat(context).getFailure().hasRootCauseInstanceOf(NonUniqueSessionRepositoryException.class); assertThat(context).getFailure() - .hasMessageContaining("Multiple session repository candidates are available"); + .hasMessageContaining("Multiple session repository candidates are available"); }); } @@ -83,16 +83,17 @@ class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurationTest @Test void autoConfigurationDisabledIfStoreTypeSetToNone() { this.contextRunner.withPropertyValues("spring.session.store-type=none") - .run((context) -> assertThat(context).doesNotHaveBean(SessionRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(SessionRepository.class)); } @Test void backOffIfSessionRepositoryIsPresent() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) - .withPropertyValues("spring.session.store-type=redis").run((context) -> { - MapSessionRepository repository = validateSessionRepository(context, MapSessionRepository.class); - assertThat(context).getBean("mySessionRepository").isSameAs(repository); - }); + .withPropertyValues("spring.session.store-type=redis") + .run((context) -> { + MapSessionRepository repository = validateSessionRepository(context, MapSessionRepository.class); + assertThat(context).getBean("mySessionRepository").isSameAs(repository); + }); } @Test @@ -101,69 +102,73 @@ class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurationTest FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); assertThat(registration.getFilter()).isSameAs(context.getBean(SessionRepositoryFilter.class)); assertThat(registration) - .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) - .containsOnly(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST); + .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) + .containsOnly(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST); }); } @Test void filterOrderCanBeCustomizedWithCustomStore() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) - .withPropertyValues("spring.session.servlet.filter-order=123").run((context) -> { - FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); - assertThat(registration.getOrder()).isEqualTo(123); - }); + .withPropertyValues("spring.session.servlet.filter-order=123") + .run((context) -> { + FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); + assertThat(registration.getOrder()).isEqualTo(123); + }); } @Test void filterDispatcherTypesCanBeCustomized() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) - .withPropertyValues("spring.session.servlet.filter-dispatcher-types=error, request").run((context) -> { - FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); - assertThat(registration) - .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) - .containsOnly(DispatcherType.ERROR, DispatcherType.REQUEST); - }); + .withPropertyValues("spring.session.servlet.filter-dispatcher-types=error, request") + .run((context) -> { + FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); + assertThat(registration) + .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) + .containsOnly(DispatcherType.ERROR, DispatcherType.REQUEST); + }); } @Test void emptyFilterDispatcherTypesDoNotThrowException() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) - .withPropertyValues("spring.session.servlet.filter-dispatcher-types=").run((context) -> { - FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); - assertThat(registration) - .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) - .isEmpty(); - }); + .withPropertyValues("spring.session.servlet.filter-dispatcher-types=") + .run((context) -> { + FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); + assertThat(registration) + .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) + .isEmpty(); + }); } @Test void sessionCookieConfigurationIsAppliedToAutoConfiguredCookieSerializer() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) - .withPropertyValues("server.servlet.session.cookie.name=sid", - "server.servlet.session.cookie.domain=spring", "server.servlet.session.cookie.path=/test", - "server.servlet.session.cookie.httpOnly=false", "server.servlet.session.cookie.secure=false", - "server.servlet.session.cookie.maxAge=10s", "server.servlet.session.cookie.sameSite=strict") - .run((context) -> { - DefaultCookieSerializer cookieSerializer = context.getBean(DefaultCookieSerializer.class); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue("cookieName", "sid"); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue("domainName", "spring"); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue("cookiePath", "/test"); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue("useHttpOnlyCookie", false); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue("useSecureCookie", false); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue("cookieMaxAge", 10); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue("sameSite", "Strict"); - }); + .withPropertyValues("server.servlet.session.cookie.name=sid", "server.servlet.session.cookie.domain=spring", + "server.servlet.session.cookie.path=/test", "server.servlet.session.cookie.httpOnly=false", + "server.servlet.session.cookie.secure=false", "server.servlet.session.cookie.maxAge=10s", + "server.servlet.session.cookie.sameSite=strict") + .run((context) -> { + DefaultCookieSerializer cookieSerializer = context.getBean(DefaultCookieSerializer.class); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("cookieName", "sid"); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("domainName", "spring"); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("cookiePath", "/test"); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("useHttpOnlyCookie", false); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("useSecureCookie", false); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("cookieMaxAge", 10); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("sameSite", "Strict"); + }); } @Test void autoConfiguredCookieSerializerIsUsedBySessionRepositoryFilter() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) - .withPropertyValues("server.port=0").run((context) -> { - SessionRepositoryFilter filter = context.getBean(SessionRepositoryFilter.class); - assertThat(filter).extracting("httpSessionIdResolver.cookieSerializer") - .isSameAs(context.getBean(DefaultCookieSerializer.class)); - }); + .withPropertyValues("server.port=0") + .run((context) -> { + SessionRepositoryFilter filter = context.getBean(SessionRepositoryFilter.class); + assertThat(filter).extracting("httpSessionIdResolver.cookieSerializer") + .isSameAs(context.getBean(DefaultCookieSerializer.class)); + }); } @Test @@ -177,19 +182,19 @@ class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurationTest @Test void cookiesSerializerIsAutoConfiguredWhenUserConfiguresCookieHttpSessionIdResolver() { this.contextRunner.withUserConfiguration(UserProvidedCookieHttpSessionStrategyConfiguration.class) - .run((context) -> assertThat(context.getBeansOfType(DefaultCookieSerializer.class)).isNotEmpty()); + .run((context) -> assertThat(context.getBeansOfType(DefaultCookieSerializer.class)).isNotEmpty()); } @Test void autoConfiguredCookieSerializerBacksOffWhenUserConfiguresHeaderHttpSessionIdResolver() { this.contextRunner.withUserConfiguration(UserProvidedHeaderHttpSessionStrategyConfiguration.class) - .run((context) -> assertThat(context.getBeansOfType(DefaultCookieSerializer.class)).isEmpty()); + .run((context) -> assertThat(context.getBeansOfType(DefaultCookieSerializer.class)).isEmpty()); } @Test void autoConfiguredCookieSerializerBacksOffWhenUserConfiguresCustomHttpSessionIdResolver() { this.contextRunner.withUserConfiguration(UserProvidedCustomHttpSessionStrategyConfiguration.class) - .run((context) -> assertThat(context.getBeansOfType(DefaultCookieSerializer.class)).isEmpty()); + .run((context) -> assertThat(context.getBeansOfType(DefaultCookieSerializer.class)).isEmpty()); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationWithoutSecurityTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationWithoutSecurityTests.java index 7f8768afce..956afde4de 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationWithoutSecurityTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationWithoutSecurityTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; class SessionAutoConfigurationWithoutSecurityTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); @Test void sessionCookieConfigurationIsAppliedToAutoConfiguredCookieSerializer() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sql/init/OnDatabaseInitializationConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sql/init/OnDatabaseInitializationConditionTests.java index 8378fb2b57..fd44e19a44 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sql/init/OnDatabaseInitializationConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sql/init/OnDatabaseInitializationConditionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,7 +38,7 @@ class OnDatabaseInitializationConditionTests { void getMatchOutcomeWithPropertyNoSetMatches() { OnDatabaseInitializationCondition condition = new OnDatabaseInitializationCondition("Test", "test.init-mode"); ConditionOutcome outcome = condition - .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.another", "noise")), null); + .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.another", "noise")), null); assertThat(outcome.isMatch()).isTrue(); } @@ -46,7 +46,7 @@ class OnDatabaseInitializationConditionTests { void getMatchOutcomeWithPropertySetToAlwaysMatches() { OnDatabaseInitializationCondition condition = new OnDatabaseInitializationCondition("Test", "test.init-mode"); ConditionOutcome outcome = condition - .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode=always")), null); + .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode=always")), null); assertThat(outcome.isMatch()).isTrue(); } @@ -54,7 +54,7 @@ class OnDatabaseInitializationConditionTests { void getMatchOutcomeWithPropertySetToEmbeddedMatches() { OnDatabaseInitializationCondition condition = new OnDatabaseInitializationCondition("Test", "test.init-mode"); ConditionOutcome outcome = condition - .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode=embedded")), null); + .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode=embedded")), null); assertThat(outcome.isMatch()).isTrue(); } @@ -62,7 +62,7 @@ class OnDatabaseInitializationConditionTests { void getMatchOutcomeWithPropertySetToNeverDoesNotMatch() { OnDatabaseInitializationCondition condition = new OnDatabaseInitializationCondition("Test", "test.init-mode"); ConditionOutcome outcome = condition - .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode=never")), null); + .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode=never")), null); assertThat(outcome.isMatch()).isFalse(); } @@ -70,7 +70,7 @@ class OnDatabaseInitializationConditionTests { void getMatchOutcomeWithPropertySetToEmptyStringIsIgnored() { OnDatabaseInitializationCondition condition = new OnDatabaseInitializationCondition("Test", "test.init-mode"); ConditionOutcome outcome = condition - .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode")), null); + .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode")), null); assertThat(outcome.isMatch()).isTrue(); } @@ -79,7 +79,7 @@ class OnDatabaseInitializationConditionTests { OnDatabaseInitializationCondition condition = new OnDatabaseInitializationCondition("Test", "test.init-mode", "test.schema-mode", "test.init-schema-mode"); ConditionOutcome outcome = condition - .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-schema-mode=embedded")), null); + .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-schema-mode=embedded")), null); assertThat(outcome.isMatch()).isTrue(); assertThat(outcome.getMessage()).isEqualTo("TestDatabase Initialization test.init-schema-mode is EMBEDDED"); } @@ -88,7 +88,7 @@ class OnDatabaseInitializationConditionTests { void getMatchOutcomeHasDedicatedDescription() { OnDatabaseInitializationCondition condition = new OnDatabaseInitializationCondition("Test", "test.init-mode"); ConditionOutcome outcome = condition - .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode=embedded")), null); + .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode=embedded")), null); assertThat(outcome.getMessage()).isEqualTo("TestDatabase Initialization test.init-mode is EMBEDDED"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sql/init/SqlInitializationAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sql/init/SqlInitializationAutoConfigurationTests.java index d40130f181..f14b294333 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sql/init/SqlInitializationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sql/init/SqlInitializationAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,106 +52,111 @@ import static org.assertj.core.api.Assertions.assertThat; class SqlInitializationAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SqlInitializationAutoConfiguration.class)).withPropertyValues( - "spring.datasource.generate-unique-name:true", "spring.r2dbc.generate-unique-name:true"); + .withConfiguration(AutoConfigurations.of(SqlInitializationAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name:true", "spring.r2dbc.generate-unique-name:true"); @Test void whenNoDataSourceOrConnectionFactoryIsAvailableThenAutoConfigurationBacksOff() { this.contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class)); + .run((context) -> assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class)); } @Test void whenConnectionFactoryIsAvailableThenR2dbcInitializerIsAutoConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(R2dbcScriptDatabaseInitializer.class)); + .run((context) -> assertThat(context).hasSingleBean(R2dbcScriptDatabaseInitializer.class)); } @Test void whenConnectionFactoryIsAvailableAndModeIsNeverThenInitializerIsNotAutoConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .withInitializer(new ConditionEvaluationReportLoggingListener(LogLevel.INFO)) - .withPropertyValues("spring.sql.init.mode:never") - .run((context) -> assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class)); + .withInitializer(new ConditionEvaluationReportLoggingListener(LogLevel.INFO)) + .withPropertyValues("spring.sql.init.mode:never") + .run((context) -> assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class)); } @Test void whenDataSourceIsAvailableThenDataSourceInitializerIsAutoConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(DataSourceScriptDatabaseInitializer.class)); + .run((context) -> assertThat(context).hasSingleBean(DataSourceScriptDatabaseInitializer.class)); } @Test void whenDataSourceIsAvailableAndModeIsNeverThenThenInitializerIsNotAutoConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.sql.init.mode:never") - .run((context) -> assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class)); + .withPropertyValues("spring.sql.init.mode:never") + .run((context) -> assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class)); } @Test void whenDataSourceAndConnectionFactoryAreAvailableThenOnlyR2dbcInitializerIsAutoConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .withUserConfiguration(DataSourceAutoConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) - .hasSingleBean(DataSource.class).hasSingleBean(R2dbcScriptDatabaseInitializer.class) - .doesNotHaveBean(DataSourceScriptDatabaseInitializer.class)); + .withUserConfiguration(DataSourceAutoConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(DataSource.class) + .hasSingleBean(R2dbcScriptDatabaseInitializer.class) + .doesNotHaveBean(DataSourceScriptDatabaseInitializer.class)); } @Test void whenAnSqlInitializerIsDefinedThenInitializerIsNotAutoConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .withUserConfiguration(DataSourceAutoConfiguration.class, SqlDatabaseInitializerConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(AbstractScriptDatabaseInitializer.class) - .hasBean("customInitializer")); + .withUserConfiguration(DataSourceAutoConfiguration.class, SqlDatabaseInitializerConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(AbstractScriptDatabaseInitializer.class) + .hasBean("customInitializer")); } @Test void whenAnInitializerIsDefinedThenSqlInitializerIsStillAutoConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withUserConfiguration(DatabaseInitializerConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(SqlDataSourceScriptDatabaseInitializer.class).hasBean("customInitializer")); + .withUserConfiguration(DatabaseInitializerConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(SqlDataSourceScriptDatabaseInitializer.class) + .hasBean("customInitializer")); } @Test void whenBeanIsAnnotatedAsDependingOnDatabaseInitializationThenItDependsOnR2dbcScriptDatabaseInitializer() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .withUserConfiguration(DependsOnInitializedDatabaseConfiguration.class).run((context) -> { - BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition( + .withUserConfiguration(DependsOnInitializedDatabaseConfiguration.class) + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory() + .getBeanDefinition( "sqlInitializationAutoConfigurationTests.DependsOnInitializedDatabaseConfiguration"); - assertThat(beanDefinition.getDependsOn()) - .containsExactlyInAnyOrder("r2dbcScriptDatabaseInitializer"); - }); + assertThat(beanDefinition.getDependsOn()).containsExactlyInAnyOrder("r2dbcScriptDatabaseInitializer"); + }); } @Test void whenBeanIsAnnotatedAsDependingOnDatabaseInitializationThenItDependsOnDataSourceScriptDatabaseInitializer() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withUserConfiguration(DependsOnInitializedDatabaseConfiguration.class).run((context) -> { - BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition( + .withUserConfiguration(DependsOnInitializedDatabaseConfiguration.class) + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory() + .getBeanDefinition( "sqlInitializationAutoConfigurationTests.DependsOnInitializedDatabaseConfiguration"); - assertThat(beanDefinition.getDependsOn()) - .containsExactlyInAnyOrder("dataSourceScriptDatabaseInitializer"); - }); + assertThat(beanDefinition.getDependsOn()) + .containsExactlyInAnyOrder("dataSourceScriptDatabaseInitializer"); + }); } @Test void whenADataSourceIsAvailableAndSpringJdbcIsNotThenAutoConfigurationBacksOff() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(DatabasePopulator.class)).run((context) -> { - assertThat(context).hasSingleBean(DataSource.class); - assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class); - }); + .withClassLoader(new FilteredClassLoader(DatabasePopulator.class)) + .run((context) -> { + assertThat(context).hasSingleBean(DataSource.class); + assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class); + }); } @Test void whenAConnectionFactoryIsAvailableAndSpringR2dbcIsNotThenAutoConfigurationBacksOff() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .withClassLoader( - new FilteredClassLoader(org.springframework.r2dbc.connection.init.DatabasePopulator.class)) - .run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class); - assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class); - }); + .withClassLoader(new FilteredClassLoader(org.springframework.r2dbc.connection.init.DatabasePopulator.class)) + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class); + assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskExecutionAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskExecutionAutoConfigurationTests.java index 5b1c97250b..35d9ca4547 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskExecutionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskExecutionAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,25 +56,27 @@ import static org.mockito.Mockito.mock; class TaskExecutionAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class)); @Test void taskExecutorBuilderShouldApplyCustomSettings() { - this.contextRunner.withPropertyValues("spring.task.execution.pool.queue-capacity=10", - "spring.task.execution.pool.core-size=2", "spring.task.execution.pool.max-size=4", - "spring.task.execution.pool.allow-core-thread-timeout=true", "spring.task.execution.pool.keep-alive=5s", - "spring.task.execution.shutdown.await-termination=true", - "spring.task.execution.shutdown.await-termination-period=30s", - "spring.task.execution.thread-name-prefix=mytest-").run(assertTaskExecutor((taskExecutor) -> { - assertThat(taskExecutor).hasFieldOrPropertyWithValue("queueCapacity", 10); - assertThat(taskExecutor.getCorePoolSize()).isEqualTo(2); - assertThat(taskExecutor.getMaxPoolSize()).isEqualTo(4); - assertThat(taskExecutor).hasFieldOrPropertyWithValue("allowCoreThreadTimeOut", true); - assertThat(taskExecutor.getKeepAliveSeconds()).isEqualTo(5); - assertThat(taskExecutor).hasFieldOrPropertyWithValue("waitForTasksToCompleteOnShutdown", true); - assertThat(taskExecutor).hasFieldOrPropertyWithValue("awaitTerminationMillis", 30000L); - assertThat(taskExecutor.getThreadNamePrefix()).isEqualTo("mytest-"); - })); + this.contextRunner + .withPropertyValues("spring.task.execution.pool.queue-capacity=10", + "spring.task.execution.pool.core-size=2", "spring.task.execution.pool.max-size=4", + "spring.task.execution.pool.allow-core-thread-timeout=true", + "spring.task.execution.pool.keep-alive=5s", "spring.task.execution.shutdown.await-termination=true", + "spring.task.execution.shutdown.await-termination-period=30s", + "spring.task.execution.thread-name-prefix=mytest-") + .run(assertTaskExecutor((taskExecutor) -> { + assertThat(taskExecutor).hasFieldOrPropertyWithValue("queueCapacity", 10); + assertThat(taskExecutor.getCorePoolSize()).isEqualTo(2); + assertThat(taskExecutor.getMaxPoolSize()).isEqualTo(4); + assertThat(taskExecutor).hasFieldOrPropertyWithValue("allowCoreThreadTimeOut", true); + assertThat(taskExecutor.getKeepAliveSeconds()).isEqualTo(5); + assertThat(taskExecutor).hasFieldOrPropertyWithValue("waitForTasksToCompleteOnShutdown", true); + assertThat(taskExecutor).hasFieldOrPropertyWithValue("awaitTerminationMillis", 30000L); + assertThat(taskExecutor.getThreadNamePrefix()).isEqualTo("mytest-"); + })); } @Test @@ -82,7 +84,7 @@ class TaskExecutionAutoConfigurationTests { this.contextRunner.withUserConfiguration(CustomTaskExecutorBuilderConfig.class).run((context) -> { assertThat(context).hasSingleBean(TaskExecutorBuilder.class); assertThat(context.getBean(TaskExecutorBuilder.class)) - .isSameAs(context.getBean(CustomTaskExecutorBuilderConfig.class).taskExecutorBuilder); + .isSameAs(context.getBean(CustomTaskExecutorBuilderConfig.class).taskExecutorBuilder); }); } @@ -99,8 +101,9 @@ class TaskExecutionAutoConfigurationTests { void taskExecutorAutoConfiguredIsLazy() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(Executor.class).hasBean("applicationTaskExecutor"); - BeanDefinition beanDefinition = context.getSourceApplicationContext().getBeanFactory() - .getBeanDefinition("applicationTaskExecutor"); + BeanDefinition beanDefinition = context.getSourceApplicationContext() + .getBeanFactory() + .getBeanDefinition("applicationTaskExecutor"); assertThat(beanDefinition.isLazyInit()).isTrue(); assertThat(context).getBean("applicationTaskExecutor").isInstanceOf(ThreadPoolTaskExecutor.class); }); @@ -126,24 +129,25 @@ class TaskExecutionAutoConfigurationTests { @Test void enableAsyncUsesAutoConfiguredOneByDefault() { this.contextRunner.withPropertyValues("spring.task.execution.thread-name-prefix=task-test-") - .withUserConfiguration(AsyncConfiguration.class, TestBean.class).run((context) -> { - assertThat(context).hasSingleBean(TaskExecutor.class); - TestBean bean = context.getBean(TestBean.class); - String text = bean.echo("something").get(); - assertThat(text).contains("task-test-").contains("something"); - }); + .withUserConfiguration(AsyncConfiguration.class, TestBean.class) + .run((context) -> { + assertThat(context).hasSingleBean(TaskExecutor.class); + TestBean bean = context.getBean(TestBean.class); + String text = bean.echo("something").get(); + assertThat(text).contains("task-test-").contains("something"); + }); } @Test void enableAsyncUsesAutoConfiguredOneByDefaultEvenThoughSchedulingIsConfigured() { this.contextRunner.withPropertyValues("spring.task.execution.thread-name-prefix=task-test-") - .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) - .withUserConfiguration(AsyncConfiguration.class, SchedulingConfiguration.class, TestBean.class) - .run((context) -> { - TestBean bean = context.getBean(TestBean.class); - String text = bean.echo("something").get(); - assertThat(text).contains("task-test-").contains("something"); - }); + .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) + .withUserConfiguration(AsyncConfiguration.class, SchedulingConfiguration.class, TestBean.class) + .run((context) -> { + TestBean bean = context.getBean(TestBean.class); + String text = bean.echo("something").get(); + assertThat(text).contains("task-test-").contains("something"); + }); } private ContextConsumer assertTaskExecutor( diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfigurationTests.java index e437068987..990e8cb6db 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,8 +53,8 @@ import static org.assertj.core.api.Assertions.assertThat; class TaskSchedulingAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(TestConfiguration.class) - .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)); + .withUserConfiguration(TestConfiguration.class) + .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)); @Test void noSchedulingDoesNotExposeTaskScheduler() { @@ -63,89 +63,91 @@ class TaskSchedulingAutoConfigurationTests { @Test void noSchedulingDoesNotExposeScheduledBeanLazyInitializationExcludeFilter() { - this.contextRunner.run( - (context) -> assertThat(context).doesNotHaveBean(ScheduledBeanLazyInitializationExcludeFilter.class)); + this.contextRunner + .run((context) -> assertThat(context).doesNotHaveBean(ScheduledBeanLazyInitializationExcludeFilter.class)); } @Test void enableSchedulingWithNoTaskExecutorAutoConfiguresOne() { this.contextRunner - .withPropertyValues("spring.task.scheduling.shutdown.await-termination=true", - "spring.task.scheduling.shutdown.await-termination-period=30s", - "spring.task.scheduling.thread-name-prefix=scheduling-test-") - .withUserConfiguration(SchedulingConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(TaskExecutor.class); - TaskExecutor taskExecutor = context.getBean(TaskExecutor.class); - TestBean bean = context.getBean(TestBean.class); - assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); - assertThat(taskExecutor).hasFieldOrPropertyWithValue("waitForTasksToCompleteOnShutdown", true); - assertThat(taskExecutor).hasFieldOrPropertyWithValue("awaitTerminationMillis", 30000L); - assertThat(bean.threadNames).allMatch((name) -> name.contains("scheduling-test-")); - }); + .withPropertyValues("spring.task.scheduling.shutdown.await-termination=true", + "spring.task.scheduling.shutdown.await-termination-period=30s", + "spring.task.scheduling.thread-name-prefix=scheduling-test-") + .withUserConfiguration(SchedulingConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(TaskExecutor.class); + TaskExecutor taskExecutor = context.getBean(TaskExecutor.class); + TestBean bean = context.getBean(TestBean.class); + assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); + assertThat(taskExecutor).hasFieldOrPropertyWithValue("waitForTasksToCompleteOnShutdown", true); + assertThat(taskExecutor).hasFieldOrPropertyWithValue("awaitTerminationMillis", 30000L); + assertThat(bean.threadNames).allMatch((name) -> name.contains("scheduling-test-")); + }); } @Test void enableSchedulingWithNoTaskExecutorAppliesCustomizers() { this.contextRunner.withPropertyValues("spring.task.scheduling.thread-name-prefix=scheduling-test-") - .withUserConfiguration(SchedulingConfiguration.class, TaskSchedulerCustomizerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(TaskExecutor.class); - TestBean bean = context.getBean(TestBean.class); - assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); - assertThat(bean.threadNames).allMatch((name) -> name.contains("customized-scheduler-")); - }); + .withUserConfiguration(SchedulingConfiguration.class, TaskSchedulerCustomizerConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(TaskExecutor.class); + TestBean bean = context.getBean(TestBean.class); + assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); + assertThat(bean.threadNames).allMatch((name) -> name.contains("customized-scheduler-")); + }); } @Test void enableSchedulingWithExistingTaskSchedulerBacksOff() { this.contextRunner.withUserConfiguration(SchedulingConfiguration.class, TaskSchedulerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(TaskScheduler.class); - assertThat(context.getBean(TaskScheduler.class)).isInstanceOf(TestTaskScheduler.class); - TestBean bean = context.getBean(TestBean.class); - assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); - assertThat(bean.threadNames).containsExactly("test-1"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(TaskScheduler.class); + assertThat(context.getBean(TaskScheduler.class)).isInstanceOf(TestTaskScheduler.class); + TestBean bean = context.getBean(TestBean.class); + assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); + assertThat(bean.threadNames).containsExactly("test-1"); + }); } @Test void enableSchedulingWithExistingScheduledExecutorServiceBacksOff() { this.contextRunner - .withUserConfiguration(SchedulingConfiguration.class, ScheduledExecutorServiceConfiguration.class) - .run((context) -> { - assertThat(context).doesNotHaveBean(TaskScheduler.class); - assertThat(context).hasSingleBean(ScheduledExecutorService.class); - TestBean bean = context.getBean(TestBean.class); - assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); - assertThat(bean.threadNames).allMatch((name) -> name.contains("pool-")); - }); + .withUserConfiguration(SchedulingConfiguration.class, ScheduledExecutorServiceConfiguration.class) + .run((context) -> { + assertThat(context).doesNotHaveBean(TaskScheduler.class); + assertThat(context).hasSingleBean(ScheduledExecutorService.class); + TestBean bean = context.getBean(TestBean.class); + assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); + assertThat(bean.threadNames).allMatch((name) -> name.contains("pool-")); + }); } @Test void enableSchedulingWithConfigurerBacksOff() { this.contextRunner.withUserConfiguration(SchedulingConfiguration.class, SchedulingConfigurerConfiguration.class) - .run((context) -> { - assertThat(context).doesNotHaveBean(TaskScheduler.class); - TestBean bean = context.getBean(TestBean.class); - assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); - assertThat(bean.threadNames).containsExactly("test-1"); - }); + .run((context) -> { + assertThat(context).doesNotHaveBean(TaskScheduler.class); + TestBean bean = context.getBean(TestBean.class); + assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); + assertThat(bean.threadNames).containsExactly("test-1"); + }); } @Test void enableSchedulingWithLazyInitializationInvokeScheduledMethods() { List threadNames = new ArrayList<>(); new ApplicationContextRunner() - .withInitializer((context) -> context - .addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor())) - .withPropertyValues("spring.task.scheduling.thread-name-prefix=scheduling-test-") - .withBean(LazyTestBean.class, () -> new LazyTestBean(threadNames)) - .withUserConfiguration(SchedulingConfiguration.class) - .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)).run((context) -> { - // No lazy lookup. - Awaitility.waitAtMost(Duration.ofSeconds(3)).until(() -> !threadNames.isEmpty()); - assertThat(threadNames).allMatch((name) -> name.contains("scheduling-test-")); - }); + .withInitializer( + (context) -> context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor())) + .withPropertyValues("spring.task.scheduling.thread-name-prefix=scheduling-test-") + .withBean(LazyTestBean.class, () -> new LazyTestBean(threadNames)) + .withUserConfiguration(SchedulingConfiguration.class) + .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) + .run((context) -> { + // No lazy lookup. + Awaitility.waitAtMost(Duration.ofSeconds(3)).until(() -> !threadNames.isEmpty()); + assertThat(threadNames).allMatch((name) -> name.contains("scheduling-test-")); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java index 903e04463f..46ce5d2e10 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,8 +66,8 @@ class TemplateAvailabilityProvidersTests { @Test void createWhenApplicationContextIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TemplateAvailabilityProviders((ApplicationContext) null)) - .withMessageContaining("ClassLoader must not be null"); + .isThrownBy(() -> new TemplateAvailabilityProviders((ApplicationContext) null)) + .withMessageContaining("ClassLoader must not be null"); } @Test @@ -82,7 +82,7 @@ class TemplateAvailabilityProvidersTests { @Test void createWhenClassLoaderIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new TemplateAvailabilityProviders((ClassLoader) null)) - .withMessageContaining("ClassLoader must not be null"); + .withMessageContaining("ClassLoader must not be null"); } @Test @@ -94,8 +94,8 @@ class TemplateAvailabilityProvidersTests { @Test void createWhenProvidersIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TemplateAvailabilityProviders((Collection) null)) - .withMessageContaining("Providers must not be null"); + .isThrownBy(() -> new TemplateAvailabilityProviders((Collection) null)) + .withMessageContaining("Providers must not be null"); } @Test @@ -108,36 +108,35 @@ class TemplateAvailabilityProvidersTests { @Test void getProviderWhenApplicationContextIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.providers.getProvider(this.view, null)) - .withMessageContaining("ApplicationContext must not be null"); + .withMessageContaining("ApplicationContext must not be null"); } @Test void getProviderWhenViewIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> this.providers.getProvider(null, this.environment, this.classLoader, this.resourceLoader)) - .withMessageContaining("View must not be null"); + .isThrownBy(() -> this.providers.getProvider(null, this.environment, this.classLoader, this.resourceLoader)) + .withMessageContaining("View must not be null"); } @Test void getProviderWhenEnvironmentIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.providers.getProvider(this.view, null, this.classLoader, this.resourceLoader)) - .withMessageContaining("Environment must not be null"); + .isThrownBy(() -> this.providers.getProvider(this.view, null, this.classLoader, this.resourceLoader)) + .withMessageContaining("Environment must not be null"); } @Test void getProviderWhenClassLoaderIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.providers.getProvider(this.view, this.environment, null, this.resourceLoader)) - .withMessageContaining("ClassLoader must not be null"); + .isThrownBy(() -> this.providers.getProvider(this.view, this.environment, null, this.resourceLoader)) + .withMessageContaining("ClassLoader must not be null"); } @Test void getProviderWhenResourceLoaderIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.providers.getProvider(this.view, this.environment, this.classLoader, null)) - .withMessageContaining("ResourceLoader must not be null"); + .isThrownBy(() -> this.providers.getProvider(this.view, this.environment, this.classLoader, null)) + .withMessageContaining("ResourceLoader must not be null"); } @Test @@ -145,14 +144,14 @@ class TemplateAvailabilityProvidersTests { TemplateAvailabilityProvider found = this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); assertThat(found).isNull(); - then(this.provider).should().isTemplateAvailable(this.view, this.environment, this.classLoader, - this.resourceLoader); + then(this.provider).should() + .isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader); } @Test void getProviderWhenMatchShouldReturnProvider() { given(this.provider.isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader)) - .willReturn(true); + .willReturn(true); TemplateAvailabilityProvider found = this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); assertThat(found).isSameAs(this.provider); @@ -162,30 +161,30 @@ class TemplateAvailabilityProvidersTests { @Test void getProviderShouldCacheMatchResult() { given(this.provider.isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader)) - .willReturn(true); + .willReturn(true); this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); - then(this.provider).should().isTemplateAvailable(this.view, this.environment, this.classLoader, - this.resourceLoader); + then(this.provider).should() + .isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader); } @Test void getProviderShouldCacheNoMatchResult() { this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); - then(this.provider).should().isTemplateAvailable(this.view, this.environment, this.classLoader, - this.resourceLoader); + then(this.provider).should() + .isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader); } @Test void getProviderWhenCacheDisabledShouldNotUseCache() { given(this.provider.isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader)) - .willReturn(true); + .willReturn(true); this.environment.setProperty("spring.template.provider.cache", "false"); this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); - then(this.provider).should(times(2)).isTemplateAvailable(this.view, this.environment, this.classLoader, - this.resourceLoader); + then(this.provider).should(times(2)) + .isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafReactiveAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafReactiveAutoConfigurationTests.java index 41e5b7aeb6..438f2205e3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafReactiveAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafReactiveAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,7 +66,7 @@ class ThymeleafReactiveAutoConfigurationTests { private final BuildOutput buildOutput = new BuildOutput(getClass()); private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ThymeleafAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ThymeleafAutoConfiguration.class)); @Test void createFromConfigClass() { @@ -91,98 +91,99 @@ class ThymeleafReactiveAutoConfigurationTests { @Test void defaultMediaTypes() { - this.contextRunner.run( - (context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getSupportedMediaTypes()) - .containsExactly(MediaType.TEXT_HTML, MediaType.APPLICATION_XHTML_XML, - MediaType.APPLICATION_XML, MediaType.TEXT_XML, MediaType.APPLICATION_RSS_XML, - MediaType.APPLICATION_ATOM_XML, new MediaType("application", "javascript"), - new MediaType("application", "ecmascript"), new MediaType("text", "javascript"), - new MediaType("text", "ecmascript"), MediaType.APPLICATION_JSON, - new MediaType("text", "css"), MediaType.TEXT_PLAIN, MediaType.TEXT_EVENT_STREAM)); + this.contextRunner + .run((context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getSupportedMediaTypes()) + .containsExactly(MediaType.TEXT_HTML, MediaType.APPLICATION_XHTML_XML, MediaType.APPLICATION_XML, + MediaType.TEXT_XML, MediaType.APPLICATION_RSS_XML, MediaType.APPLICATION_ATOM_XML, + new MediaType("application", "javascript"), new MediaType("application", "ecmascript"), + new MediaType("text", "javascript"), new MediaType("text", "ecmascript"), + MediaType.APPLICATION_JSON, new MediaType("text", "css"), MediaType.TEXT_PLAIN, + MediaType.TEXT_EVENT_STREAM)); } @Test void overrideMediaTypes() { - this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.media-types:text/html,text/plain").run( - (context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getSupportedMediaTypes()) - .containsExactly(MediaType.TEXT_HTML, MediaType.TEXT_PLAIN)); + this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.media-types:text/html,text/plain") + .run((context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getSupportedMediaTypes()) + .containsExactly(MediaType.TEXT_HTML, MediaType.TEXT_PLAIN)); } @Test void overrideTemplateResolverOrder() { this.contextRunner.withPropertyValues("spring.thymeleaf.templateResolverOrder:25") - .run((context) -> assertThat(context.getBean(ITemplateResolver.class).getOrder()) - .isEqualTo(Integer.valueOf(25))); + .run((context) -> assertThat(context.getBean(ITemplateResolver.class).getOrder()) + .isEqualTo(Integer.valueOf(25))); } @Test void overrideViewNames() { this.contextRunner.withPropertyValues("spring.thymeleaf.viewNames:foo,bar") - .run((context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getViewNames()) - .isEqualTo(new String[] { "foo", "bar" })); + .run((context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getViewNames()) + .isEqualTo(new String[] { "foo", "bar" })); } @Test void overrideMaxChunkSize() { this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.maxChunkSize:8KB") - .run((context) -> assertThat( - context.getBean(ThymeleafReactiveViewResolver.class).getResponseMaxChunkSizeBytes()) - .isEqualTo(Integer.valueOf(8192))); + .run((context) -> assertThat( + context.getBean(ThymeleafReactiveViewResolver.class).getResponseMaxChunkSizeBytes()) + .isEqualTo(Integer.valueOf(8192))); } @Test void overrideFullModeViewNames() { - this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.fullModeViewNames:foo,bar").run( - (context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getFullModeViewNames()) - .isEqualTo(new String[] { "foo", "bar" })); + this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.fullModeViewNames:foo,bar") + .run((context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getFullModeViewNames()) + .isEqualTo(new String[] { "foo", "bar" })); } @Test void overrideChunkedModeViewNames() { - this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.chunkedModeViewNames:foo,bar").run( - (context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getChunkedModeViewNames()) - .isEqualTo(new String[] { "foo", "bar" })); + this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.chunkedModeViewNames:foo,bar") + .run((context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getChunkedModeViewNames()) + .isEqualTo(new String[] { "foo", "bar" })); } @Test void overrideEnableSpringElCompiler() { - this.contextRunner.withPropertyValues("spring.thymeleaf.enable-spring-el-compiler:true").run( - (context) -> assertThat(context.getBean(SpringWebFluxTemplateEngine.class).getEnableSpringELCompiler()) - .isTrue()); + this.contextRunner.withPropertyValues("spring.thymeleaf.enable-spring-el-compiler:true") + .run((context) -> assertThat(context.getBean(SpringWebFluxTemplateEngine.class).getEnableSpringELCompiler()) + .isTrue()); } @Test void enableSpringElCompilerIsDisabledByDefault() { - this.contextRunner.run( - (context) -> assertThat(context.getBean(SpringWebFluxTemplateEngine.class).getEnableSpringELCompiler()) - .isFalse()); + this.contextRunner + .run((context) -> assertThat(context.getBean(SpringWebFluxTemplateEngine.class).getEnableSpringELCompiler()) + .isFalse()); } @Test void overrideRenderHiddenMarkersBeforeCheckboxes() { this.contextRunner.withPropertyValues("spring.thymeleaf.render-hidden-markers-before-checkboxes:true") - .run((context) -> assertThat( - context.getBean(SpringWebFluxTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()) - .isTrue()); + .run((context) -> assertThat( + context.getBean(SpringWebFluxTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()) + .isTrue()); } @Test void enableRenderHiddenMarkersBeforeCheckboxesIsDisabledByDefault() { this.contextRunner.run((context) -> assertThat( - context.getBean(SpringWebFluxTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()).isFalse()); + context.getBean(SpringWebFluxTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()) + .isFalse()); } @Test void templateLocationDoesNotExist(CapturedOutput output) { this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/no-such-directory/") - .run((context) -> assertThat(output).contains("Cannot find template location")); + .run((context) -> assertThat(output).contains("Cannot find template location")); } @Test void templateLocationEmpty(CapturedOutput output) { new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs(); this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/empty-templates/empty-directory/") - .run((context) -> assertThat(output).doesNotContain("Cannot find template location")); + .run((context) -> assertThat(output).doesNotContain("Cannot find template location")); } @Test @@ -210,8 +211,9 @@ class ThymeleafReactiveAutoConfigurationTests { this.contextRunner.run((context) -> { ISpringWebFluxTemplateEngine engine = context.getBean(ISpringWebFluxTemplateEngine.class); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/test").build()); - exchange.getAttributes().put(SpringSecurityContextUtils.SECURITY_CONTEXT_MODEL_ATTRIBUTE_NAME, - new SecurityContextImpl(new TestingAuthenticationToken("alice", "admin"))); + exchange.getAttributes() + .put(SpringSecurityContextUtils.SECURITY_CONTEXT_MODEL_ATTRIBUTE_NAME, + new SecurityContextImpl(new TestingAuthenticationToken("alice", "admin"))); IContext attrs = new SpringWebFluxContext(exchange); String result = engine.process("security-dialect", attrs); assertThat(result).isEqualTo("
alice
" + System.lineSeparator()); @@ -221,7 +223,7 @@ class ThymeleafReactiveAutoConfigurationTests { @Test void securityDialectAutoConfigurationBacksOffWithoutSpringSecurity() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.security")) - .run((context) -> assertThat(context).doesNotHaveBean(SpringSecurityDialect.class)); + .run((context) -> assertThat(context).doesNotHaveBean(SpringSecurityDialect.class)); } @Test @@ -237,9 +239,9 @@ class ThymeleafReactiveAutoConfigurationTests { @Test void layoutDialectCanBeCustomized() { this.contextRunner.withUserConfiguration(LayoutDialectConfiguration.class) - .run((context) -> assertThat( - ReflectionTestUtils.getField(context.getBean(LayoutDialect.class), "sortingStrategy")) - .isInstanceOf(GroupingStrategy.class)); + .run((context) -> assertThat( + ReflectionTestUtils.getField(context.getBean(LayoutDialect.class), "sortingStrategy")) + .isInstanceOf(GroupingStrategy.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java index b2e1d116ba..f7620dac45 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -78,24 +78,24 @@ class ThymeleafServletAutoConfigurationTests { private final BuildOutput buildOutput = new BuildOutput(getClass()); private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ThymeleafAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ThymeleafAutoConfiguration.class)); @Test void autoConfigurationBackOffWithoutThymeleafSpring() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.thymeleaf.spring5")) - .run((context) -> assertThat(context).doesNotHaveBean(TemplateEngine.class)); + .run((context) -> assertThat(context).doesNotHaveBean(TemplateEngine.class)); } @Test void createFromConfigClass() { this.contextRunner.withPropertyValues("spring.thymeleaf.mode:HTML", "spring.thymeleaf.suffix:") - .run((context) -> { - assertThat(context).hasSingleBean(TemplateEngine.class); - TemplateEngine engine = context.getBean(TemplateEngine.class); - Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); - String result = engine.process("template.html", attrs).trim(); - assertThat(result).isEqualTo("bar"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(TemplateEngine.class); + TemplateEngine engine = context.getBean(TemplateEngine.class); + Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); + String result = engine.process("template.html", attrs).trim(); + assertThat(result).isEqualTo("bar"); + }); } @Test @@ -113,76 +113,79 @@ class ThymeleafServletAutoConfigurationTests { @Test void overrideDisableProducePartialOutputWhileProcessing() { this.contextRunner.withPropertyValues("spring.thymeleaf.servlet.produce-partial-output-while-processing:false") - .run((context) -> assertThat( - context.getBean(ThymeleafViewResolver.class).getProducePartialOutputWhileProcessing()) - .isFalse()); + .run((context) -> assertThat( + context.getBean(ThymeleafViewResolver.class).getProducePartialOutputWhileProcessing()) + .isFalse()); } @Test void disableProducePartialOutputWhileProcessingIsEnabledByDefault() { this.contextRunner.run((context) -> assertThat( - context.getBean(ThymeleafViewResolver.class).getProducePartialOutputWhileProcessing()).isTrue()); + context.getBean(ThymeleafViewResolver.class).getProducePartialOutputWhileProcessing()) + .isTrue()); } @Test void overrideTemplateResolverOrder() { this.contextRunner.withPropertyValues("spring.thymeleaf.templateResolverOrder:25") - .run((context) -> assertThat(context.getBean(ITemplateResolver.class).getOrder()) - .isEqualTo(Integer.valueOf(25))); + .run((context) -> assertThat(context.getBean(ITemplateResolver.class).getOrder()) + .isEqualTo(Integer.valueOf(25))); } @Test void overrideViewNames() { this.contextRunner.withPropertyValues("spring.thymeleaf.viewNames:foo,bar") - .run((context) -> assertThat(context.getBean(ThymeleafViewResolver.class).getViewNames()) - .isEqualTo(new String[] { "foo", "bar" })); + .run((context) -> assertThat(context.getBean(ThymeleafViewResolver.class).getViewNames()) + .isEqualTo(new String[] { "foo", "bar" })); } @Test void overrideEnableSpringElCompiler() { this.contextRunner.withPropertyValues("spring.thymeleaf.enable-spring-el-compiler:true") - .run((context) -> assertThat(context.getBean(SpringTemplateEngine.class).getEnableSpringELCompiler()) - .isTrue()); + .run((context) -> assertThat(context.getBean(SpringTemplateEngine.class).getEnableSpringELCompiler()) + .isTrue()); } @Test void enableSpringElCompilerIsDisabledByDefault() { this.contextRunner - .run((context) -> assertThat(context.getBean(SpringTemplateEngine.class).getEnableSpringELCompiler()) - .isFalse()); + .run((context) -> assertThat(context.getBean(SpringTemplateEngine.class).getEnableSpringELCompiler()) + .isFalse()); } @Test void overrideRenderHiddenMarkersBeforeCheckboxes() { this.contextRunner.withPropertyValues("spring.thymeleaf.render-hidden-markers-before-checkboxes:true") - .run((context) -> assertThat( - context.getBean(SpringTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()).isTrue()); + .run((context) -> assertThat( + context.getBean(SpringTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()) + .isTrue()); } @Test void enableRenderHiddenMarkersBeforeCheckboxesIsDisabledByDefault() { this.contextRunner.run((context) -> assertThat( - context.getBean(SpringTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()).isFalse()); + context.getBean(SpringTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()) + .isFalse()); } @Test void templateLocationDoesNotExist(CapturedOutput output) { this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/no-such-directory/") - .run((context) -> assertThat(output).contains("Cannot find template location")); + .run((context) -> assertThat(output).contains("Cannot find template location")); } @Test void templateLocationEmpty(CapturedOutput output) { new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs(); this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/empty-templates/empty-directory/") - .run((context) -> assertThat(output).doesNotContain("Cannot find template location")); + .run((context) -> assertThat(output).doesNotContain("Cannot find template location")); } @Test void createLayoutFromConfigClass() { this.contextRunner.run((context) -> { - ThymeleafView view = (ThymeleafView) context.getBean(ThymeleafViewResolver.class).resolveViewName("view", - Locale.UK); + ThymeleafView view = (ThymeleafView) context.getBean(ThymeleafViewResolver.class) + .resolveViewName("view", Locale.UK); MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); @@ -222,7 +225,7 @@ class ThymeleafServletAutoConfigurationTests { new MockServletContext()); try { SecurityContextHolder - .setContext(new SecurityContextImpl(new TestingAuthenticationToken("alice", "admin"))); + .setContext(new SecurityContextImpl(new TestingAuthenticationToken("alice", "admin"))); String result = engine.process("security-dialect", attrs); assertThat(result).isEqualTo("
alice
" + System.lineSeparator()); } @@ -235,7 +238,7 @@ class ThymeleafServletAutoConfigurationTests { @Test void securityDialectAutoConfigurationBacksOffWithoutSpringSecurity() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.security")) - .run((context) -> assertThat(context).doesNotHaveBean(SpringSecurityDialect.class)); + .run((context) -> assertThat(context).doesNotHaveBean(SpringSecurityDialect.class)); } @Test @@ -251,13 +254,13 @@ class ThymeleafServletAutoConfigurationTests { @Test void renderNonWebAppTemplate() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(ThymeleafAutoConfiguration.class)) - .run((context) -> { - assertThat(context).doesNotHaveBean(ViewResolver.class); - TemplateEngine engine = context.getBean(TemplateEngine.class); - Context attrs = new Context(Locale.UK, Collections.singletonMap("greeting", "Hello World")); - String result = engine.process("message", attrs); - assertThat(result).contains("Hello World"); - }); + .run((context) -> { + assertThat(context).doesNotHaveBean(ViewResolver.class); + TemplateEngine engine = context.getBean(TemplateEngine.class); + Context attrs = new Context(Locale.UK, Collections.singletonMap("greeting", "Hello World")); + String result = engine.process("message", attrs); + assertThat(result).contains("Hello World"); + }); } @Test @@ -280,14 +283,18 @@ class ThymeleafServletAutoConfigurationTests { void registerResourceHandlingFilterWithOtherRegistrationBean() { // gh-14897 this.contextRunner.withUserConfiguration(FilterRegistrationOtherConfiguration.class) - .withPropertyValues("spring.web.resources.chain.enabled:true").run((context) -> { - Map beans = context.getBeansOfType(FilterRegistrationBean.class); - assertThat(beans).hasSize(2); - FilterRegistrationBean registration = beans.values().stream() - .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter).findFirst().get(); - assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", - EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR)); - }); + .withPropertyValues("spring.web.resources.chain.enabled:true") + .run((context) -> { + Map beans = context.getBeansOfType(FilterRegistrationBean.class); + assertThat(beans).hasSize(2); + FilterRegistrationBean registration = beans.values() + .stream() + .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter) + .findFirst() + .get(); + assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", + EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR)); + }); } @Test @@ -295,22 +302,26 @@ class ThymeleafServletAutoConfigurationTests { void registerResourceHandlingFilterWithResourceRegistrationBean() { // gh-14926 this.contextRunner.withUserConfiguration(FilterRegistrationResourceConfiguration.class) - .withPropertyValues("spring.web.resources.chain.enabled:true").run((context) -> { - Map beans = context.getBeansOfType(FilterRegistrationBean.class); - assertThat(beans).hasSize(1); - FilterRegistrationBean registration = beans.values().stream() - .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter).findFirst().get(); - assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", - EnumSet.of(DispatcherType.INCLUDE)); - }); + .withPropertyValues("spring.web.resources.chain.enabled:true") + .run((context) -> { + Map beans = context.getBeansOfType(FilterRegistrationBean.class); + assertThat(beans).hasSize(1); + FilterRegistrationBean registration = beans.values() + .stream() + .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter) + .findFirst() + .get(); + assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", + EnumSet.of(DispatcherType.INCLUDE)); + }); } @Test void layoutDialectCanBeCustomized() { this.contextRunner.withUserConfiguration(LayoutDialectConfiguration.class) - .run((context) -> assertThat( - ReflectionTestUtils.getField(context.getBean(LayoutDialect.class), "sortingStrategy")) - .isInstanceOf(GroupingStrategy.class)); + .run((context) -> assertThat( + ReflectionTestUtils.getField(context.getBean(LayoutDialect.class), "sortingStrategy")) + .isInstanceOf(GroupingStrategy.class)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java index bc900721d2..7861c74fc1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,27 +41,31 @@ class ThymeleafTemplateAvailabilityProviderTests { @Test void availabilityOfTemplateInDefaultLocation() { assertThat(this.provider.isTemplateAvailable("home", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateThatDoesNotExist() { assertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isFalse(); + this.resourceLoader)) + .isFalse(); } @Test void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.thymeleaf.prefix", "classpath:/custom-templates/"); assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.thymeleaf.suffix", ".thymeleaf"); assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java index c61dffbb9a..502124eb17 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,7 @@ import static org.mockito.Mockito.mock; class TransactionAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(TransactionAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(TransactionAutoConfiguration.class)); @Test void whenThereIsNoPlatformTransactionManagerNoTransactionTemplateIsAutoConfigured() { @@ -79,33 +79,33 @@ class TransactionAutoConfigurationTests { @Test void whenThereAreBothReactiveAndPlatformTransactionManagersATemplateAndAnOperatorAreAutoConfigured() { this.contextRunner - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withUserConfiguration(SinglePlatformTransactionManagerConfiguration.class, - SingleReactiveTransactionManagerConfiguration.class) - .withPropertyValues("spring.datasource.url:jdbc:h2:mem:" + UUID.randomUUID()).run((context) -> { - PlatformTransactionManager platformTransactionManager = context - .getBean(PlatformTransactionManager.class); - TransactionTemplate transactionTemplate = context.getBean(TransactionTemplate.class); - assertThat(transactionTemplate.getTransactionManager()).isSameAs(platformTransactionManager); - ReactiveTransactionManager reactiveTransactionManager = context - .getBean(ReactiveTransactionManager.class); - TransactionalOperator transactionalOperator = context.getBean(TransactionalOperator.class); - assertThat(transactionalOperator).extracting("transactionManager") - .isSameAs(reactiveTransactionManager); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withUserConfiguration(SinglePlatformTransactionManagerConfiguration.class, + SingleReactiveTransactionManagerConfiguration.class) + .withPropertyValues("spring.datasource.url:jdbc:h2:mem:" + UUID.randomUUID()) + .run((context) -> { + PlatformTransactionManager platformTransactionManager = context + .getBean(PlatformTransactionManager.class); + TransactionTemplate transactionTemplate = context.getBean(TransactionTemplate.class); + assertThat(transactionTemplate.getTransactionManager()).isSameAs(platformTransactionManager); + ReactiveTransactionManager reactiveTransactionManager = context + .getBean(ReactiveTransactionManager.class); + TransactionalOperator transactionalOperator = context.getBean(TransactionalOperator.class); + assertThat(transactionalOperator).extracting("transactionManager").isSameAs(reactiveTransactionManager); + }); } @Test void whenThereAreSeveralPlatformTransactionManagersNoTransactionTemplateIsAutoConfigured() { this.contextRunner.withUserConfiguration(SeveralPlatformTransactionManagersConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(TransactionTemplate.class)); + .run((context) -> assertThat(context).doesNotHaveBean(TransactionTemplate.class)); } @Test void whenThereAreSeveralReactiveTransactionManagersNoTransactionOperatorIsAutoConfigured() { this.contextRunner.withUserConfiguration(SeveralReactiveTransactionManagersConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(TransactionalOperator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(TransactionalOperator.class)); } @Test @@ -118,28 +118,31 @@ class TransactionAutoConfigurationTests { @Test void whenAUserProvidesATransactionalOperatorTheAutoConfiguredOperatorBacksOff() { - this.contextRunner.withUserConfiguration(SingleReactiveTransactionManagerConfiguration.class, - CustomTransactionalOperatorConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(TransactionalOperator.class); - assertThat(context.getBean("customTransactionalOperator")) - .isInstanceOf(TransactionalOperator.class); - }); + this.contextRunner + .withUserConfiguration(SingleReactiveTransactionManagerConfiguration.class, + CustomTransactionalOperatorConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(TransactionalOperator.class); + assertThat(context.getBean("customTransactionalOperator")).isInstanceOf(TransactionalOperator.class); + }); } @Test void platformTransactionManagerCustomizers() { this.contextRunner.withUserConfiguration(SeveralPlatformTransactionManagersConfiguration.class) - .run((context) -> { - TransactionManagerCustomizers customizers = context.getBean(TransactionManagerCustomizers.class); - assertThat(customizers).extracting("customizers").asList().singleElement() - .isInstanceOf(TransactionProperties.class); - }); + .run((context) -> { + TransactionManagerCustomizers customizers = context.getBean(TransactionManagerCustomizers.class); + assertThat(customizers).extracting("customizers") + .asList() + .singleElement() + .isInstanceOf(TransactionProperties.class); + }); } @Test void transactionNotManagedWithNoTransactionManager() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run( - (context) -> assertThat(context.getBean(TransactionalService.class).isTransactionActive()).isFalse()); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context.getBean(TransactionalService.class).isTransactionActive()).isFalse()); } @Test @@ -153,23 +156,25 @@ class TransactionAutoConfigurationTests { @Test void transactionManagerCanBeConfiguredToJdkProxy() { this.contextRunner.withUserConfiguration(PlatformTransactionManagersConfiguration.class) - .withPropertyValues("spring.aop.proxy-target-class=false").run((context) -> { - assertThat(context.getBean(AnotherService.class).isTransactionActive()).isTrue(); - assertThat(context).doesNotHaveBean(AnotherServiceImpl.class); - assertThat(context).doesNotHaveBean(TransactionalServiceImpl.class); - }); + .withPropertyValues("spring.aop.proxy-target-class=false") + .run((context) -> { + assertThat(context.getBean(AnotherService.class).isTransactionActive()).isTrue(); + assertThat(context).doesNotHaveBean(AnotherServiceImpl.class); + assertThat(context).doesNotHaveBean(TransactionalServiceImpl.class); + }); } @Test void customEnableTransactionManagementTakesPrecedence() { this.contextRunner - .withUserConfiguration(CustomTransactionManagementConfiguration.class, - PlatformTransactionManagersConfiguration.class) - .withPropertyValues("spring.aop.proxy-target-class=true").run((context) -> { - assertThat(context.getBean(AnotherService.class).isTransactionActive()).isTrue(); - assertThat(context).doesNotHaveBean(AnotherServiceImpl.class); - assertThat(context).doesNotHaveBean(TransactionalServiceImpl.class); - }); + .withUserConfiguration(CustomTransactionManagementConfiguration.class, + PlatformTransactionManagersConfiguration.class) + .withPropertyValues("spring.aop.proxy-target-class=true") + .run((context) -> { + assertThat(context.getBean(AnotherService.class).isTransactionActive()).isTrue(); + assertThat(context).doesNotHaveBean(AnotherServiceImpl.class); + assertThat(context).doesNotHaveBean(TransactionalServiceImpl.class); + }); } @Configuration @@ -273,8 +278,11 @@ class TransactionAutoConfigurationTests { @Bean DataSource dataSource() { - return DataSourceBuilder.create().driverClassName("org.hsqldb.jdbc.JDBCDriver").url("jdbc:hsqldb:mem:tx") - .username("sa").build(); + return DataSourceBuilder.create() + .driverClassName("org.hsqldb.jdbc.JDBCDriver") + .url("jdbc:hsqldb:mem:tx") + .username("sa") + .build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java index f25bcdcf70..918b413dc6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -128,7 +128,7 @@ class JtaAutoConfigurationTests { this.context = new AnnotationConfigApplicationContext(CustomTransactionManagerConfig.class, JtaAutoConfiguration.class); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(JtaTransactionManager.class)); + .isThrownBy(() -> this.context.getBean(JtaTransactionManager.class)); } @Test @@ -173,9 +173,10 @@ class JtaAutoConfigurationTests { @Test void atomikosConnectionFactoryPoolConfiguration() { this.context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.jta.atomikos.connectionfactory.minPoolSize:5", - "spring.jta.atomikos.connectionfactory.maxPoolSize:10", "spring.jta.log-dir:" + this.atomikosLogs) - .applyTo(this.context); + TestPropertyValues + .of("spring.jta.atomikos.connectionfactory.minPoolSize:5", + "spring.jta.atomikos.connectionfactory.maxPoolSize:10", "spring.jta.log-dir:" + this.atomikosLogs) + .applyTo(this.context); this.context.register(AtomikosJtaConfiguration.class, PoolConfiguration.class); this.context.refresh(); AtomikosConnectionFactoryBean connectionFactory = this.context.getBean(AtomikosConnectionFactoryBean.class); @@ -186,9 +187,10 @@ class JtaAutoConfigurationTests { @Test void atomikosDataSourcePoolConfiguration() { this.context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.jta.atomikos.datasource.minPoolSize:5", - "spring.jta.atomikos.datasource.maxPoolSize:10", "spring.jta.log-dir:" + this.atomikosLogs) - .applyTo(this.context); + TestPropertyValues + .of("spring.jta.atomikos.datasource.minPoolSize:5", "spring.jta.atomikos.datasource.maxPoolSize:10", + "spring.jta.log-dir:" + this.atomikosLogs) + .applyTo(this.context); this.context.register(AtomikosJtaConfiguration.class, PoolConfiguration.class); this.context.refresh(); AtomikosDataSourceBean dataSource = this.context.getBean(AtomikosDataSourceBean.class); @@ -199,9 +201,10 @@ class JtaAutoConfigurationTests { @Test void atomikosCustomizeJtaTransactionManagerUsingProperties() { this.context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.transaction.default-timeout:30", - "spring.transaction.rollback-on-commit-failure:true", "spring.jta.log-dir:" + this.atomikosLogs) - .applyTo(this.context); + TestPropertyValues + .of("spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true", + "spring.jta.log-dir:" + this.atomikosLogs) + .applyTo(this.context); this.context.register(AtomikosJtaConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); JtaTransactionManager transactionManager = this.context.getBean(JtaTransactionManager.class); @@ -282,8 +285,8 @@ class JtaAutoConfigurationTests { @Override public void beforeEach(ExtensionContext context) throws Exception { Namespace namespace = Namespace.create(getClass(), context.getUniqueId()); - context.getStore(namespace).getOrComputeIfAbsent(InitialContext.class, (k) -> createInitialContext(), - InitialContext.class); + context.getStore(namespace) + .getOrComputeIfAbsent(InitialContext.class, (k) -> createInitialContext(), InitialContext.class); } private InitialContext createInitialContext() { @@ -298,8 +301,8 @@ class JtaAutoConfigurationTests { @Override public void afterEach(ExtensionContext context) throws Exception { Namespace namespace = Namespace.create(getClass(), context.getUniqueId()); - InitialContext initialContext = context.getStore(namespace).remove(InitialContext.class, - InitialContext.class); + InitialContext initialContext = context.getStore(namespace) + .remove(InitialContext.class, InitialContext.class); initialContext.removeFromEnvironment("org.osjava.sj.jndi.ignoreClose"); initialContext.close(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java index 30ce1a4bdd..59d4d7583d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,16 +58,16 @@ import static org.mockito.Mockito.mock; class ValidationAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)); @Test void validationAutoConfigurationShouldConfigureDefaultValidator() { this.contextRunner.run((context) -> { assertThat(context.getBeanNamesForType(Validator.class)).containsExactly("defaultValidator"); assertThat(context.getBeanNamesForType(org.springframework.validation.Validator.class)) - .containsExactly("defaultValidator"); + .containsExactly("defaultValidator"); assertThat(context.getBean(Validator.class)).isInstanceOf(LocalValidatorFactoryBean.class) - .isEqualTo(context.getBean(org.springframework.validation.Validator.class)); + .isEqualTo(context.getBean(org.springframework.validation.Validator.class)); assertThat(isPrimaryBean(context, "defaultValidator")).isTrue(); }); } @@ -77,9 +77,9 @@ class ValidationAutoConfigurationTests { this.contextRunner.withUserConfiguration(UserDefinedValidatorConfig.class).run((context) -> { assertThat(context.getBeanNamesForType(Validator.class)).containsExactly("customValidator"); assertThat(context.getBeanNamesForType(org.springframework.validation.Validator.class)) - .containsExactly("customValidator"); + .containsExactly("customValidator"); assertThat(context.getBean(Validator.class)).isInstanceOf(OptionalValidatorFactoryBean.class) - .isEqualTo(context.getBean(org.springframework.validation.Validator.class)); + .isEqualTo(context.getBean(org.springframework.validation.Validator.class)); assertThat(isPrimaryBean(context, "customValidator")).isFalse(); }); } @@ -89,7 +89,7 @@ class ValidationAutoConfigurationTests { this.contextRunner.withUserConfiguration(UserDefinedDefaultValidatorConfig.class).run((context) -> { assertThat(context.getBeanNamesForType(Validator.class)).containsExactly("defaultValidator"); assertThat(context.getBeanNamesForType(org.springframework.validation.Validator.class)) - .containsExactly("defaultValidator"); + .containsExactly("defaultValidator"); assertThat(isPrimaryBean(context, "defaultValidator")).isFalse(); }); } @@ -108,9 +108,9 @@ class ValidationAutoConfigurationTests { this.contextRunner.withUserConfiguration(UserDefinedSpringValidatorConfig.class).run((context) -> { assertThat(context.getBeanNamesForType(Validator.class)).containsExactly("defaultValidator"); assertThat(context.getBeanNamesForType(org.springframework.validation.Validator.class)) - .containsExactly("customValidator", "anotherCustomValidator", "defaultValidator"); + .containsExactly("customValidator", "anotherCustomValidator", "defaultValidator"); assertThat(context.getBean(Validator.class)).isInstanceOf(LocalValidatorFactoryBean.class) - .isEqualTo(context.getBean(org.springframework.validation.Validator.class)); + .isEqualTo(context.getBean(org.springframework.validation.Validator.class)); assertThat(isPrimaryBean(context, "defaultValidator")).isTrue(); }); } @@ -120,10 +120,10 @@ class ValidationAutoConfigurationTests { this.contextRunner.withUserConfiguration(UserDefinedPrimarySpringValidatorConfig.class).run((context) -> { assertThat(context.getBeanNamesForType(Validator.class)).containsExactly("defaultValidator"); assertThat(context.getBeanNamesForType(org.springframework.validation.Validator.class)) - .containsExactly("customValidator", "anotherCustomValidator", "defaultValidator"); + .containsExactly("customValidator", "anotherCustomValidator", "defaultValidator"); assertThat(context.getBean(Validator.class)).isInstanceOf(LocalValidatorFactoryBean.class); assertThat(context.getBean(org.springframework.validation.Validator.class)) - .isEqualTo(context.getBean("anotherCustomValidator")); + .isEqualTo(context.getBean("anotherCustomValidator")); assertThat(isPrimaryBean(context, "defaultValidator")).isFalse(); }); } @@ -134,10 +134,10 @@ class ValidationAutoConfigurationTests { this.contextRunner.withParent(parent).run((context) -> { assertThat(context.getBeanNamesForType(Validator.class)).containsExactly("defaultValidator"); assertThat(context.getBeanNamesForType(org.springframework.validation.Validator.class)) - .containsExactly("defaultValidator"); + .containsExactly("defaultValidator"); assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getBeanFactory(), - org.springframework.validation.Validator.class)).containsExactly("defaultValidator", - "customValidator", "anotherCustomValidator"); + org.springframework.validation.Validator.class)) + .containsExactly("defaultValidator", "customValidator", "anotherCustomValidator"); assertThat(isPrimaryBean(context, "defaultValidator")).isTrue(); }); }); @@ -146,17 +146,17 @@ class ValidationAutoConfigurationTests { @Test void whenUserProvidesPrimarySpringValidatorInParentContextThenAutoConfiguredValidatorIsPrimary() { new ApplicationContextRunner().withUserConfiguration(UserDefinedPrimarySpringValidatorConfig.class) - .run((parent) -> { - this.contextRunner.withParent(parent).run((context) -> { - assertThat(context.getBeanNamesForType(Validator.class)).containsExactly("defaultValidator"); - assertThat(context.getBeanNamesForType(org.springframework.validation.Validator.class)) - .containsExactly("defaultValidator"); - assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getBeanFactory(), - org.springframework.validation.Validator.class)).containsExactly("defaultValidator", - "customValidator", "anotherCustomValidator"); - assertThat(isPrimaryBean(context, "defaultValidator")).isTrue(); - }); + .run((parent) -> { + this.contextRunner.withParent(parent).run((context) -> { + assertThat(context.getBeanNamesForType(Validator.class)).containsExactly("defaultValidator"); + assertThat(context.getBeanNamesForType(org.springframework.validation.Validator.class)) + .containsExactly("defaultValidator"); + assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getBeanFactory(), + org.springframework.validation.Validator.class)) + .containsExactly("defaultValidator", "customValidator", "anotherCustomValidator"); + assertThat(isPrimaryBean(context, "defaultValidator")).isTrue(); }); + }); } @Test @@ -192,14 +192,14 @@ class ValidationAutoConfigurationTests { @Test void validationCanBeConfiguredToUseJdkProxy() { this.contextRunner.withUserConfiguration(AnotherSampleServiceConfiguration.class) - .withPropertyValues("spring.aop.proxy-target-class=false").run((context) -> { - assertThat(context.getBeansOfType(Validator.class)).hasSize(1); - assertThat(context.getBeansOfType(DefaultAnotherSampleService.class)).isEmpty(); - AnotherSampleService service = context.getBean(AnotherSampleService.class); - service.doSomething(42); - assertThatExceptionOfType(ConstraintViolationException.class) - .isThrownBy(() -> service.doSomething(2)); - }); + .withPropertyValues("spring.aop.proxy-target-class=false") + .run((context) -> { + assertThat(context.getBeansOfType(Validator.class)).hasSize(1); + assertThat(context.getBeansOfType(DefaultAnotherSampleService.class)).isEmpty(); + AnotherSampleService service = context.getBean(AnotherSampleService.class); + service.doSomething(42); + assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> service.doSomething(2)); + }); } @Test @@ -208,32 +208,34 @@ class ValidationAutoConfigurationTests { assertThat(context.getBeansOfType(Validator.class)).hasSize(1); Object userMethodValidationPostProcessor = context.getBean("testMethodValidationPostProcessor"); assertThat(context.getBean(MethodValidationPostProcessor.class)) - .isSameAs(userMethodValidationPostProcessor); + .isSameAs(userMethodValidationPostProcessor); assertThat(context.getBeansOfType(MethodValidationPostProcessor.class)).hasSize(1); assertThat(context.getBean(Validator.class)) - .isNotSameAs(ReflectionTestUtils.getField(userMethodValidationPostProcessor, "validator")); + .isNotSameAs(ReflectionTestUtils.getField(userMethodValidationPostProcessor, "validator")); }); } @Test void methodValidationPostProcessorValidatorDependencyDoesNotTriggerEarlyInitialization() { this.contextRunner.withUserConfiguration(CustomValidatorConfiguration.class) - .run((context) -> assertThat(context.getBean(TestBeanPostProcessor.class).postProcessed) - .contains("someService")); + .run((context) -> assertThat(context.getBean(TestBeanPostProcessor.class).postProcessed) + .contains("someService")); } @Test void validationIsEnabledInChildContext() { this.contextRunner.run((parent) -> new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) - .withUserConfiguration(SampleService.class).withParent(parent).run((context) -> { - assertThat(context.getBeansOfType(Validator.class)).hasSize(0); - assertThat(parent.getBeansOfType(Validator.class)).hasSize(1); - SampleService service = context.getBean(SampleService.class); - service.doSomething("Valid"); - assertThatExceptionOfType(ConstraintViolationException.class) - .isThrownBy(() -> service.doSomething("KO")); - })); + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) + .withUserConfiguration(SampleService.class) + .withParent(parent) + .run((context) -> { + assertThat(context.getBeansOfType(Validator.class)).hasSize(0); + assertThat(parent.getBeansOfType(Validator.class)).hasSize(1); + SampleService service = context.getBean(SampleService.class); + service.doSomething("Valid"); + assertThatExceptionOfType(ConstraintViolationException.class) + .isThrownBy(() -> service.doSomething("KO")); + })); } private boolean isPrimaryBean(AssertableApplicationContext context, String beanName) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java index 7020ef36f3..7a30d6c21d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)); @Test void missingElDependencyIsTolerated() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java index 70dfa9ffb5..bfddc1eb14 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ValidationAutoConfigurationWithoutValidatorTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)); @Test void validationIsDisabled() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapterTests.java index f11535abfe..99a01f9c39 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,10 +87,9 @@ class ValidatorAdapterTests { ClassPathResource hibernateValidator = new ClassPathResource( "META-INF/services/javax.validation.spi.ValidationProvider"); this.contextRunner - .withClassLoader( - new FilteredClassLoader(FilteredClassLoader.ClassPathResourceFilter.of(hibernateValidator), - FilteredClassLoader.PackageFilter.of("org.hibernate.validator"))) - .run((context) -> ValidatorAdapter.get(context, null)); + .withClassLoader(new FilteredClassLoader(FilteredClassLoader.ClassPathResourceFilter.of(hibernateValidator), + FilteredClassLoader.PackageFilter.of("org.hibernate.validator"))) + .run((context) -> ValidatorAdapter.get(context, null)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java index dc0cd28b08..b7fd934172 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -368,55 +368,55 @@ class ServerPropertiesTests { @Test void tomcatMinSpareThreadsMatchesProtocolDefault() throws Exception { assertThat(this.properties.getTomcat().getThreads().getMinSpare()) - .isEqualTo(getDefaultProtocol().getMinSpareThreads()); + .isEqualTo(getDefaultProtocol().getMinSpareThreads()); } @Test void tomcatMaxHttpPostSizeMatchesConnectorDefault() { assertThat(this.properties.getTomcat().getMaxHttpFormPostSize().toBytes()) - .isEqualTo(getDefaultConnector().getMaxPostSize()); + .isEqualTo(getDefaultConnector().getMaxPostSize()); } @Test void tomcatBackgroundProcessorDelayMatchesEngineDefault() { assertThat(this.properties.getTomcat().getBackgroundProcessorDelay()) - .hasSeconds((new StandardEngine().getBackgroundProcessorDelay())); + .hasSeconds((new StandardEngine().getBackgroundProcessorDelay())); } @Test void tomcatMaxHttpFormPostSizeMatchesConnectorDefault() { assertThat(this.properties.getTomcat().getMaxHttpFormPostSize().toBytes()) - .isEqualTo(getDefaultConnector().getMaxPostSize()); + .isEqualTo(getDefaultConnector().getMaxPostSize()); } @Test void tomcatUriEncodingMatchesConnectorDefault() { assertThat(this.properties.getTomcat().getUriEncoding().name()) - .isEqualTo(getDefaultConnector().getURIEncoding()); + .isEqualTo(getDefaultConnector().getURIEncoding()); } @Test void tomcatRedirectContextRootMatchesDefault() { assertThat(this.properties.getTomcat().getRedirectContextRoot()) - .isEqualTo(new StandardContext().getMapperContextRootRedirectEnabled()); + .isEqualTo(new StandardContext().getMapperContextRootRedirectEnabled()); } @Test void tomcatAccessLogRenameOnRotateMatchesDefault() { assertThat(this.properties.getTomcat().getAccesslog().isRenameOnRotate()) - .isEqualTo(new AccessLogValve().isRenameOnRotate()); + .isEqualTo(new AccessLogValve().isRenameOnRotate()); } @Test void tomcatAccessLogRequestAttributesEnabledMatchesDefault() { assertThat(this.properties.getTomcat().getAccesslog().isRequestAttributesEnabled()) - .isEqualTo(new AccessLogValve().getRequestAttributesEnabled()); + .isEqualTo(new AccessLogValve().getRequestAttributesEnabled()); } @Test void tomcatInternalProxiesMatchesDefault() { assertThat(this.properties.getTomcat().getRemoteip().getInternalProxies()) - .isEqualTo(new RemoteIpValve().getInternalProxies()); + .isEqualTo(new RemoteIpValve().getInternalProxies()); } @Test @@ -456,16 +456,17 @@ class ServerPropertiesTests { void jettyMaxHttpFormPostSizeMatchesDefault() { JettyServletWebServerFactory jettyFactory = new JettyServletWebServerFactory(0); JettyWebServer jetty = (JettyWebServer) jettyFactory - .getWebServer((ServletContextInitializer) (servletContext) -> servletContext - .addServlet("formPost", new HttpServlet() { + .getWebServer((ServletContextInitializer) (servletContext) -> servletContext + .addServlet("formPost", new HttpServlet() { - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - req.getParameterMap(); - } + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + req.getParameterMap(); + } - }).addMapping("/form")); + }) + .addMapping("/form")); jetty.start(); org.eclipse.jetty.server.Connector connector = jetty.getServer().getConnectors()[0]; final AtomicReference failure = new AtomicReference<>(); @@ -515,19 +516,19 @@ class ServerPropertiesTests { @Test void undertowMaxHttpPostSizeMatchesDefault() { assertThat(this.properties.getUndertow().getMaxHttpPostSize().toBytes()) - .isEqualTo(UndertowOptions.DEFAULT_MAX_ENTITY_SIZE); + .isEqualTo(UndertowOptions.DEFAULT_MAX_ENTITY_SIZE); } @Test void nettyMaxChunkSizeMatchesHttpDecoderSpecDefault() { assertThat(this.properties.getNetty().getMaxChunkSize().toBytes()) - .isEqualTo(HttpDecoderSpec.DEFAULT_MAX_CHUNK_SIZE); + .isEqualTo(HttpDecoderSpec.DEFAULT_MAX_CHUNK_SIZE); } @Test void nettyMaxInitialLineLengthMatchesHttpDecoderSpecDefault() { assertThat(this.properties.getNetty().getMaxInitialLineLength().toBytes()) - .isEqualTo(HttpDecoderSpec.DEFAULT_MAX_INITIAL_LINE_LENGTH); + .isEqualTo(HttpDecoderSpec.DEFAULT_MAX_INITIAL_LINE_LENGTH); } @Test @@ -538,13 +539,13 @@ class ServerPropertiesTests { @Test void nettyH2cMaxContentLengthMatchesHttpDecoderSpecDefault() { assertThat(this.properties.getNetty().getH2cMaxContentLength().toBytes()) - .isEqualTo(HttpRequestDecoderSpec.DEFAULT_H2C_MAX_CONTENT_LENGTH); + .isEqualTo(HttpRequestDecoderSpec.DEFAULT_H2C_MAX_CONTENT_LENGTH); } @Test void nettyInitialBufferSizeMatchesHttpDecoderSpecDefault() { assertThat(this.properties.getNetty().getInitialBufferSize().toBytes()) - .isEqualTo(HttpDecoderSpec.DEFAULT_INITIAL_BUFFER_SIZE); + .isEqualTo(HttpDecoderSpec.DEFAULT_INITIAL_BUFFER_SIZE); } private Connector getDefaultConnector() { @@ -553,7 +554,8 @@ class ServerPropertiesTests { private AbstractProtocol getDefaultProtocol() throws Exception { return (AbstractProtocol) Class.forName(TomcatServletWebServerFactory.DEFAULT_PROTOCOL) - .getDeclaredConstructor().newInstance(); + .getDeclaredConstructor() + .newInstance(); } private void bind(String name, String value) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebPropertiesResourcesBindingTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebPropertiesResourcesBindingTests.java index ce8d794285..0a12d44e10 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebPropertiesResourcesBindingTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebPropertiesResourcesBindingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,20 +37,20 @@ import static org.assertj.core.api.Assertions.assertThat; class WebPropertiesResourcesBindingTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(TestConfiguration.class); + .withUserConfiguration(TestConfiguration.class); @Test void staticLocationsExpandArray() { this.contextRunner - .withPropertyValues("spring.web.resources.static-locations[0]=classpath:/one/", - "spring.web.resources.static-locations[1]=classpath:/two", - "spring.web.resources.static-locations[2]=classpath:/three/", - "spring.web.resources.static-locations[3]=classpath:/four", - "spring.web.resources.static-locations[4]=classpath:/five/", - "spring.web.resources.static-locations[5]=classpath:/six") - .run(assertResourceProperties((properties) -> assertThat(properties.getStaticLocations()).contains( - "classpath:/one/", "classpath:/two/", "classpath:/three/", "classpath:/four/", - "classpath:/five/", "classpath:/six/"))); + .withPropertyValues("spring.web.resources.static-locations[0]=classpath:/one/", + "spring.web.resources.static-locations[1]=classpath:/two", + "spring.web.resources.static-locations[2]=classpath:/three/", + "spring.web.resources.static-locations[3]=classpath:/four", + "spring.web.resources.static-locations[4]=classpath:/five/", + "spring.web.resources.static-locations[5]=classpath:/six") + .run(assertResourceProperties((properties) -> assertThat(properties.getStaticLocations()).contains( + "classpath:/one/", "classpath:/two/", "classpath:/three/", "classpath:/four/", "classpath:/five/", + "classpath:/six/"))); } private ContextConsumer assertResourceProperties(Consumer consumer) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebPropertiesResourcesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebPropertiesResourcesTests.java index e77e190de6..c7cf28174a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebPropertiesResourcesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebPropertiesResourcesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -91,8 +91,8 @@ class WebPropertiesResourcesTests { properties.setStaleWhileRevalidate(Duration.ofSeconds(7)); CacheControl cacheControl = properties.toHttpCacheControl(); assertThat(cacheControl.getHeaderValue()) - .isEqualTo("max-age=4, must-revalidate, no-transform, public, private, proxy-revalidate," - + " s-maxage=5, stale-if-error=6, stale-while-revalidate=7"); + .isEqualTo("max-age=4, must-revalidate, no-transform, public, private, proxy-revalidate," + + " s-maxage=5, stale-if-error=6, stale-while-revalidate=7"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java index 72b592b971..cb6e87cb74 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,33 +56,33 @@ import static org.mockito.Mockito.mock; class RestTemplateAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)); @Test void restTemplateBuilderConfigurerShouldBeLazilyDefined() { this.contextRunner.run((context) -> assertThat( - context.getBeanFactory().getBeanDefinition("restTemplateBuilderConfigurer").isLazyInit()).isTrue()); + context.getBeanFactory().getBeanDefinition("restTemplateBuilderConfigurer").isLazyInit()) + .isTrue()); } @Test void restTemplateBuilderShouldBeLazilyDefined() { - this.contextRunner.run( - (context) -> assertThat(context.getBeanFactory().getBeanDefinition("restTemplateBuilder").isLazyInit()) - .isTrue()); + this.contextRunner + .run((context) -> assertThat(context.getBeanFactory().getBeanDefinition("restTemplateBuilder").isLazyInit()) + .isTrue()); } @Test void restTemplateWhenMessageConvertersDefinedShouldHaveMessageConverters() { this.contextRunner.withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) - .withUserConfiguration(RestTemplateConfig.class).run((context) -> { - assertThat(context).hasSingleBean(RestTemplate.class); - RestTemplate restTemplate = context.getBean(RestTemplate.class); - List> converters = context.getBean(HttpMessageConverters.class) - .getConverters(); - assertThat(restTemplate.getMessageConverters()).containsExactlyElementsOf(converters); - assertThat(restTemplate.getRequestFactory()) - .isInstanceOf(HttpComponentsClientHttpRequestFactory.class); - }); + .withUserConfiguration(RestTemplateConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(RestTemplate.class); + RestTemplate restTemplate = context.getBean(RestTemplate.class); + List> converters = context.getBean(HttpMessageConverters.class).getConverters(); + assertThat(restTemplate.getMessageConverters()).containsExactlyElementsOf(converters); + assertThat(restTemplate.getRequestFactory()).isInstanceOf(HttpComponentsClientHttpRequestFactory.class); + }); } @Test @@ -91,7 +91,7 @@ class RestTemplateAutoConfigurationTests { assertThat(context).hasSingleBean(RestTemplate.class); RestTemplate restTemplate = context.getBean(RestTemplate.class); assertThat(restTemplate.getMessageConverters().size()) - .isEqualTo(new RestTemplate().getMessageConverters().size()); + .isEqualTo(new RestTemplate().getMessageConverters().size()); }); } @@ -99,51 +99,53 @@ class RestTemplateAutoConfigurationTests { @SuppressWarnings({ "unchecked", "rawtypes" }) void restTemplateWhenHasCustomMessageConvertersShouldHaveMessageConverters() { this.contextRunner.withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) - .withUserConfiguration(CustomHttpMessageConverter.class, RestTemplateConfig.class).run((context) -> { - assertThat(context).hasSingleBean(RestTemplate.class); - RestTemplate restTemplate = context.getBean(RestTemplate.class); - assertThat(restTemplate.getMessageConverters()).extracting(HttpMessageConverter::getClass) - .contains((Class) CustomHttpMessageConverter.class); - }); + .withUserConfiguration(CustomHttpMessageConverter.class, RestTemplateConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(RestTemplate.class); + RestTemplate restTemplate = context.getBean(RestTemplate.class); + assertThat(restTemplate.getMessageConverters()).extracting(HttpMessageConverter::getClass) + .contains((Class) CustomHttpMessageConverter.class); + }); } @Test void restTemplateShouldApplyCustomizer() { this.contextRunner.withUserConfiguration(RestTemplateConfig.class, RestTemplateCustomizerConfig.class) - .run((context) -> { - assertThat(context).hasSingleBean(RestTemplate.class); - RestTemplate restTemplate = context.getBean(RestTemplate.class); - RestTemplateCustomizer customizer = context.getBean(RestTemplateCustomizer.class); - then(customizer).should().customize(restTemplate); - }); + .run((context) -> { + assertThat(context).hasSingleBean(RestTemplate.class); + RestTemplate restTemplate = context.getBean(RestTemplate.class); + RestTemplateCustomizer customizer = context.getBean(RestTemplateCustomizer.class); + then(customizer).should().customize(restTemplate); + }); } @Test void restTemplateWhenHasCustomBuilderShouldUseCustomBuilder() { - this.contextRunner.withUserConfiguration(RestTemplateConfig.class, CustomRestTemplateBuilderConfig.class, - RestTemplateCustomizerConfig.class).run((context) -> { - assertThat(context).hasSingleBean(RestTemplate.class); - RestTemplate restTemplate = context.getBean(RestTemplate.class); - assertThat(restTemplate.getMessageConverters()).hasSize(1); - assertThat(restTemplate.getMessageConverters().get(0)) - .isInstanceOf(CustomHttpMessageConverter.class); - then(context.getBean(RestTemplateCustomizer.class)).shouldHaveNoInteractions(); - }); + this.contextRunner + .withUserConfiguration(RestTemplateConfig.class, CustomRestTemplateBuilderConfig.class, + RestTemplateCustomizerConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(RestTemplate.class); + RestTemplate restTemplate = context.getBean(RestTemplate.class); + assertThat(restTemplate.getMessageConverters()).hasSize(1); + assertThat(restTemplate.getMessageConverters().get(0)).isInstanceOf(CustomHttpMessageConverter.class); + then(context.getBean(RestTemplateCustomizer.class)).shouldHaveNoInteractions(); + }); } @Test void restTemplateWhenHasCustomBuilderCouldReuseBuilderConfigurer() { - this.contextRunner.withUserConfiguration(RestTemplateConfig.class, - CustomRestTemplateBuilderWithConfigurerConfig.class, RestTemplateCustomizerConfig.class) - .run((context) -> { - assertThat(context).hasSingleBean(RestTemplate.class); - RestTemplate restTemplate = context.getBean(RestTemplate.class); - assertThat(restTemplate.getMessageConverters()).hasSize(1); - assertThat(restTemplate.getMessageConverters().get(0)) - .isInstanceOf(CustomHttpMessageConverter.class); - RestTemplateCustomizer customizer = context.getBean(RestTemplateCustomizer.class); - then(customizer).should().customize(restTemplate); - }); + this.contextRunner + .withUserConfiguration(RestTemplateConfig.class, CustomRestTemplateBuilderWithConfigurerConfig.class, + RestTemplateCustomizerConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(RestTemplate.class); + RestTemplate restTemplate = context.getBean(RestTemplate.class); + assertThat(restTemplate.getMessageConverters()).hasSize(1); + assertThat(restTemplate.getMessageConverters().get(0)).isInstanceOf(CustomHttpMessageConverter.class); + RestTemplateCustomizer customizer = context.getBean(RestTemplateCustomizer.class); + then(customizer).should().customize(restTemplate); + }); } @Test @@ -163,22 +165,22 @@ class RestTemplateAutoConfigurationTests { @Test void builderShouldBeFreshForEachUse() { this.contextRunner.withUserConfiguration(DirtyRestTemplateConfig.class) - .run((context) -> assertThat(context).hasNotFailed()); + .run((context) -> assertThat(context).hasNotFailed()); } @Test void whenServletWebApplicationRestTemplateBuilderIsConfigured() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(RestTemplateBuilder.class) - .hasSingleBean(RestTemplateBuilderConfigurer.class)); + .run((context) -> assertThat(context).hasSingleBean(RestTemplateBuilder.class) + .hasSingleBean(RestTemplateBuilderConfigurer.class)); } @Test void whenReactiveWebApplicationRestTemplateBuilderIsNotConfigured() { new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(RestTemplateBuilder.class) - .doesNotHaveBean(RestTemplateBuilderConfigurer.class)); + .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(RestTemplateBuilder.class) + .doesNotHaveBean(RestTemplateBuilderConfigurer.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizerTests.java index db30924210..1418526416 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -159,7 +159,7 @@ class JettyWebServerFactoryCustomizerTests { assertThat(defaultQueue).isInstanceOf(BlockingArrayQueue.class); assertThat(configuredQueue).isInstanceOf(BlockingArrayQueue.class); assertThat(((BlockingArrayQueue) defaultQueue).getMaxCapacity()) - .isEqualTo(((BlockingArrayQueue) configuredQueue).getMaxCapacity()); + .isEqualTo(((BlockingArrayQueue) configuredQueue).getMaxCapacity()); } @Test @@ -236,7 +236,7 @@ class JettyWebServerFactoryCustomizerTests { assertThat(queuedThreadPool.getMinThreads()).isEqualTo(defaultProperties.getThreads().getMin()); assertThat(queuedThreadPool.getMaxThreads()).isEqualTo(defaultProperties.getThreads().getMax()); assertThat(queuedThreadPool.getIdleTimeout()) - .isEqualTo(defaultProperties.getThreads().getIdleTimeout().toMillis()); + .isEqualTo(defaultProperties.getThreads().getIdleTimeout().toMillis()); } private CustomRequestLog getRequestLog(JettyWebServer server) { @@ -296,8 +296,9 @@ class JettyWebServerFactoryCustomizerTests { server.start(); server.stop(); return Arrays.stream(server.getServer().getConnectors()) - .filter((connector) -> connector instanceof AbstractConnector).map(Connector::getIdleTimeout) - .collect(Collectors.toList()); + .filter((connector) -> connector instanceof AbstractConnector) + .map(Connector::getIdleTimeout) + .collect(Collectors.toList()); } private List getRequestHeaderSizes(JettyWebServer server) { @@ -307,12 +308,14 @@ class JettyWebServerFactoryCustomizerTests { server.stop(); Connector[] connectors = server.getServer().getConnectors(); for (Connector connector : connectors) { - connector.getConnectionFactories().stream().filter((factory) -> factory instanceof ConnectionFactory) - .forEach((cf) -> { - ConnectionFactory factory = (ConnectionFactory) cf; - HttpConfiguration configuration = factory.getHttpConfiguration(); - requestHeaderSizes.add(configuration.getRequestHeaderSize()); - }); + connector.getConnectionFactories() + .stream() + .filter((factory) -> factory instanceof ConnectionFactory) + .forEach((cf) -> { + ConnectionFactory factory = (ConnectionFactory) cf; + HttpConfiguration configuration = factory.getHttpConfiguration(); + requestHeaderSizes.add(configuration.getRequestHeaderSize()); + }); } return requestHeaderSizes; } 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..ed3f9ad4c1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,8 +79,8 @@ class TomcatWebServerFactoryCustomizerTests { void defaultsAreConsistent() { customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getMaxSwallowSize()) - .isEqualTo(this.serverProperties.getTomcat().getMaxSwallowSize().toBytes())); + .getMaxSwallowSize()) + .isEqualTo(this.serverProperties.getTomcat().getMaxSwallowSize().toBytes())); } @Test @@ -88,7 +88,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.accept-count=10"); customizeAndRunServer((server) -> assertThat( ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getAcceptCount()) - .isEqualTo(10)); + .isEqualTo(10)); } @Test @@ -96,7 +96,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.processor-cache=100"); customizeAndRunServer((server) -> assertThat( ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getProcessorCache()) - .isEqualTo(100)); + .isEqualTo(100)); } @Test @@ -104,7 +104,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.keep-alive-timeout=30ms"); customizeAndRunServer((server) -> assertThat( ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getKeepAliveTimeout()) - .isEqualTo(30)); + .isEqualTo(30)); } @Test @@ -112,7 +112,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.http2.enabled=true"); customizeAndRunServer((server) -> assertThat( ((Http2Protocol) server.getTomcat().getConnector().findUpgradeProtocols()[0]).getKeepAliveTimeout()) - .isEqualTo(20000L)); + .isEqualTo(20000L)); } @Test @@ -120,7 +120,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.keep-alive-timeout=30s", "server.http2.enabled=true"); customizeAndRunServer((server) -> assertThat( ((Http2Protocol) server.getTomcat().getConnector().findUpgradeProtocols()[0]).getKeepAliveTimeout()) - .isEqualTo(30000L)); + .isEqualTo(30000L)); } @Test @@ -128,14 +128,16 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.max-keep-alive-requests=-1"); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getMaxKeepAliveRequests()).isEqualTo(-1)); + .getMaxKeepAliveRequests()) + .isEqualTo(-1)); } @Test void defaultMaxKeepAliveRequests() { customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getMaxKeepAliveRequests()).isEqualTo(100)); + .getMaxKeepAliveRequests()) + .isEqualTo(100)); } @Test @@ -143,7 +145,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.processor-cache=-1"); customizeAndRunServer((server) -> assertThat( ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getProcessorCache()) - .isEqualTo(-1)); + .isEqualTo(-1)); } @Test @@ -164,7 +166,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.max-connections=5"); customizeAndRunServer((server) -> assertThat( ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getMaxConnections()) - .isEqualTo(5)); + .isEqualTo(5)); } @Test @@ -179,19 +181,21 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.max-http-header-size=1KB"); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getMaxHttpHeaderSize()).isEqualTo(DataSize.ofKilobytes(1).toBytes())); + .getMaxHttpHeaderSize()) + .isEqualTo(DataSize.ofKilobytes(1).toBytes())); } @Test void customMaxHttpHeaderSizeWithHttp2() { bind("server.max-http-header-size=1KB", "server.http2.enabled=true"); customizeAndRunServer((server) -> { - AbstractHttp11Protocol protocolHandler = (AbstractHttp11Protocol) server.getTomcat().getConnector() - .getProtocolHandler(); + AbstractHttp11Protocol protocolHandler = (AbstractHttp11Protocol) server.getTomcat() + .getConnector() + .getProtocolHandler(); long expectedSize = DataSize.ofKilobytes(1).toBytes(); assertThat(protocolHandler.getMaxHttpHeaderSize()).isEqualTo(expectedSize); assertThat(((Http2Protocol) protocolHandler.getUpgradeProtocol("h2c")).getMaxHeaderSize()) - .isEqualTo(expectedSize); + .isEqualTo(expectedSize); }); } @@ -200,7 +204,8 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.max-http-header-size=-1"); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getMaxHttpHeaderSize()).isEqualTo(DataSize.ofKilobytes(8).toBytes())); + .getMaxHttpHeaderSize()) + .isEqualTo(DataSize.ofKilobytes(8).toBytes())); } @Test @@ -208,7 +213,8 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.max-http-header-size=0"); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getMaxHttpHeaderSize()).isEqualTo(DataSize.ofKilobytes(8).toBytes())); + .getMaxHttpHeaderSize()) + .isEqualTo(DataSize.ofKilobytes(8).toBytes())); } @Test @@ -216,7 +222,8 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.max-swallow-size=10MB"); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getMaxSwallowSize()).isEqualTo(DataSize.ofMegabytes(10).toBytes())); + .getMaxSwallowSize()) + .isEqualTo(DataSize.ofMegabytes(10).toBytes())); } @Test @@ -265,7 +272,8 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.relaxed-path-chars=|,^"); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getRelaxedPathChars()).isEqualTo("|^")); + .getRelaxedPathChars()) + .isEqualTo("|^")); } @Test @@ -273,7 +281,8 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.relaxed-query-chars=^ , | "); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getRelaxedQueryChars()).isEqualTo("^|")); + .getRelaxedQueryChars()) + .isEqualTo("^|")); } @Test @@ -355,7 +364,8 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.reject-illegal-header=false"); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getRejectIllegalHeader()).isFalse()); + .getRejectIllegalHeader()) + .isFalse()); } @Test @@ -383,7 +393,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.connection-timeout=30s"); customizeAndRunServer((server) -> assertThat( ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getConnectionTimeout()) - .isEqualTo(30000)); + .isEqualTo(30000)); } @Test @@ -406,7 +416,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getFileDateFormat()) - .isEqualTo(".yyyy-MM-dd"); + .isEqualTo(".yyyy-MM-dd"); } @Test @@ -414,7 +424,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.file-date-format=yyyy-MM-dd.HH"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getFileDateFormat()) - .isEqualTo("yyyy-MM-dd.HH"); + .isEqualTo("yyyy-MM-dd.HH"); } @Test @@ -435,7 +445,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getMaxDays()) - .isEqualTo(this.serverProperties.getTomcat().getAccesslog().getMaxDays()); + .isEqualTo(this.serverProperties.getTomcat().getAccesslog().getMaxDays()); } @Test @@ -445,10 +455,10 @@ class TomcatWebServerFactoryCustomizerTests { TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getConditionIf()).isEqualTo("foo"); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getConditionUnless()) - .isEqualTo("bar"); + .isEqualTo("bar"); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getCondition()) - .describedAs("value of condition should equal conditionUnless - provided for backwards compatibility") - .isEqualTo("bar"); + .describedAs("value of condition should equal conditionUnless - provided for backwards compatibility") + .isEqualTo("bar"); } @Test @@ -470,7 +480,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getLocale()) - .isEqualTo(Locale.getDefault().toString()); + .isEqualTo(Locale.getDefault().toString()); } @Test 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..6897cb9d62 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -249,9 +249,11 @@ 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) + ? new UndertowBuilderCustomizer[] { (UndertowBuilderCustomizer) argument } + : (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/format/WebConversionServiceTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/format/WebConversionServiceTests.java index dd6d51c340..d6e280710a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/format/WebConversionServiceTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/format/WebConversionServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ class WebConversionServiceTests { WebConversionService conversionService = new WebConversionService(new DateTimeFormatters()); LocalDate date = LocalDate.of(2020, 4, 26); assertThat(conversionService.convert(date, String.class)) - .isEqualTo(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).format(date)); + .isEqualTo(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).format(date)); } @Test @@ -55,7 +55,7 @@ class WebConversionServiceTests { WebConversionService conversionService = new WebConversionService(new DateTimeFormatters().dateFormat("iso")); LocalDate date = LocalDate.of(2020, 4, 26); assertThat(conversionService.convert(date, String.class)) - .isEqualTo(DateTimeFormatter.ISO_LOCAL_DATE.format(date)); + .isEqualTo(DateTimeFormatter.ISO_LOCAL_DATE.format(date)); } @Test @@ -73,7 +73,7 @@ class WebConversionServiceTests { WebConversionService conversionService = new WebConversionService(new DateTimeFormatters()); LocalTime time = LocalTime.of(12, 45, 23); assertThat(conversionService.convert(time, String.class)) - .isEqualTo(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).format(time)); + .isEqualTo(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).format(time)); } @Test @@ -81,7 +81,7 @@ class WebConversionServiceTests { WebConversionService conversionService = new WebConversionService(new DateTimeFormatters().timeFormat("iso")); LocalTime time = LocalTime.of(12, 45, 23); assertThat(conversionService.convert(time, String.class)) - .isEqualTo(DateTimeFormatter.ISO_LOCAL_TIME.format(time)); + .isEqualTo(DateTimeFormatter.ISO_LOCAL_TIME.format(time)); } @Test @@ -98,7 +98,7 @@ class WebConversionServiceTests { WebConversionService conversionService = new WebConversionService(formatters); OffsetTime offsetTime = OffsetTime.of(LocalTime.of(12, 45, 23), ZoneOffset.ofHoursMinutes(1, 30)); assertThat(conversionService.convert(offsetTime, String.class)) - .isEqualTo(DateTimeFormatter.ISO_OFFSET_TIME.format(offsetTime)); + .isEqualTo(DateTimeFormatter.ISO_OFFSET_TIME.format(offsetTime)); } @Test @@ -114,7 +114,7 @@ class WebConversionServiceTests { WebConversionService conversionService = new WebConversionService(new DateTimeFormatters()); LocalDateTime dateTime = LocalDateTime.of(2020, 4, 26, 12, 45, 23); assertThat(conversionService.convert(dateTime, String.class)) - .isEqualTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).format(dateTime)); + .isEqualTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).format(dateTime)); } @Test @@ -123,7 +123,7 @@ class WebConversionServiceTests { new DateTimeFormatters().dateTimeFormat("iso")); LocalDateTime dateTime = LocalDateTime.of(2020, 4, 26, 12, 45, 23); assertThat(conversionService.convert(dateTime, String.class)) - .isEqualTo(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(dateTime)); + .isEqualTo(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(dateTime)); } @Test @@ -141,7 +141,7 @@ class WebConversionServiceTests { OffsetDateTime offsetDateTime = OffsetDateTime.of(LocalDate.of(2020, 4, 26), LocalTime.of(12, 45, 23), ZoneOffset.ofHoursMinutes(1, 30)); assertThat(conversionService.convert(offsetDateTime, String.class)) - .isEqualTo(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(offsetDateTime)); + .isEqualTo(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(offsetDateTime)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java index 4c44adc556..70df1d0c2e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ import static org.springframework.web.reactive.function.server.RouterFunctions.r class HttpHandlerAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class)); @Test void shouldNotProcessIfExistingHttpHandler() { @@ -57,25 +57,26 @@ class HttpHandlerAutoConfigurationTests { @Test void shouldConfigureHttpHandlerAnnotation() { this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(HttpHandler.class)); + .run((context) -> assertThat(context).hasSingleBean(HttpHandler.class)); } @Test void shouldConfigureHttpHandlerWithoutWebFluxAutoConfiguration() { this.contextRunner.withUserConfiguration(CustomWebHandler.class) - .run((context) -> assertThat(context).hasSingleBean(HttpHandler.class)); + .run((context) -> assertThat(context).hasSingleBean(HttpHandler.class)); } @Test void shouldConfigureBasePathCompositeHandler() { this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) - .withPropertyValues("spring.webflux.base-path=/something").run((context) -> { - assertThat(context).hasSingleBean(HttpHandler.class); - HttpHandler httpHandler = context.getBean(HttpHandler.class); - assertThat(httpHandler).isInstanceOf(ContextPathCompositeHandler.class) - .extracting("handlerMap", InstanceOfAssertFactories.map(String.class, HttpHandler.class)) - .containsKey("/something"); - }); + .withPropertyValues("spring.webflux.base-path=/something") + .run((context) -> { + assertThat(context).hasSingleBean(HttpHandler.class); + HttpHandler httpHandler = context.getBean(HttpHandler.class); + assertThat(httpHandler).isInstanceOf(ContextPathCompositeHandler.class) + .extracting("handlerMap", InstanceOfAssertFactories.map(String.class, HttpHandler.class)) + .containsKey("/something"); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveMultipartAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveMultipartAutoConfigurationTests.java index 82b3093582..9375a9384b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveMultipartAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveMultipartAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,47 +40,52 @@ import static org.assertj.core.api.Assertions.assertThat; class ReactiveMultipartAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveMultipartAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveMultipartAutoConfiguration.class)); @Test void shouldNotProvideCustomizerForNonReactiveApp() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveMultipartAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(CodecCustomizer.class)); + .withConfiguration(AutoConfigurations.of(ReactiveMultipartAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(CodecCustomizer.class)); } @Test void shouldNotProvideCustomizerWhenWebFluxNotAvailable() { this.contextRunner.withClassLoader(new FilteredClassLoader(WebFluxConfigurer.class)) - .run((context) -> assertThat(context).doesNotHaveBean(CodecCustomizer.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CodecCustomizer.class)); } @Test void shouldConfigureMultipartProperties() { - this.contextRunner.withPropertyValues("spring.webflux.multipart.streaming:true", - "spring.webflux.multipart.max-in-memory-size=1GB", "spring.webflux.multipart.max-headers-size=16KB", - "spring.webflux.multipart.max-disk-usage-per-part=100MB", "spring.webflux.multipart.max-parts=7", - "spring.webflux.multipart.headers-charset:UTF_16").run((context) -> { - CodecCustomizer customizer = context.getBean(CodecCustomizer.class); - DefaultServerCodecConfigurer configurer = new DefaultServerCodecConfigurer(); - customizer.customize(configurer); - DefaultPartHttpMessageReader partReader = getPartReader(configurer); - assertThat(partReader).hasFieldOrPropertyWithValue("streaming", true); - assertThat(partReader).hasFieldOrPropertyWithValue("maxParts", 7); - assertThat(partReader).hasFieldOrPropertyWithValue("maxHeadersSize", - Math.toIntExact(DataSize.ofKilobytes(16).toBytes())); - assertThat(partReader).hasFieldOrPropertyWithValue("headersCharset", StandardCharsets.UTF_16); - assertThat(partReader).hasFieldOrPropertyWithValue("maxInMemorySize", - Math.toIntExact(DataSize.ofGigabytes(1).toBytes())); - assertThat(partReader).hasFieldOrPropertyWithValue("maxDiskUsagePerPart", - DataSize.ofMegabytes(100).toBytes()); - }); + this.contextRunner + .withPropertyValues("spring.webflux.multipart.streaming:true", + "spring.webflux.multipart.max-in-memory-size=1GB", "spring.webflux.multipart.max-headers-size=16KB", + "spring.webflux.multipart.max-disk-usage-per-part=100MB", "spring.webflux.multipart.max-parts=7", + "spring.webflux.multipart.headers-charset:UTF_16") + .run((context) -> { + CodecCustomizer customizer = context.getBean(CodecCustomizer.class); + DefaultServerCodecConfigurer configurer = new DefaultServerCodecConfigurer(); + customizer.customize(configurer); + DefaultPartHttpMessageReader partReader = getPartReader(configurer); + assertThat(partReader).hasFieldOrPropertyWithValue("streaming", true); + assertThat(partReader).hasFieldOrPropertyWithValue("maxParts", 7); + assertThat(partReader).hasFieldOrPropertyWithValue("maxHeadersSize", + Math.toIntExact(DataSize.ofKilobytes(16).toBytes())); + assertThat(partReader).hasFieldOrPropertyWithValue("headersCharset", StandardCharsets.UTF_16); + assertThat(partReader).hasFieldOrPropertyWithValue("maxInMemorySize", + Math.toIntExact(DataSize.ofGigabytes(1).toBytes())); + assertThat(partReader).hasFieldOrPropertyWithValue("maxDiskUsagePerPart", + DataSize.ofMegabytes(100).toBytes()); + }); } private DefaultPartHttpMessageReader getPartReader(DefaultServerCodecConfigurer codecConfigurer) { - return codecConfigurer.getReaders().stream().filter(DefaultPartHttpMessageReader.class::isInstance) - .map(DefaultPartHttpMessageReader.class::cast).findFirst() - .orElseThrow(() -> new IllegalStateException("Could not find DefaultPartHttpMessageReader")); + return codecConfigurer.getReaders() + .stream() + .filter(DefaultPartHttpMessageReader.class::isInstance) + .map(DefaultPartHttpMessageReader.class::cast) + .findFirst() + .orElseThrow(() -> new IllegalStateException("Could not find DefaultPartHttpMessageReader")); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfigurationTests.java index 4b549494d6..a2cdbd3b06 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,61 +67,59 @@ class ReactiveWebServerFactoryAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)); @Test void createFromConfigClass() { this.contextRunner.withUserConfiguration(MockWebServerConfiguration.class, HttpHandlerConfiguration.class) - .run((context) -> { - assertThat(context.getBeansOfType(ReactiveWebServerFactory.class)).hasSize(1); - assertThat(context.getBeansOfType(WebServerFactoryCustomizer.class)).hasSize(2); - assertThat(context.getBeansOfType(ReactiveWebServerFactoryCustomizer.class)).hasSize(1); - }); + .run((context) -> { + assertThat(context.getBeansOfType(ReactiveWebServerFactory.class)).hasSize(1); + assertThat(context.getBeansOfType(WebServerFactoryCustomizer.class)).hasSize(2); + assertThat(context.getBeansOfType(ReactiveWebServerFactoryCustomizer.class)).hasSize(1); + }); } @Test void missingHttpHandler() { this.contextRunner.withUserConfiguration(MockWebServerConfiguration.class) - .run((context) -> assertThat(context.getStartupFailure()) - .isInstanceOf(ApplicationContextException.class) - .hasMessageContaining("missing HttpHandler bean")); + .run((context) -> assertThat(context.getStartupFailure()).isInstanceOf(ApplicationContextException.class) + .hasMessageContaining("missing HttpHandler bean")); } @Test void multipleHttpHandler() { this.contextRunner - .withUserConfiguration(MockWebServerConfiguration.class, HttpHandlerConfiguration.class, - TooManyHttpHandlers.class) - .run((context) -> assertThat(context.getStartupFailure()) - .isInstanceOf(ApplicationContextException.class) - .hasMessageContaining("multiple HttpHandler beans : httpHandler,additionalHttpHandler")); + .withUserConfiguration(MockWebServerConfiguration.class, HttpHandlerConfiguration.class, + TooManyHttpHandlers.class) + .run((context) -> assertThat(context.getStartupFailure()).isInstanceOf(ApplicationContextException.class) + .hasMessageContaining("multiple HttpHandler beans : httpHandler,additionalHttpHandler")); } @Test void customizeReactiveWebServer() { this.contextRunner - .withUserConfiguration(MockWebServerConfiguration.class, HttpHandlerConfiguration.class, - ReactiveWebServerCustomization.class) - .run((context) -> assertThat(context.getBean(MockReactiveWebServerFactory.class).getPort()) - .isEqualTo(9000)); + .withUserConfiguration(MockWebServerConfiguration.class, HttpHandlerConfiguration.class, + ReactiveWebServerCustomization.class) + .run((context) -> assertThat(context.getBean(MockReactiveWebServerFactory.class).getPort()) + .isEqualTo(9000)); } @Test void defaultWebServerIsTomcat() { // Tomcat should be chosen over Netty if the Tomcat library is present. - this.contextRunner.withUserConfiguration(HttpHandlerConfiguration.class).withPropertyValues("server.port=0") - .run((context) -> assertThat(context.getBean(ReactiveWebServerFactory.class)) - .isInstanceOf(TomcatReactiveWebServerFactory.class)); + this.contextRunner.withUserConfiguration(HttpHandlerConfiguration.class) + .withPropertyValues("server.port=0") + .run((context) -> assertThat(context.getBean(ReactiveWebServerFactory.class)) + .isInstanceOf(TomcatReactiveWebServerFactory.class)); } @Test void tomcatConnectorCustomizerBeanIsAddedToFactory() { ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(HttpHandlerConfiguration.class, - TomcatConnectorCustomizerConfiguration.class) - .withPropertyValues("server.port: 0"); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(HttpHandlerConfiguration.class, TomcatConnectorCustomizerConfiguration.class) + .withPropertyValues("server.port: 0"); runner.run((context) -> { TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class); TomcatConnectorCustomizer customizer = context.getBean("connectorCustomizer", @@ -135,10 +133,10 @@ class ReactiveWebServerFactoryAutoConfigurationTests { void tomcatConnectorCustomizerRegisteredAsBeanAndViaFactoryIsOnlyCalledOnce() { ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(HttpHandlerConfiguration.class, - DoubleRegistrationTomcatConnectorCustomizerConfiguration.class) - .withPropertyValues("server.port: 0"); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(HttpHandlerConfiguration.class, + DoubleRegistrationTomcatConnectorCustomizerConfiguration.class) + .withPropertyValues("server.port: 0"); runner.run((context) -> { TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class); TomcatConnectorCustomizer customizer = context.getBean("connectorCustomizer", @@ -152,10 +150,9 @@ class ReactiveWebServerFactoryAutoConfigurationTests { void tomcatContextCustomizerBeanIsAddedToFactory() { ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(HttpHandlerConfiguration.class, - TomcatContextCustomizerConfiguration.class) - .withPropertyValues("server.port: 0"); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(HttpHandlerConfiguration.class, TomcatContextCustomizerConfiguration.class) + .withPropertyValues("server.port: 0"); runner.run((context) -> { TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class); TomcatContextCustomizer customizer = context.getBean("contextCustomizer", TomcatContextCustomizer.class); @@ -168,10 +165,10 @@ class ReactiveWebServerFactoryAutoConfigurationTests { void tomcatContextCustomizerRegisteredAsBeanAndViaFactoryIsOnlyCalledOnce() { ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(HttpHandlerConfiguration.class, - DoubleRegistrationTomcatContextCustomizerConfiguration.class) - .withPropertyValues("server.port: 0"); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(HttpHandlerConfiguration.class, + DoubleRegistrationTomcatContextCustomizerConfiguration.class) + .withPropertyValues("server.port: 0"); runner.run((context) -> { TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class); TomcatContextCustomizer customizer = context.getBean("contextCustomizer", TomcatContextCustomizer.class); @@ -184,10 +181,9 @@ class ReactiveWebServerFactoryAutoConfigurationTests { void tomcatProtocolHandlerCustomizerBeanIsAddedToFactory() { ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(HttpHandlerConfiguration.class, - TomcatProtocolHandlerCustomizerConfiguration.class) - .withPropertyValues("server.port: 0"); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(HttpHandlerConfiguration.class, TomcatProtocolHandlerCustomizerConfiguration.class) + .withPropertyValues("server.port: 0"); runner.run((context) -> { TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class); TomcatProtocolHandlerCustomizer customizer = context.getBean("protocolHandlerCustomizer", @@ -201,10 +197,10 @@ class ReactiveWebServerFactoryAutoConfigurationTests { void tomcatProtocolHandlerCustomizerRegisteredAsBeanAndViaFactoryIsOnlyCalledOnce() { ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(HttpHandlerConfiguration.class, - DoubleRegistrationTomcatProtocolHandlerCustomizerConfiguration.class) - .withPropertyValues("server.port: 0"); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(HttpHandlerConfiguration.class, + DoubleRegistrationTomcatProtocolHandlerCustomizerConfiguration.class) + .withPropertyValues("server.port: 0"); runner.run((context) -> { TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class); TomcatProtocolHandlerCustomizer customizer = context.getBean("protocolHandlerCustomizer", @@ -217,105 +213,108 @@ class ReactiveWebServerFactoryAutoConfigurationTests { @Test void jettyServerCustomizerBeanIsAddedToFactory() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class)) - .withUserConfiguration(JettyServerCustomizerConfiguration.class, HttpHandlerConfiguration.class) - .run((context) -> { - JettyReactiveWebServerFactory factory = context.getBean(JettyReactiveWebServerFactory.class); - assertThat(factory.getServerCustomizers()).hasSize(1); - }); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class)) + .withUserConfiguration(JettyServerCustomizerConfiguration.class, HttpHandlerConfiguration.class) + .run((context) -> { + JettyReactiveWebServerFactory factory = context.getBean(JettyReactiveWebServerFactory.class); + assertThat(factory.getServerCustomizers()).hasSize(1); + }); } @Test void jettyServerCustomizerRegisteredAsBeanAndViaFactoryIsOnlyCalledOnce() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class)) - .withUserConfiguration(DoubleRegistrationJettyServerCustomizerConfiguration.class, - HttpHandlerConfiguration.class) - .withPropertyValues("server.port=0").run((context) -> { - JettyReactiveWebServerFactory factory = context.getBean(JettyReactiveWebServerFactory.class); - JettyServerCustomizer customizer = context.getBean("serverCustomizer", JettyServerCustomizer.class); - assertThat(factory.getServerCustomizers()).contains(customizer); - then(customizer).should().customize(any(Server.class)); - }); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class)) + .withUserConfiguration(DoubleRegistrationJettyServerCustomizerConfiguration.class, + HttpHandlerConfiguration.class) + .withPropertyValues("server.port=0") + .run((context) -> { + JettyReactiveWebServerFactory factory = context.getBean(JettyReactiveWebServerFactory.class); + JettyServerCustomizer customizer = context.getBean("serverCustomizer", JettyServerCustomizer.class); + assertThat(factory.getServerCustomizers()).contains(customizer); + then(customizer).should().customize(any(Server.class)); + }); } @Test void undertowBuilderCustomizerBeanIsAddedToFactory() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class, Server.class)) - .withUserConfiguration(UndertowBuilderCustomizerConfiguration.class, HttpHandlerConfiguration.class) - .run((context) -> { - UndertowReactiveWebServerFactory factory = context.getBean(UndertowReactiveWebServerFactory.class); - assertThat(factory.getBuilderCustomizers()).hasSize(1); - }); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class, Server.class)) + .withUserConfiguration(UndertowBuilderCustomizerConfiguration.class, HttpHandlerConfiguration.class) + .run((context) -> { + UndertowReactiveWebServerFactory factory = context.getBean(UndertowReactiveWebServerFactory.class); + assertThat(factory.getBuilderCustomizers()).hasSize(1); + }); } @Test void undertowBuilderCustomizerRegisteredAsBeanAndViaFactoryIsOnlyCalledOnce() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class, Server.class)) - .withUserConfiguration(DoubleRegistrationUndertowBuilderCustomizerConfiguration.class, - HttpHandlerConfiguration.class) - .withPropertyValues("server.port: 0").run((context) -> { - UndertowReactiveWebServerFactory factory = context.getBean(UndertowReactiveWebServerFactory.class); - UndertowBuilderCustomizer customizer = context.getBean("builderCustomizer", - UndertowBuilderCustomizer.class); - assertThat(factory.getBuilderCustomizers()).contains(customizer); - then(customizer).should().customize(any(Builder.class)); - }); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class, Server.class)) + .withUserConfiguration(DoubleRegistrationUndertowBuilderCustomizerConfiguration.class, + HttpHandlerConfiguration.class) + .withPropertyValues("server.port: 0") + .run((context) -> { + UndertowReactiveWebServerFactory factory = context.getBean(UndertowReactiveWebServerFactory.class); + UndertowBuilderCustomizer customizer = context.getBean("builderCustomizer", + UndertowBuilderCustomizer.class); + assertThat(factory.getBuilderCustomizers()).contains(customizer); + then(customizer).should().customize(any(Builder.class)); + }); } @Test void nettyServerCustomizerBeanIsAddedToFactory() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(Tomcat.class, Server.class, Undertow.class)) - .withUserConfiguration(NettyServerCustomizerConfiguration.class, HttpHandlerConfiguration.class) - .run((context) -> { - NettyReactiveWebServerFactory factory = context.getBean(NettyReactiveWebServerFactory.class); - assertThat(factory.getServerCustomizers()).hasSize(1); - }); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(Tomcat.class, Server.class, Undertow.class)) + .withUserConfiguration(NettyServerCustomizerConfiguration.class, HttpHandlerConfiguration.class) + .run((context) -> { + NettyReactiveWebServerFactory factory = context.getBean(NettyReactiveWebServerFactory.class); + assertThat(factory.getServerCustomizers()).hasSize(1); + }); } @Test void nettyServerCustomizerRegisteredAsBeanAndViaFactoryIsOnlyCalledOnce() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(Tomcat.class, Server.class, Undertow.class)) - .withUserConfiguration(DoubleRegistrationNettyServerCustomizerConfiguration.class, - HttpHandlerConfiguration.class) - .withPropertyValues("server.port: 0").run((context) -> { - NettyReactiveWebServerFactory factory = context.getBean(NettyReactiveWebServerFactory.class); - NettyServerCustomizer customizer = context.getBean("serverCustomizer", NettyServerCustomizer.class); - assertThat(factory.getServerCustomizers()).contains(customizer); - then(customizer).should().apply(any(HttpServer.class)); - }); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(Tomcat.class, Server.class, Undertow.class)) + .withUserConfiguration(DoubleRegistrationNettyServerCustomizerConfiguration.class, + HttpHandlerConfiguration.class) + .withPropertyValues("server.port: 0") + .run((context) -> { + NettyReactiveWebServerFactory factory = context.getBean(NettyReactiveWebServerFactory.class); + NettyServerCustomizer customizer = context.getBean("serverCustomizer", NettyServerCustomizer.class); + assertThat(factory.getServerCustomizers()).contains(customizer); + then(customizer).should().apply(any(HttpServer.class)); + }); } @Test void forwardedHeaderTransformerShouldBeConfigured() { this.contextRunner.withUserConfiguration(HttpHandlerConfiguration.class) - .withPropertyValues("server.forward-headers-strategy=framework", "server.port=0") - .run((context) -> assertThat(context).hasSingleBean(ForwardedHeaderTransformer.class)); + .withPropertyValues("server.forward-headers-strategy=framework", "server.port=0") + .run((context) -> assertThat(context).hasSingleBean(ForwardedHeaderTransformer.class)); } @Test void forwardedHeaderTransformerWhenStrategyNotFilterShouldNotBeConfigured() { this.contextRunner.withUserConfiguration(HttpHandlerConfiguration.class) - .withPropertyValues("server.forward-headers-strategy=native", "server.port=0") - .run((context) -> assertThat(context).doesNotHaveBean(ForwardedHeaderTransformer.class)); + .withPropertyValues("server.forward-headers-strategy=native", "server.port=0") + .run((context) -> assertThat(context).doesNotHaveBean(ForwardedHeaderTransformer.class)); } @Test void forwardedHeaderTransformerWhenAlreadyRegisteredShouldBackOff() { this.contextRunner - .withUserConfiguration(ForwardedHeaderTransformerConfiguration.class, HttpHandlerConfiguration.class) - .withPropertyValues("server.forward-headers-strategy=framework", "server.port=0") - .run((context) -> assertThat(context).hasSingleBean(ForwardedHeaderTransformer.class)); + .withUserConfiguration(ForwardedHeaderTransformerConfiguration.class, HttpHandlerConfiguration.class) + .withPropertyValues("server.forward-headers-strategy=framework", "server.port=0") + .run((context) -> assertThat(context).hasSingleBean(ForwardedHeaderTransformer.class)); } @Configuration(proxyBeanMethods = false) 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 6fc59b80f7..bea61b39ce 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 @@ -117,9 +117,9 @@ class WebFluxAutoConfigurationTests { private static final MockReactiveWebServerFactory mockReactiveWebServerFactory = new MockReactiveWebServerFactory(); private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(WebFluxAutoConfiguration.class, WebSessionIdResolverAutoConfiguration.class)) - .withUserConfiguration(Config.class); + .withConfiguration( + AutoConfigurations.of(WebFluxAutoConfiguration.class, WebSessionIdResolverAutoConfiguration.class)) + .withUserConfiguration(Config.class); @Test void shouldNotProcessIfExistingWebReactiveConfiguration() { @@ -137,7 +137,7 @@ class WebFluxAutoConfigurationTests { assertThat(context).getBeans(RequestedContentTypeResolver.class).hasSize(1); assertThat(context).getBeans(RouterFunctionMapping.class).hasSize(1); assertThat(context.getBean(WebHttpHandlerBuilder.WEB_SESSION_MANAGER_BEAN_NAME, WebSessionManager.class)) - .isNotNull(); + .isNotNull(); assertThat(context.getBean("resourceHandlerMapping", HandlerMapping.class)).isNotNull(); }); } @@ -148,7 +148,7 @@ class WebFluxAutoConfigurationTests { this.contextRunner.withUserConfiguration(CustomArgumentResolvers.class).run((context) -> { RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class); List customResolvers = (List) ReflectionTestUtils - .getField(adapter.getArgumentResolverConfigurer(), "customResolvers"); + .getField(adapter.getArgumentResolverConfigurer(), "customResolvers"); assertThat(customResolvers).contains(context.getBean("firstResolver", HandlerMethodArgumentResolver.class), context.getBean("secondResolver", HandlerMethodArgumentResolver.class)); }); @@ -174,7 +174,7 @@ class WebFluxAutoConfigurationTests { ResourceWebHandler webjarsHandler = (ResourceWebHandler) hm.getUrlMap().get("/webjars/**"); assertThat(webjarsHandler.getLocations()).hasSize(1); assertThat(webjarsHandler.getLocations().get(0)) - .isEqualTo(new ClassPathResource("/META-INF/resources/webjars/")); + .isEqualTo(new ClassPathResource("/META-INF/resources/webjars/")); }); } @@ -191,8 +191,8 @@ class WebFluxAutoConfigurationTests { @Test void shouldNotMapResourcesWhenDisabled() { this.contextRunner.withPropertyValues("spring.web.resources.add-mappings:false") - .run((context) -> assertThat(context.getBean("resourceHandlerMapping")) - .isNotInstanceOf(SimpleUrlHandlerMapping.class)); + .run((context) -> assertThat(context.getBean("resourceHandlerMapping")) + .isNotInstanceOf(SimpleUrlHandlerMapping.class)); } @Test @@ -202,9 +202,9 @@ class WebFluxAutoConfigurationTests { assertThat(hm.getUrlMap().get("/**")).isInstanceOf(ResourceWebHandler.class); ResourceWebHandler staticHandler = (ResourceWebHandler) hm.getUrlMap().get("/**"); assertThat(staticHandler.getResourceResolvers()).extractingResultOf("getClass") - .containsOnly(CachingResourceResolver.class, PathResourceResolver.class); + .containsOnly(CachingResourceResolver.class, PathResourceResolver.class); assertThat(staticHandler.getResourceTransformers()).extractingResultOf("getClass") - .containsOnly(CachingResourceTransformer.class); + .containsOnly(CachingResourceTransformer.class); }); } @@ -243,7 +243,7 @@ class WebFluxAutoConfigurationTests { FormattingConversionService conversionService = context.getBean(FormattingConversionService.class); LocalTime time = LocalTime.of(11, 43, 10); assertThat(conversionService.convert(time, String.class)) - .isEqualTo(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).format(time)); + .isEqualTo(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).format(time)); }); } @@ -262,7 +262,7 @@ class WebFluxAutoConfigurationTests { FormattingConversionService conversionService = context.getBean(FormattingConversionService.class); LocalDateTime dateTime = LocalDateTime.of(2020, 4, 28, 11, 43, 10); assertThat(conversionService.convert(dateTime, String.class)) - .isEqualTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).format(dateTime)); + .isEqualTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).format(dateTime)); }); } @@ -287,19 +287,18 @@ class WebFluxAutoConfigurationTests { @Test void validatorWhenNoCustomizationShouldUseAutoConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) - .run((context) -> { - assertThat(context).getBeanNames(javax.validation.Validator.class) - .containsExactly("defaultValidator"); - assertThat(context).getBeanNames(Validator.class).containsExactlyInAnyOrder("defaultValidator", - "webFluxValidator"); - Validator validator = context.getBean("webFluxValidator", Validator.class); - assertThat(validator).isInstanceOf(ValidatorAdapter.class); - Object defaultValidator = context.getBean("defaultValidator"); - assertThat(((ValidatorAdapter) validator).getTarget()).isSameAs(defaultValidator); - // Primary Spring validator is the one used by WebFlux behind the - // scenes - assertThat(context.getBean(Validator.class)).isEqualTo(defaultValidator); - }); + .run((context) -> { + assertThat(context).getBeanNames(javax.validation.Validator.class).containsExactly("defaultValidator"); + assertThat(context).getBeanNames(Validator.class) + .containsExactlyInAnyOrder("defaultValidator", "webFluxValidator"); + Validator validator = context.getBean("webFluxValidator", Validator.class); + assertThat(validator).isInstanceOf(ValidatorAdapter.class); + Object defaultValidator = context.getBean("defaultValidator"); + assertThat(((ValidatorAdapter) validator).getTarget()).isSameAs(defaultValidator); + // Primary Spring validator is the one used by WebFlux behind the + // scenes + assertThat(context.getBean(Validator.class)).isEqualTo(defaultValidator); + }); } @Test @@ -309,7 +308,7 @@ class WebFluxAutoConfigurationTests { assertThat(context).doesNotHaveBean(javax.validation.Validator.class); assertThat(context).getBeanNames(Validator.class).containsOnly("webFluxValidator"); assertThat(context.getBean("webFluxValidator")) - .isSameAs(context.getBean(ValidatorWebFluxConfigurer.class).validator); + .isSameAs(context.getBean(ValidatorWebFluxConfigurer.class).validator); }); } @@ -322,42 +321,43 @@ class WebFluxAutoConfigurationTests { Validator validator = context.getBean("webFluxValidator", Validator.class); assertThat(validator).isInstanceOf(ValidatorAdapter.class); assertThat(((ValidatorAdapter) validator).getTarget()) - .isSameAs(context.getBean(ValidatorJsr303WebFluxConfigurer.class).validator); + .isSameAs(context.getBean(ValidatorJsr303WebFluxConfigurer.class).validator); }); } @Test void validationCustomConfigurerTakesPrecedence() { this.contextRunner.withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) - .withUserConfiguration(ValidatorWebFluxConfigurer.class).run((context) -> { - assertThat(context).getBeans(ValidatorFactory.class).hasSize(1); - assertThat(context).getBeans(javax.validation.Validator.class).hasSize(1); - assertThat(context).getBeanNames(Validator.class).containsExactlyInAnyOrder("defaultValidator", - "webFluxValidator"); - assertThat(context.getBean("webFluxValidator")) - .isSameAs(context.getBean(ValidatorWebFluxConfigurer.class).validator); - // Primary Spring validator is the auto-configured one as the WebFlux - // one has been customized through a WebFluxConfigurer - assertThat(context.getBean(Validator.class)).isEqualTo(context.getBean("defaultValidator")); - }); + .withUserConfiguration(ValidatorWebFluxConfigurer.class) + .run((context) -> { + assertThat(context).getBeans(ValidatorFactory.class).hasSize(1); + assertThat(context).getBeans(javax.validation.Validator.class).hasSize(1); + assertThat(context).getBeanNames(Validator.class) + .containsExactlyInAnyOrder("defaultValidator", "webFluxValidator"); + assertThat(context.getBean("webFluxValidator")) + .isSameAs(context.getBean(ValidatorWebFluxConfigurer.class).validator); + // Primary Spring validator is the auto-configured one as the WebFlux + // one has been customized through a WebFluxConfigurer + assertThat(context.getBean(Validator.class)).isEqualTo(context.getBean("defaultValidator")); + }); } @Test void validatorWithCustomSpringValidatorIgnored() { this.contextRunner.withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) - .withUserConfiguration(CustomSpringValidator.class).run((context) -> { - assertThat(context).getBeanNames(javax.validation.Validator.class) - .containsExactly("defaultValidator"); - assertThat(context).getBeanNames(Validator.class).containsExactlyInAnyOrder("customValidator", - "defaultValidator", "webFluxValidator"); - Validator validator = context.getBean("webFluxValidator", Validator.class); - assertThat(validator).isInstanceOf(ValidatorAdapter.class); - Object defaultValidator = context.getBean("defaultValidator"); - assertThat(((ValidatorAdapter) validator).getTarget()).isSameAs(defaultValidator); - // Primary Spring validator is the one used by WebFlux behind the - // scenes - assertThat(context.getBean(Validator.class)).isEqualTo(defaultValidator); - }); + .withUserConfiguration(CustomSpringValidator.class) + .run((context) -> { + assertThat(context).getBeanNames(javax.validation.Validator.class).containsExactly("defaultValidator"); + assertThat(context).getBeanNames(Validator.class) + .containsExactlyInAnyOrder("customValidator", "defaultValidator", "webFluxValidator"); + Validator validator = context.getBean("webFluxValidator", Validator.class); + assertThat(validator).isInstanceOf(ValidatorAdapter.class); + Object defaultValidator = context.getBean("defaultValidator"); + assertThat(((ValidatorAdapter) validator).getTarget()).isSameAs(defaultValidator); + // Primary Spring validator is the one used by WebFlux behind the + // scenes + assertThat(context.getBean(Validator.class)).isEqualTo(defaultValidator); + }); } @Test @@ -381,23 +381,24 @@ class WebFluxAutoConfigurationTests { @Test void hiddenHttpMethodFilterCanBeOverridden() { this.contextRunner.withPropertyValues("spring.webflux.hiddenmethod.filter.enabled=true") - .withUserConfiguration(CustomHiddenHttpMethodFilter.class).run((context) -> { - assertThat(context).doesNotHaveBean(OrderedHiddenHttpMethodFilter.class); - assertThat(context).hasSingleBean(HiddenHttpMethodFilter.class); - }); + .withUserConfiguration(CustomHiddenHttpMethodFilter.class) + .run((context) -> { + assertThat(context).doesNotHaveBean(OrderedHiddenHttpMethodFilter.class); + assertThat(context).hasSingleBean(HiddenHttpMethodFilter.class); + }); } @Test void hiddenHttpMethodFilterCanBeEnabled() { this.contextRunner.withPropertyValues("spring.webflux.hiddenmethod.filter.enabled=true") - .run((context) -> assertThat(context).hasSingleBean(OrderedHiddenHttpMethodFilter.class)); + .run((context) -> assertThat(context).hasSingleBean(OrderedHiddenHttpMethodFilter.class)); } @Test void customRequestMappingHandlerMapping() { this.contextRunner.withUserConfiguration(CustomRequestMappingHandlerMapping.class).run((context) -> { assertThat(context).getBean(RequestMappingHandlerMapping.class) - .isInstanceOf(MyRequestMappingHandlerMapping.class); + .isInstanceOf(MyRequestMappingHandlerMapping.class); assertThat(context.getBean(CustomRequestMappingHandlerMapping.class).handlerMappings).isEqualTo(1); }); } @@ -406,7 +407,7 @@ class WebFluxAutoConfigurationTests { void customRequestMappingHandlerAdapter() { this.contextRunner.withUserConfiguration(CustomRequestMappingHandlerAdapter.class).run((context) -> { assertThat(context).getBean(RequestMappingHandlerAdapter.class) - .isInstanceOf(MyRequestMappingHandlerAdapter.class); + .isInstanceOf(MyRequestMappingHandlerAdapter.class); assertThat(context.getBean(CustomRequestMappingHandlerAdapter.class).handlerAdapters).isEqualTo(1); }); } @@ -415,9 +416,9 @@ class WebFluxAutoConfigurationTests { void multipleWebFluxRegistrations() { this.contextRunner.withUserConfiguration(MultipleWebFluxRegistrations.class).run((context) -> { assertThat(context.getBean(RequestMappingHandlerMapping.class)) - .isNotInstanceOf(MyRequestMappingHandlerMapping.class); + .isNotInstanceOf(MyRequestMappingHandlerMapping.class); assertThat(context.getBean(RequestMappingHandlerAdapter.class)) - .isNotInstanceOf(MyRequestMappingHandlerAdapter.class); + .isNotInstanceOf(MyRequestMappingHandlerAdapter.class); }); } @@ -430,7 +431,7 @@ class WebFluxAutoConfigurationTests { for (Object handler : handlerMap.values()) { if (handler instanceof ResourceWebHandler) { assertThat(((ResourceWebHandler) handler).getCacheControl()).usingRecursiveComparison() - .isEqualTo(CacheControl.maxAge(5, TimeUnit.SECONDS)); + .isEqualTo(CacheControl.maxAge(5, TimeUnit.SECONDS)); } } }); @@ -440,17 +441,19 @@ class WebFluxAutoConfigurationTests { @Test void cacheControl() { Assertions.setExtractBareNamePropertyMethods(false); - this.contextRunner.withPropertyValues("spring.web.resources.cache.cachecontrol.max-age:5", - "spring.web.resources.cache.cachecontrol.proxy-revalidate:true").run((context) -> { - Map handlerMap = getHandlerMap(context); - assertThat(handlerMap).hasSize(2); - for (Object handler : handlerMap.values()) { - if (handler instanceof ResourceWebHandler) { - assertThat(((ResourceWebHandler) handler).getCacheControl()).usingRecursiveComparison() - .isEqualTo(CacheControl.maxAge(5, TimeUnit.SECONDS).proxyRevalidate()); - } + this.contextRunner + .withPropertyValues("spring.web.resources.cache.cachecontrol.max-age:5", + "spring.web.resources.cache.cachecontrol.proxy-revalidate:true") + .run((context) -> { + Map handlerMap = getHandlerMap(context); + assertThat(handlerMap).hasSize(2); + for (Object handler : handlerMap.values()) { + if (handler instanceof ResourceWebHandler) { + assertThat(((ResourceWebHandler) handler).getCacheControl()).usingRecursiveComparison() + .isEqualTo(CacheControl.maxAge(5, TimeUnit.SECONDS).proxyRevalidate()); } - }); + } + }); Assertions.setExtractBareNamePropertyMethods(true); } @@ -470,21 +473,22 @@ class WebFluxAutoConfigurationTests { @Test void customPrinterAndParserShouldBeRegisteredAsConverters() { this.contextRunner.withUserConfiguration(ParserConfiguration.class, PrinterConfiguration.class) - .run((context) -> { - ConversionService service = context.getBean(ConversionService.class); - assertThat(service.convert(new Example("spring", new Date()), String.class)).isEqualTo("spring"); - assertThat(service.convert("boot", Example.class)).extracting(Example::getName).isEqualTo("boot"); - }); + .run((context) -> { + ConversionService service = context.getBean(ConversionService.class); + assertThat(service.convert(new Example("spring", new Date()), String.class)).isEqualTo("spring"); + assertThat(service.convert("boot", Example.class)).extracting(Example::getName).isEqualTo("boot"); + }); } @Test void welcomePageHandlerMapping() { this.contextRunner.withPropertyValues("spring.web.resources.static-locations=classpath:/welcome-page/") - .run((context) -> { - assertThat(context).getBeans(RouterFunctionMapping.class).hasSize(2); - assertThat(context.getBean("welcomePageRouterFunctionMapping", HandlerMapping.class)).isNotNull() - .extracting("order").isEqualTo(1); - }); + .run((context) -> { + assertThat(context).getBeans(RouterFunctionMapping.class).hasSize(2); + assertThat(context.getBean("welcomePageRouterFunctionMapping", HandlerMapping.class)).isNotNull() + .extracting("order") + .isEqualTo(1); + }); } @Test @@ -499,22 +503,24 @@ class WebFluxAutoConfigurationTests { @Test void whenFixedLocalContextResolverIsUsedThenAcceptLanguagesHeaderIsIgnored() { this.contextRunner.withPropertyValues("spring.web.locale:en_UK", "spring.web.locale-resolver=fixed") - .run((context) -> { - MockServerHttpRequest request = MockServerHttpRequest.get("/") - .acceptLanguageAsLocales(StringUtils.parseLocaleString("nl_NL")).build(); - MockServerWebExchange exchange = MockServerWebExchange.from(request); - LocaleContextResolver localeContextResolver = context.getBean(LocaleContextResolver.class); - assertThat(localeContextResolver).isInstanceOf(FixedLocaleContextResolver.class); - LocaleContext localeContext = localeContextResolver.resolveLocaleContext(exchange); - assertThat(localeContext.getLocale()).isEqualTo(StringUtils.parseLocaleString("en_UK")); - }); + .run((context) -> { + MockServerHttpRequest request = MockServerHttpRequest.get("/") + .acceptLanguageAsLocales(StringUtils.parseLocaleString("nl_NL")) + .build(); + MockServerWebExchange exchange = MockServerWebExchange.from(request); + LocaleContextResolver localeContextResolver = context.getBean(LocaleContextResolver.class); + assertThat(localeContextResolver).isInstanceOf(FixedLocaleContextResolver.class); + LocaleContext localeContext = localeContextResolver.resolveLocaleContext(exchange); + assertThat(localeContext.getLocale()).isEqualTo(StringUtils.parseLocaleString("en_UK")); + }); } @Test void whenAcceptHeaderLocaleContextResolverIsUsedThenAcceptLanguagesHeaderIsHonoured() { this.contextRunner.withPropertyValues("spring.web.locale:en_UK").run((context) -> { MockServerHttpRequest request = MockServerHttpRequest.get("/") - .acceptLanguageAsLocales(StringUtils.parseLocaleString("nl_NL")).build(); + .acceptLanguageAsLocales(StringUtils.parseLocaleString("nl_NL")) + .build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); LocaleContextResolver localeContextResolver = context.getBean(LocaleContextResolver.class); assertThat(localeContextResolver).isInstanceOf(AcceptHeaderLocaleContextResolver.class); @@ -538,66 +544,72 @@ class WebFluxAutoConfigurationTests { @Test void customLocaleContextResolverWithMatchingNameReplacedAutoConfiguredLocaleContextResolver() { this.contextRunner - .withBean("localeContextResolver", CustomLocaleContextResolver.class, CustomLocaleContextResolver::new) - .run((context) -> { - assertThat(context).hasSingleBean(LocaleContextResolver.class); - assertThat(context.getBean("localeContextResolver")) - .isInstanceOf(CustomLocaleContextResolver.class); - }); + .withBean("localeContextResolver", CustomLocaleContextResolver.class, CustomLocaleContextResolver::new) + .run((context) -> { + assertThat(context).hasSingleBean(LocaleContextResolver.class); + assertThat(context.getBean("localeContextResolver")).isInstanceOf(CustomLocaleContextResolver.class); + }); } @Test void customLocaleContextResolverWithDifferentNameDoesNotReplaceAutoConfiguredLocaleContextResolver() { - this.contextRunner.withBean("customLocaleContextResolver", CustomLocaleContextResolver.class, - CustomLocaleContextResolver::new).run((context) -> { - assertThat(context.getBean("customLocaleContextResolver")) - .isInstanceOf(CustomLocaleContextResolver.class); - assertThat(context.getBean("localeContextResolver")) - .isInstanceOf(AcceptHeaderLocaleContextResolver.class); - }); + this.contextRunner + .withBean("customLocaleContextResolver", CustomLocaleContextResolver.class, + CustomLocaleContextResolver::new) + .run((context) -> { + assertThat(context.getBean("customLocaleContextResolver")) + .isInstanceOf(CustomLocaleContextResolver.class); + assertThat(context.getBean("localeContextResolver")) + .isInstanceOf(AcceptHeaderLocaleContextResolver.class); + }); } @Test @SuppressWarnings("rawtypes") void userConfigurersCanBeOrderedBeforeOrAfterTheAutoConfiguredConfigurer() { this.contextRunner.withBean(HighPrecedenceConfigurer.class, HighPrecedenceConfigurer::new) - .withBean(LowPrecedenceConfigurer.class, LowPrecedenceConfigurer::new) - .run((context) -> assertThat(context.getBean(DelegatingWebFluxConfiguration.class)) - .extracting("configurers.delegates").asList() - .extracting((configurer) -> (Class) configurer.getClass()).containsExactly( - HighPrecedenceConfigurer.class, WebFluxConfig.class, LowPrecedenceConfigurer.class)); + .withBean(LowPrecedenceConfigurer.class, LowPrecedenceConfigurer::new) + .run((context) -> assertThat(context.getBean(DelegatingWebFluxConfiguration.class)) + .extracting("configurers.delegates") + .asList() + .extracting((configurer) -> (Class) configurer.getClass()) + .containsExactly(HighPrecedenceConfigurer.class, WebFluxConfig.class, LowPrecedenceConfigurer.class)); } @Test void customWebSessionIdResolverShouldBeApplied() { - this.contextRunner.withUserConfiguration(CustomWebSessionIdResolver.class).run(assertExchangeWithSession( - (exchange) -> assertThat(exchange.getResponse().getCookies().get("TEST")).isNotEmpty())); + this.contextRunner.withUserConfiguration(CustomWebSessionIdResolver.class) + .run(assertExchangeWithSession( + (exchange) -> assertThat(exchange.getResponse().getCookies().get("TEST")).isNotEmpty())); } @Test void customSessionTimeoutConfigurationShouldBeApplied() { this.contextRunner.withPropertyValues("server.reactive.session.timeout:123") - .run((assertSessionTimeoutWithWebSession((webSession) -> { - webSession.start(); - assertThat(webSession.getMaxIdleTime()).hasSeconds(123); - }))); + .run((assertSessionTimeoutWithWebSession((webSession) -> { + webSession.start(); + assertThat(webSession.getMaxIdleTime()).hasSeconds(123); + }))); } @Test void sameSiteAttributesAreExclusive() { - this.contextRunner.withPropertyValues("spring.webflux.session.cookie.same-site:strict", - "server.reactive.session.cookie.same-site:strict").run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure() - .hasRootCauseExactlyInstanceOf(MutuallyExclusiveConfigurationPropertiesException.class); - }); + this.contextRunner + .withPropertyValues("spring.webflux.session.cookie.same-site:strict", + "server.reactive.session.cookie.same-site:strict") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure() + .hasRootCauseExactlyInstanceOf(MutuallyExclusiveConfigurationPropertiesException.class); + }); } @Test void deprecatedCustomSameSiteConfigurationShouldBeApplied() { - this.contextRunner.withPropertyValues("spring.webflux.session.cookie.same-site:strict").run( - assertExchangeWithSession((exchange) -> assertThat(exchange.getResponse().getCookies().get("SESSION")) - .isNotEmpty().allMatch((cookie) -> cookie.getSameSite().equals("Strict")))); + this.contextRunner.withPropertyValues("spring.webflux.session.cookie.same-site:strict") + .run(assertExchangeWithSession( + (exchange) -> assertThat(exchange.getResponse().getCookies().get("SESSION")).isNotEmpty() + .allMatch((cookie) -> cookie.getSameSite().equals("Strict")))); } @Test @@ -606,25 +618,25 @@ class WebFluxAutoConfigurationTests { "server.reactive.session.cookie.domain:.example.com", "server.reactive.session.cookie.path:/example", "server.reactive.session.cookie.max-age:60", "server.reactive.session.cookie.http-only:false", "server.reactive.session.cookie.secure:false", "server.reactive.session.cookie.same-site:strict") - .run(assertExchangeWithSession((exchange) -> { - List cookies = exchange.getResponse().getCookies().get("JSESSIONID"); - assertThat(cookies).isNotEmpty(); - assertThat(cookies).allMatch((cookie) -> cookie.getDomain().equals(".example.com")); - assertThat(cookies).allMatch((cookie) -> cookie.getPath().equals("/example")); - assertThat(cookies).allMatch((cookie) -> cookie.getMaxAge().equals(Duration.ofSeconds(60))); - assertThat(cookies).allMatch((cookie) -> !cookie.isHttpOnly()); - assertThat(cookies).allMatch((cookie) -> !cookie.isSecure()); - assertThat(cookies).allMatch((cookie) -> cookie.getSameSite().equals("Strict")); - })); + .run(assertExchangeWithSession((exchange) -> { + List cookies = exchange.getResponse().getCookies().get("JSESSIONID"); + assertThat(cookies).isNotEmpty(); + assertThat(cookies).allMatch((cookie) -> cookie.getDomain().equals(".example.com")); + assertThat(cookies).allMatch((cookie) -> cookie.getPath().equals("/example")); + assertThat(cookies).allMatch((cookie) -> cookie.getMaxAge().equals(Duration.ofSeconds(60))); + assertThat(cookies).allMatch((cookie) -> !cookie.isHttpOnly()); + assertThat(cookies).allMatch((cookie) -> !cookie.isSecure()); + assertThat(cookies).allMatch((cookie) -> cookie.getSameSite().equals("Strict")); + })); } @ParameterizedTest @ValueSource(classes = { ServerProperties.class, WebFluxProperties.class }) void propertiesAreNotEnabledInNonWebApplication(Class propertiesClass) { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class, - WebSessionIdResolverAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(propertiesClass)); + .withConfiguration( + AutoConfigurations.of(WebFluxAutoConfiguration.class, WebSessionIdResolverAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(propertiesClass)); } private ContextConsumer assertExchangeWithSession( diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WelcomePageRouterFunctionFactoryTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WelcomePageRouterFunctionFactoryTests.java index c6c8499083..7a464da43e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WelcomePageRouterFunctionFactoryTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WelcomePageRouterFunctionFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,15 +63,27 @@ class WelcomePageRouterFunctionFactoryTests { @Test void handlesRequestForStaticPageThatAcceptsTextHtml() { WebTestClient client = withStaticIndex(); - client.get().uri("/").accept(MediaType.TEXT_HTML).exchange().expectStatus().isOk().expectBody(String.class) - .isEqualTo("welcome-page-static"); + client.get() + .uri("/") + .accept(MediaType.TEXT_HTML) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("welcome-page-static"); } @Test void handlesRequestForStaticPageThatAcceptsAll() { WebTestClient client = withStaticIndex(); - client.get().uri("/").accept(MediaType.ALL).exchange().expectStatus().isOk().expectBody(String.class) - .isEqualTo("welcome-page-static"); + client.get() + .uri("/") + .accept(MediaType.ALL) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("welcome-page-static"); } @Test @@ -83,15 +95,26 @@ class WelcomePageRouterFunctionFactoryTests { @Test void handlesRequestWithNoAcceptHeader() { WebTestClient client = withStaticIndex(); - client.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class) - .isEqualTo("welcome-page-static"); + client.get() + .uri("/") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("welcome-page-static"); } @Test void handlesRequestWithEmptyAcceptHeader() { WebTestClient client = withStaticIndex(); - client.get().uri("/").header(HttpHeaders.ACCEPT, "").exchange().expectStatus().isOk().expectBody(String.class) - .isEqualTo("welcome-page-static"); + client.get() + .uri("/") + .header(HttpHeaders.ACCEPT, "") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("welcome-page-static"); } @Test @@ -103,22 +126,40 @@ class WelcomePageRouterFunctionFactoryTests { @Test void handlesRequestForTemplateThatAcceptsTextHtml() { WebTestClient client = withTemplateIndex(); - client.get().uri("/").accept(MediaType.TEXT_HTML).exchange().expectStatus().isOk().expectBody(String.class) - .isEqualTo("welcome-page-template"); + client.get() + .uri("/") + .accept(MediaType.TEXT_HTML) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("welcome-page-template"); } @Test void handlesRequestForTemplateThatAcceptsAll() { WebTestClient client = withTemplateIndex(); - client.get().uri("/").accept(MediaType.ALL).exchange().expectStatus().isOk().expectBody(String.class) - .isEqualTo("welcome-page-template"); + client.get() + .uri("/") + .accept(MediaType.ALL) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("welcome-page-template"); } @Test void prefersAStaticResourceToATemplate() { WebTestClient client = withStaticAndTemplateIndex(); - client.get().uri("/").accept(MediaType.ALL).exchange().expectStatus().isOk().expectBody(String.class) - .isEqualTo("welcome-page-static"); + client.get() + .uri("/") + .accept(MediaType.ALL) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("welcome-page-static"); } private WebTestClient withStaticIndex() { @@ -130,14 +171,16 @@ class WelcomePageRouterFunctionFactoryTests { WelcomePageRouterFunctionFactory factory = factoryWithTemplateSupport(this.noIndexLocations); TestViewResolver testViewResolver = new TestViewResolver(); return WebTestClient.bindToRouterFunction(factory.createRouterFunction()) - .handlerStrategies(HandlerStrategies.builder().viewResolver(testViewResolver).build()).build(); + .handlerStrategies(HandlerStrategies.builder().viewResolver(testViewResolver).build()) + .build(); } private WebTestClient withStaticAndTemplateIndex() { WelcomePageRouterFunctionFactory factory = factoryWithTemplateSupport(this.indexLocations); TestViewResolver testViewResolver = new TestViewResolver(); return WebTestClient.bindToRouterFunction(factory.createRouterFunction()) - .handlerStrategies(HandlerStrategies.builder().viewResolver(testViewResolver).build()).build(); + .handlerStrategies(HandlerStrategies.builder().viewResolver(testViewResolver).build()) + .build(); } private WelcomePageRouterFunctionFactory factoryWithoutTemplateSupport(String[] locations, diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java index 576935cbd7..875878355b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,24 +73,38 @@ class DefaultErrorWebExceptionHandlerIntegrationTests { private final LogIdFilter logIdFilter = new LogIdFilter(); private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class, - HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, - ErrorWebFluxAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - MustacheAutoConfiguration.class)) - .withPropertyValues("spring.main.web-application-type=reactive", "server.port=0") - .withUserConfiguration(Application.class); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class, + HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, ErrorWebFluxAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, MustacheAutoConfiguration.class)) + .withPropertyValues("spring.main.web-application-type=reactive", "server.port=0") + .withUserConfiguration(Application.class); @Test void jsonError(CapturedOutput output) { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); - client.get().uri("/").exchange().expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody() - .jsonPath("status").isEqualTo("500").jsonPath("error") - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("path").isEqualTo(("/")) - .jsonPath("message").doesNotExist().jsonPath("exception").doesNotExist().jsonPath("trace") - .doesNotExist().jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); + client.get() + .uri("/") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody() + .jsonPath("status") + .isEqualTo("500") + .jsonPath("error") + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) + .jsonPath("path") + .isEqualTo(("/")) + .jsonPath("message") + .doesNotExist() + .jsonPath("exception") + .doesNotExist() + .jsonPath("trace") + .doesNotExist() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); assertThat(output).contains("500 Server Error for HTTP GET \"/\"") - .contains("java.lang.IllegalStateException: Expected!"); + .contains("java.lang.IllegalStateException: Expected!"); }); } @@ -98,10 +112,22 @@ class DefaultErrorWebExceptionHandlerIntegrationTests { void notFound() { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); - client.get().uri("/notFound").exchange().expectStatus().isNotFound().expectBody().jsonPath("status") - .isEqualTo("404").jsonPath("error").isEqualTo(HttpStatus.NOT_FOUND.getReasonPhrase()) - .jsonPath("path").isEqualTo(("/notFound")).jsonPath("exception").doesNotExist() - .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); + client.get() + .uri("/notFound") + .exchange() + .expectStatus() + .isNotFound() + .expectBody() + .jsonPath("status") + .isEqualTo("404") + .jsonPath("error") + .isEqualTo(HttpStatus.NOT_FOUND.getReasonPhrase()) + .jsonPath("path") + .isEqualTo(("/notFound")) + .jsonPath("exception") + .doesNotExist() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); }); } @@ -109,9 +135,17 @@ class DefaultErrorWebExceptionHandlerIntegrationTests { void htmlError() { this.contextRunner.withPropertyValues("server.error.include-message=always").run((context) -> { WebTestClient client = getWebClient(context); - String body = client.get().uri("/").accept(MediaType.TEXT_HTML).exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader().contentType(TEXT_HTML_UTF8) - .expectBody(String.class).returnResult().getResponseBody(); + String body = client.get() + .uri("/") + .accept(MediaType.TEXT_HTML) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectHeader() + .contentType(TEXT_HTML_UTF8) + .expectBody(String.class) + .returnResult() + .getResponseBody(); assertThat(body).contains("status: 500").contains("message: Expected!"); }); } @@ -120,168 +154,300 @@ class DefaultErrorWebExceptionHandlerIntegrationTests { void bindingResultError() { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); - client.post().uri("/bind").contentType(MediaType.APPLICATION_JSON).bodyValue("{}").exchange().expectStatus() - .isBadRequest().expectBody().jsonPath("status").isEqualTo("400").jsonPath("error") - .isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()).jsonPath("path").isEqualTo(("/bind")) - .jsonPath("exception").doesNotExist().jsonPath("errors").doesNotExist().jsonPath("message") - .doesNotExist().jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); + client.post() + .uri("/bind") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue("{}") + .exchange() + .expectStatus() + .isBadRequest() + .expectBody() + .jsonPath("status") + .isEqualTo("400") + .jsonPath("error") + .isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()) + .jsonPath("path") + .isEqualTo(("/bind")) + .jsonPath("exception") + .doesNotExist() + .jsonPath("errors") + .doesNotExist() + .jsonPath("message") + .doesNotExist() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); }); } @Test void bindingResultErrorIncludeMessageAndErrors() { - this.contextRunner.withPropertyValues("server.error.include-message=on-param", - "server.error.include-binding-errors=on-param").run((context) -> { - WebTestClient client = getWebClient(context); - client.post().uri("/bind?message=true&errors=true").contentType(MediaType.APPLICATION_JSON) - .bodyValue("{}").exchange().expectStatus().isBadRequest().expectBody().jsonPath("status") - .isEqualTo("400").jsonPath("error").isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()) - .jsonPath("path").isEqualTo(("/bind")).jsonPath("exception").doesNotExist() - .jsonPath("errors").isArray().jsonPath("message").isNotEmpty().jsonPath("requestId") - .isEqualTo(this.logIdFilter.getLogId()); - }); + this.contextRunner + .withPropertyValues("server.error.include-message=on-param", "server.error.include-binding-errors=on-param") + .run((context) -> { + WebTestClient client = getWebClient(context); + client.post() + .uri("/bind?message=true&errors=true") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue("{}") + .exchange() + .expectStatus() + .isBadRequest() + .expectBody() + .jsonPath("status") + .isEqualTo("400") + .jsonPath("error") + .isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()) + .jsonPath("path") + .isEqualTo(("/bind")) + .jsonPath("exception") + .doesNotExist() + .jsonPath("errors") + .isArray() + .jsonPath("message") + .isNotEmpty() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); + }); } @Test void includeStackTraceOnParam() { this.contextRunner - .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=on-param") - .run((context) -> { - WebTestClient client = getWebClient(context); - client.get().uri("/?trace=true").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody().jsonPath("status") - .isEqualTo("500").jsonPath("error") - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("exception") - .isEqualTo(IllegalStateException.class.getName()).jsonPath("trace").exists() - .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); - }); + .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=on-param") + .run((context) -> { + WebTestClient client = getWebClient(context); + client.get() + .uri("/?trace=true") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody() + .jsonPath("status") + .isEqualTo("500") + .jsonPath("error") + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) + .jsonPath("exception") + .isEqualTo(IllegalStateException.class.getName()) + .jsonPath("trace") + .exists() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); + }); } @Test void alwaysIncludeStackTrace() { this.contextRunner - .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=always") - .run((context) -> { - WebTestClient client = getWebClient(context); - client.get().uri("/?trace=false").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody().jsonPath("status") - .isEqualTo("500").jsonPath("error") - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("exception") - .isEqualTo(IllegalStateException.class.getName()).jsonPath("trace").exists() - .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); - }); + .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=always") + .run((context) -> { + WebTestClient client = getWebClient(context); + client.get() + .uri("/?trace=false") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody() + .jsonPath("status") + .isEqualTo("500") + .jsonPath("error") + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) + .jsonPath("exception") + .isEqualTo(IllegalStateException.class.getName()) + .jsonPath("trace") + .exists() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); + }); } @Test void neverIncludeStackTrace() { this.contextRunner - .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=never") - .run((context) -> { - WebTestClient client = getWebClient(context); - client.get().uri("/?trace=true").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody().jsonPath("status") - .isEqualTo("500").jsonPath("error") - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("exception") - .isEqualTo(IllegalStateException.class.getName()).jsonPath("trace").doesNotExist() - .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); - }); + .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=never") + .run((context) -> { + WebTestClient client = getWebClient(context); + client.get() + .uri("/?trace=true") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody() + .jsonPath("status") + .isEqualTo("500") + .jsonPath("error") + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) + .jsonPath("exception") + .isEqualTo(IllegalStateException.class.getName()) + .jsonPath("trace") + .doesNotExist() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); + }); } @Test void includeMessageOnParam() { this.contextRunner - .withPropertyValues("server.error.include-exception=true", "server.error.include-message=on-param") - .run((context) -> { - WebTestClient client = getWebClient(context); - client.get().uri("/?message=true").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody().jsonPath("status") - .isEqualTo("500").jsonPath("error") - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("exception") - .isEqualTo(IllegalStateException.class.getName()).jsonPath("message").isNotEmpty() - .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); - }); + .withPropertyValues("server.error.include-exception=true", "server.error.include-message=on-param") + .run((context) -> { + WebTestClient client = getWebClient(context); + client.get() + .uri("/?message=true") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody() + .jsonPath("status") + .isEqualTo("500") + .jsonPath("error") + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) + .jsonPath("exception") + .isEqualTo(IllegalStateException.class.getName()) + .jsonPath("message") + .isNotEmpty() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); + }); } @Test void alwaysIncludeMessage() { this.contextRunner - .withPropertyValues("server.error.include-exception=true", "server.error.include-message=always") - .run((context) -> { - WebTestClient client = getWebClient(context); - client.get().uri("/?trace=false").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody().jsonPath("status") - .isEqualTo("500").jsonPath("error") - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("exception") - .isEqualTo(IllegalStateException.class.getName()).jsonPath("message").isNotEmpty() - .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); - }); + .withPropertyValues("server.error.include-exception=true", "server.error.include-message=always") + .run((context) -> { + WebTestClient client = getWebClient(context); + client.get() + .uri("/?trace=false") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody() + .jsonPath("status") + .isEqualTo("500") + .jsonPath("error") + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) + .jsonPath("exception") + .isEqualTo(IllegalStateException.class.getName()) + .jsonPath("message") + .isNotEmpty() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); + }); } @Test void neverIncludeMessage() { this.contextRunner - .withPropertyValues("server.error.include-exception=true", "server.error.include-message=never") - .run((context) -> { - WebTestClient client = getWebClient(context); - client.get().uri("/?trace=true").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody().jsonPath("status") - .isEqualTo("500").jsonPath("error") - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("exception") - .isEqualTo(IllegalStateException.class.getName()).jsonPath("message").doesNotExist() - .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); - }); + .withPropertyValues("server.error.include-exception=true", "server.error.include-message=never") + .run((context) -> { + WebTestClient client = getWebClient(context); + client.get() + .uri("/?trace=true") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody() + .jsonPath("status") + .isEqualTo("500") + .jsonPath("error") + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) + .jsonPath("exception") + .isEqualTo(IllegalStateException.class.getName()) + .jsonPath("message") + .doesNotExist() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); + }); } @Test void statusException() { this.contextRunner.withPropertyValues("server.error.include-exception=true").run((context) -> { WebTestClient client = getWebClient(context); - client.get().uri("/badRequest").exchange().expectStatus().isBadRequest().expectBody().jsonPath("status") - .isEqualTo("400").jsonPath("error").isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()) - .jsonPath("exception").isEqualTo(ResponseStatusException.class.getName()).jsonPath("requestId") - .isEqualTo(this.logIdFilter.getLogId()); + client.get() + .uri("/badRequest") + .exchange() + .expectStatus() + .isBadRequest() + .expectBody() + .jsonPath("status") + .isEqualTo("400") + .jsonPath("error") + .isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()) + .jsonPath("exception") + .isEqualTo(ResponseStatusException.class.getName()) + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); }); } @Test void defaultErrorView() { this.contextRunner - .withPropertyValues("spring.mustache.prefix=classpath:/unknown/", - "server.error.include-stacktrace=always", "server.error.include-message=always") - .run((context) -> { - WebTestClient client = getWebClient(context); - String body = client.get().uri("/").accept(MediaType.TEXT_HTML).exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader().contentType(TEXT_HTML_UTF8) - .expectBody(String.class).returnResult().getResponseBody(); - assertThat(body).contains("Whitelabel Error Page").contains(this.logIdFilter.getLogId()) - .contains("
Expected!
") - .contains("
java.lang.IllegalStateException"); - }); + .withPropertyValues("spring.mustache.prefix=classpath:/unknown/", "server.error.include-stacktrace=always", + "server.error.include-message=always") + .run((context) -> { + WebTestClient client = getWebClient(context); + String body = client.get() + .uri("/") + .accept(MediaType.TEXT_HTML) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectHeader() + .contentType(TEXT_HTML_UTF8) + .expectBody(String.class) + .returnResult() + .getResponseBody(); + assertThat(body).contains("Whitelabel Error Page") + .contains(this.logIdFilter.getLogId()) + .contains("
Expected!
") + .contains("
java.lang.IllegalStateException"); + }); } @Test void escapeHtmlInDefaultErrorView() { this.contextRunner - .withPropertyValues("spring.mustache.prefix=classpath:/unknown/", "server.error.include-message=always") - .run((context) -> { - WebTestClient client = getWebClient(context); - String body = client.get().uri("/html").accept(MediaType.TEXT_HTML).exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader().contentType(TEXT_HTML_UTF8) - .expectBody(String.class).returnResult().getResponseBody(); - assertThat(body).contains("Whitelabel Error Page").contains(this.logIdFilter.getLogId()) - .doesNotContain("")) .accept(MediaType.TEXT_HTML)) - .andExpect(status().is5xxServerError()).andReturn(); + .andExpect(status().is5xxServerError()) + .andReturn(); String content = response.getResponse().getContentAsString(); assertThat(content).contains("<script>"); assertThat(content).contains("Hello World"); @@ -92,9 +95,11 @@ class DefaultErrorViewIntegrationTests { @Test void testErrorWithSpelEscape() throws Exception { String spel = "${T(" + getClass().getName() + ").injectCall()}"; - MvcResult response = this.mockMvc.perform(get("/error") - .requestAttr("javax.servlet.error.exception", new RuntimeException(spel)).accept(MediaType.TEXT_HTML)) - .andExpect(status().is5xxServerError()).andReturn(); + MvcResult response = this.mockMvc + .perform(get("/error").requestAttr("javax.servlet.error.exception", new RuntimeException(spel)) + .accept(MediaType.TEXT_HTML)) + .andExpect(status().is5xxServerError()) + .andReturn(); String content = response.getResponse().getContentAsString(); assertThat(content).doesNotContain("injection"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java index a22d7707dd..e89b3e6620 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -84,14 +84,14 @@ class DefaultErrorViewResolverTests { @Test void createWhenApplicationContextIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new DefaultErrorViewResolver(null, new Resources())) - .withMessageContaining("ApplicationContext must not be null"); + .withMessageContaining("ApplicationContext must not be null"); } @Test void createWhenResourcePropertiesIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DefaultErrorViewResolver(mock(ApplicationContext.class), (Resources) null)) - .withMessageContaining("Resources must not be null"); + .isThrownBy(() -> new DefaultErrorViewResolver(mock(ApplicationContext.class), (Resources) null)) + .withMessageContaining("Resources must not be null"); } @Test @@ -103,21 +103,25 @@ class DefaultErrorViewResolverTests { @Test void resolveWhenExactTemplateMatchShouldReturnTemplate() { given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), any(Environment.class), - any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + any(ClassLoader.class), any(ResourceLoader.class))) + .willReturn(true); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); assertThat(resolved).isNotNull(); assertThat(resolved.getViewName()).isEqualTo("error/404"); - then(this.templateAvailabilityProvider).should().isTemplateAvailable(eq("error/404"), any(Environment.class), - any(ClassLoader.class), any(ResourceLoader.class)); + then(this.templateAvailabilityProvider).should() + .isTemplateAvailable(eq("error/404"), any(Environment.class), any(ClassLoader.class), + any(ResourceLoader.class)); then(this.templateAvailabilityProvider).shouldHaveNoMoreInteractions(); } @Test void resolveWhenSeries5xxTemplateMatchShouldReturnTemplate() { given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/503"), any(Environment.class), - any(ClassLoader.class), any(ResourceLoader.class))).willReturn(false); + any(ClassLoader.class), any(ResourceLoader.class))) + .willReturn(false); given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/5xx"), any(Environment.class), - any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + any(ClassLoader.class), any(ResourceLoader.class))) + .willReturn(true); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.SERVICE_UNAVAILABLE, this.model); assertThat(resolved.getViewName()).isEqualTo("error/5xx"); @@ -126,9 +130,11 @@ class DefaultErrorViewResolverTests { @Test void resolveWhenSeries4xxTemplateMatchShouldReturnTemplate() { given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), any(Environment.class), - any(ClassLoader.class), any(ResourceLoader.class))).willReturn(false); + any(ClassLoader.class), any(ResourceLoader.class))) + .willReturn(false); given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/4xx"), any(Environment.class), - any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + any(ClassLoader.class), any(ResourceLoader.class))) + .willReturn(true); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); assertThat(resolved.getViewName()).isEqualTo("error/4xx"); } @@ -165,7 +171,8 @@ class DefaultErrorViewResolverTests { void resolveWhenTemplateAndResourceMatchShouldFavorTemplate() { setResourceLocation("/exact"); given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), any(Environment.class), - any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + any(ClassLoader.class), any(ResourceLoader.class))) + .willReturn(true); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); assertThat(resolved.getViewName()).isEqualTo("error/404"); } @@ -174,7 +181,8 @@ class DefaultErrorViewResolverTests { void resolveWhenExactResourceMatchAndSeriesTemplateMatchShouldFavorResource() throws Exception { setResourceLocation("/exact"); given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), any(Environment.class), - any(ClassLoader.class), any(ResourceLoader.class))).willReturn(false); + any(ClassLoader.class), any(ResourceLoader.class))) + .willReturn(false); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); then(this.templateAvailabilityProvider).shouldHaveNoMoreInteractions(); MockHttpServletResponse response = render(resolved); @@ -196,7 +204,7 @@ class DefaultErrorViewResolverTests { private void setResourceLocation(String path) { String packageName = getClass().getPackage().getName(); this.resourcesProperties - .setStaticLocations(new String[] { "classpath:" + packageName.replace('.', '/') + path + "/" }); + .setStaticLocations(new String[] { "classpath:" + packageName.replace('.', '/') + path + "/" }); } private MockHttpServletResponse render(ModelAndView modelAndView) throws Exception { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfigurationTests.java index 455ed87b38..42917bf4ed 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,8 +63,8 @@ class ErrorMvcAutoConfigurationTests { String responseString = ((MockHttpServletResponse) webRequest.getResponse()).getContentAsString(); assertThat(responseString).contains( "

This application has no explicit mapping for /error, so you are seeing this as a fallback.

") - .contains("
Exception message
") - .contains("
java.lang.IllegalStateException"); + .contains("
Exception message
") + .contains("
java.lang.IllegalStateException"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/RemappedErrorViewIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/RemappedErrorViewIntegrationTests.java index b5e25e65c0..f61f6b3c11 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/RemappedErrorViewIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/RemappedErrorViewIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,7 +87,7 @@ class RemappedErrorViewIntegrationTests { // For manual testing static void main(String[] args) { new SpringApplicationBuilder(TestConfiguration.class).properties("spring.mvc.servlet.path:spring/*") - .run(args); + .run(args); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsConditionTests.java index 3359c134e3..1311e4d2e8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsConditionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat; class OnWsdlLocationsConditionTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(TestConfig.class); + .withUserConfiguration(TestConfig.class); @Test void wsdlLocationsNotDefined() { @@ -44,13 +44,13 @@ class OnWsdlLocationsConditionTests { @Test void wsdlLocationsDefinedAsCommaSeparated() { this.contextRunner.withPropertyValues("spring.webservices.wsdl-locations=value1") - .run((context) -> assertThat(context).hasBean("foo")); + .run((context) -> assertThat(context).hasBean("foo")); } @Test void wsdlLocationsDefinedAsList() { this.contextRunner.withPropertyValues("spring.webservices.wsdl-locations[0]=value1") - .run((context) -> assertThat(context).hasBean("foo")); + .run((context) -> assertThat(context).hasBean("foo")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java index 27d64c3afc..1ee571a244 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat; class WebServicesAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(WebServicesAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(WebServicesAutoConfiguration.class)); @Test void defaultConfiguration() { @@ -51,20 +51,21 @@ class WebServicesAutoConfigurationTests { @Test void customPathMustBeginWithASlash() { this.contextRunner.withPropertyValues("spring.webservices.path=invalid") - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("Failed to bind properties under 'spring.webservices'")); + .run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("Failed to bind properties under 'spring.webservices'")); } @Test void customPath() { this.contextRunner.withPropertyValues("spring.webservices.path=/valid") - .run((context) -> assertThat(getUrlMappings(context)).contains("/valid/*")); + .run((context) -> assertThat(getUrlMappings(context)).contains("/valid/*")); } @Test void customPathWithTrailingSlash() { this.contextRunner.withPropertyValues("spring.webservices.path=/valid/") - .run((context) -> assertThat(getUrlMappings(context)).contains("/valid/*")); + .run((context) -> assertThat(getUrlMappings(context)).contains("/valid/*")); } @Test @@ -78,10 +79,11 @@ class WebServicesAutoConfigurationTests { @Test void customInitParameters() { this.contextRunner - .withPropertyValues("spring.webservices.servlet.init.key1=value1", - "spring.webservices.servlet.init.key2=value2") - .run((context) -> assertThat(getServletRegistrationBean(context).getInitParameters()) - .containsEntry("key1", "value1").containsEntry("key2", "value2")); + .withPropertyValues("spring.webservices.servlet.init.key1=value1", + "spring.webservices.servlet.init.key2=value2") + .run((context) -> assertThat(getServletRegistrationBean(context).getInitParameters()) + .containsEntry("key1", "value1") + .containsEntry("key2", "value2")); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java index 6cf838fef0..c1450a1f46 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,21 +33,21 @@ class WebServicesPropertiesTests { void pathMustNotBeEmpty() { this.properties = new WebServicesProperties(); assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath("")) - .withMessageContaining("Path must have length greater than 1"); + .withMessageContaining("Path must have length greater than 1"); } @Test void pathMustHaveLengthGreaterThanOne() { this.properties = new WebServicesProperties(); assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath("/")) - .withMessageContaining("Path must have length greater than 1"); + .withMessageContaining("Path must have length greater than 1"); } @Test void customPathMustBeginWithASlash() { this.properties = new WebServicesProperties(); assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath("custom")) - .withMessageContaining("Path must start with '/'"); + .withMessageContaining("Path must start with '/'"); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfigurationTests.java index 2ecc12810a..f1bd27163c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ import static org.assertj.core.api.Assertions.assertThat; class WebServiceTemplateAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(WebServiceTemplateAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(WebServiceTemplateAutoConfiguration.class)); @Test void autoConfiguredBuilderShouldNotHaveMarshallerAndUnmarshaller() { @@ -70,27 +70,27 @@ class WebServiceTemplateAutoConfigurationTests { @Test void webServiceTemplateWhenHasCustomBuilderShouldUseCustomBuilder() { this.contextRunner.withUserConfiguration(CustomWebServiceTemplateBuilderConfig.class) - .run(assertWebServiceTemplateBuilder((builder) -> { - WebServiceTemplate webServiceTemplate = builder.build(); - assertThat(webServiceTemplate.getMarshaller()) - .isSameAs(CustomWebServiceTemplateBuilderConfig.marshaller); - })); + .run(assertWebServiceTemplateBuilder((builder) -> { + WebServiceTemplate webServiceTemplate = builder.build(); + assertThat(webServiceTemplate.getMarshaller()) + .isSameAs(CustomWebServiceTemplateBuilderConfig.marshaller); + })); } @Test void webServiceTemplateShouldApplyCustomizer() { this.contextRunner.withUserConfiguration(WebServiceTemplateCustomizerConfig.class) - .run(assertWebServiceTemplateBuilder((builder) -> { - WebServiceTemplate webServiceTemplate = builder.build(); - assertThat(webServiceTemplate.getUnmarshaller()) - .isSameAs(WebServiceTemplateCustomizerConfig.unmarshaller); - })); + .run(assertWebServiceTemplateBuilder((builder) -> { + WebServiceTemplate webServiceTemplate = builder.build(); + assertThat(webServiceTemplate.getUnmarshaller()) + .isSameAs(WebServiceTemplateCustomizerConfig.unmarshaller); + })); } @Test void builderShouldBeFreshForEachUse() { this.contextRunner.withUserConfiguration(DirtyWebServiceTemplateConfig.class) - .run((context) -> assertThat(context).hasNotFailed()); + .run((context) -> assertThat(context).hasNotFailed()); } private ContextConsumer assertWebServiceTemplateBuilder( diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfigurationTests.java index f4899b4573..b1e02884d1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,7 +69,7 @@ class WebSocketServletAutoConfigurationTests { this.context.register(configuration); this.context.refresh(); Object serverContainer = this.context.getServletContext() - .getAttribute("javax.websocket.server.ServerContainer"); + .getAttribute("javax.websocket.server.ServerContainer"); assertThat(serverContainer).isInstanceOf(ServerContainer.class); } diff --git a/spring-boot-project/spring-boot-cli/src/intTest/java/org/springframework/boot/cli/JarCommandIT.java b/spring-boot-project/spring-boot-cli/src/intTest/java/org/springframework/boot/cli/JarCommandIT.java index 5bb7857ead..d49819697d 100644 --- a/spring-boot-project/spring-boot-cli/src/intTest/java/org/springframework/boot/cli/JarCommandIT.java +++ b/spring-boot-project/spring-boot-cli/src/intTest/java/org/springframework/boot/cli/JarCommandIT.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,7 +55,7 @@ class JarCommandIT { invocation.await(); assertThat(invocation.getStandardOutput()).isEqualTo(""); assertThat(invocation.getErrorOutput()) - .contains("The name of the resulting jar and at least one source file must be specified"); + .contains("The name of the resulting jar and at least one source file must be specified"); } @Test @@ -64,7 +64,7 @@ class JarCommandIT { invocation.await(); assertThat(invocation.getStandardOutput()).isEqualTo(""); assertThat(invocation.getErrorOutput()) - .contains("The name of the resulting jar and at least one source file must be specified"); + .contains("The name of the resulting jar and at least one source file must be specified"); } @Test @@ -109,9 +109,12 @@ class JarCommandIT { assertThat(invocation.getErrorOutput()).isEqualTo(""); } assertThat(invocation.getStandardOutput()).contains("Hello World!") - .contains("/BOOT-INF/classes!/public/public.txt").contains("/BOOT-INF/classes!/resources/resource.txt") - .contains("/BOOT-INF/classes!/static/static.txt").contains("/BOOT-INF/classes!/templates/template.txt") - .contains("/BOOT-INF/classes!/root.properties").contains("Goodbye Mama"); + .contains("/BOOT-INF/classes!/public/public.txt") + .contains("/BOOT-INF/classes!/resources/resource.txt") + .contains("/BOOT-INF/classes!/static/static.txt") + .contains("/BOOT-INF/classes!/templates/template.txt") + .contains("/BOOT-INF/classes!/root.properties") + .contains("Goodbye Mama"); } @Test @@ -132,9 +135,12 @@ class JarCommandIT { if (!JAVA_9_OR_LATER) { assertThat(invocation.getErrorOutput()).isEqualTo(""); } - assertThat(invocation.getStandardOutput()).contains("Hello World!").doesNotContain("/public/public.txt") - .doesNotContain("/resources/resource.txt").contains("/static/static.txt") - .contains("/templates/template.txt").contains("Goodbye Mama"); + assertThat(invocation.getStandardOutput()).contains("Hello World!") + .doesNotContain("/public/public.txt") + .doesNotContain("/resources/resource.txt") + .contains("/static/static.txt") + .contains("/templates/template.txt") + .contains("Goodbye Mama"); } private static boolean isClassPresent(String name) { diff --git a/spring-boot-project/spring-boot-cli/src/intTest/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java b/spring-boot-project/spring-boot-cli/src/intTest/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java index 9d34675e27..ef687cb490 100644 --- a/spring-boot-project/spring-boot-cli/src/intTest/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java +++ b/spring-boot-project/spring-boot-cli/src/intTest/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java @@ -133,9 +133,9 @@ public final class CommandLineInvoker { public Invocation(Process process) { this.process = process; this.streamReaders - .add(new Thread(new StreamReadingRunnable(this.process.getErrorStream(), this.err, this.combined))); + .add(new Thread(new StreamReadingRunnable(this.process.getErrorStream(), this.err, this.combined))); this.streamReaders - .add(new Thread(new StreamReadingRunnable(this.process.getInputStream(), this.out, this.combined))); + .add(new Thread(new StreamReadingRunnable(this.process.getInputStream(), this.out, this.combined))); for (Thread streamReader : this.streamReaders) { streamReader.start(); } 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..641ff85953 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,7 +40,7 @@ import org.springframework.util.StringUtils; public class CommandRunner implements Iterable { private static final Set NO_EXCEPTION_OPTIONS = EnumSet - .noneOf(CommandException.Option.class); + .noneOf(CommandException.Option.class); private final String name; 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..100296609d 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -110,10 +110,14 @@ abstract class ArchiveCommand extends OptionParsingCommand { protected void doOptions() { this.includeOption = option("include", "Pattern applied to directories on the classpath to find files to include in the resulting ") - .withRequiredArg().withValuesSeparatedBy(",").defaultsTo(""); + .withRequiredArg() + .withValuesSeparatedBy(",") + .defaultsTo(""); this.excludeOption = option("exclude", "Pattern applied to directories on the classpath to find files to " - + "exclude from the resulting " + this.type).withRequiredArg().withValuesSeparatedBy(",") - .defaultsTo(""); + + "exclude from the resulting " + this.type) + .withRequiredArg() + .withValuesSeparatedBy(",") + .defaultsTo(""); } @Override @@ -150,7 +154,7 @@ abstract class ArchiveCommand extends OptionParsingCommand { private GroovyCompiler createCompiler(OptionSet options) { List repositoryConfiguration = RepositoryConfigurationFactory - .createDefaultRepositoryConfiguration(); + .createDefaultRepositoryConfiguration(); GroovyCompilerConfiguration configuration = new OptionSetGroovyCompilerConfiguration(options, this, repositoryConfiguration); GroovyCompiler groovyCompiler = new GroovyCompiler(configuration); @@ -206,8 +210,8 @@ abstract class ArchiveCommand extends OptionParsingCommand { private void addManifest(JarWriter writer, Class[] compiledClasses) throws IOException { Manifest manifest = new Manifest(); manifest.getMainAttributes().putValue("Manifest-Version", "1.0"); - manifest.getMainAttributes().putValue(PackagedSpringApplicationLauncher.SOURCE_ENTRY, - commaDelimitedClassNames(compiledClasses)); + manifest.getMainAttributes() + .putValue(PackagedSpringApplicationLauncher.SOURCE_ENTRY, commaDelimitedClassNames(compiledClasses)); writer.writeManifest(manifest); } @@ -226,7 +230,7 @@ abstract class ArchiveCommand extends OptionParsingCommand { addClass(writer, PackagedSpringApplicationLauncher.class); addClass(writer, SpringApplicationLauncher.class); Resource[] resources = new PathMatchingResourcePatternResolver() - .getResources("org/springframework/boot/groovy/**"); + .getResources("org/springframework/boot/groovy/**"); for (Resource resource : resources) { String url = resource.getURL().toString(); addResource(writer, resource, url.substring(url.indexOf("org/springframework/boot/groovy/"))); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommand.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommand.java index 6217133d26..fe0d94372f 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommand.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,8 +70,8 @@ public class EncodePasswordCommand extends OptionParsingCommand { @Override public Collection getExamples() { List examples = new ArrayList<>(); - examples.add( - new HelpExample("To encode a password with the default encoder", "spring encodepassword mypassword")); + examples + .add(new HelpExample("To encode a password with the default encoder", "spring encodepassword mypassword")); examples.add(new HelpExample("To encode a password with pbkdf2", "spring encodepassword -a pbkdf2 mypassword")); return examples; } @@ -83,7 +83,7 @@ public class EncodePasswordCommand extends OptionParsingCommand { @Override protected void options() { this.algorithm = option(Arrays.asList("algorithm", "a"), "The algorithm to use").withRequiredArg() - .defaultsTo("default"); + .defaultsTo("default"); } @Override diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/grab/GrabCommand.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/grab/GrabCommand.java index bcd38abfee..96e047b984 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/grab/GrabCommand.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/grab/GrabCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,7 @@ public class GrabCommand extends OptionParsingCommand { protected ExitStatus run(OptionSet options) throws Exception { SourceOptions sourceOptions = new SourceOptions(options); List repositoryConfiguration = RepositoryConfigurationFactory - .createDefaultRepositoryConfiguration(); + .createDefaultRepositoryConfiguration(); GroovyCompilerConfiguration configuration = new OptionSetGroovyCompilerConfiguration(options, this, repositoryConfiguration); if (System.getProperty("grape.root") == null) { diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitCommand.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitCommand.java index 5403dc745c..87796f9342 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitCommand.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -139,7 +139,7 @@ public class InitCommand extends OptionParsingCommand { @Override protected void options() { this.target = option(Arrays.asList("target"), "URL of the service to use").withRequiredArg() - .defaultsTo(ProjectGenerationRequest.DEFAULT_SERVICE_URL); + .defaultsTo(ProjectGenerationRequest.DEFAULT_SERVICE_URL); this.listCapabilities = option(Arrays.asList("list"), "List the capabilities of the service. Use it to discover the " + "dependencies and the types that are available"); @@ -149,33 +149,37 @@ public class InitCommand extends OptionParsingCommand { private void projectGenerationOptions() { this.groupId = option(Arrays.asList("group-id", "g"), "Project coordinates (for example 'org.test')") - .withRequiredArg(); + .withRequiredArg(); this.artifactId = option(Arrays.asList("artifact-id", "a"), - "Project coordinates; infer archive name (for example 'test')").withRequiredArg(); + "Project coordinates; infer archive name (for example 'test')") + .withRequiredArg(); this.version = option(Arrays.asList("version", "v"), "Project version (for example '0.0.1-SNAPSHOT')") - .withRequiredArg(); + .withRequiredArg(); this.name = option(Arrays.asList("name", "n"), "Project name; infer application name").withRequiredArg(); this.description = option("description", "Project description").withRequiredArg(); this.packageName = option(Arrays.asList("package-name"), "Package name").withRequiredArg(); this.type = option(Arrays.asList("type", "t"), "Project type. Not normally needed if you use --build " + "and/or --format. Check the capabilities of the service (--list) for more details") - .withRequiredArg(); + .withRequiredArg(); this.packaging = option(Arrays.asList("packaging", "p"), "Project packaging (for example 'jar')") - .withRequiredArg(); + .withRequiredArg(); this.build = option("build", "Build system to use (for example 'maven' or 'gradle')").withRequiredArg() - .defaultsTo("maven"); + .defaultsTo("maven"); this.format = option("format", "Format of the generated content (for example 'build' for a build file, " - + "'project' for a project archive)").withRequiredArg().defaultsTo("project"); + + "'project' for a project archive)") + .withRequiredArg() + .defaultsTo("project"); this.javaVersion = option(Arrays.asList("java-version", "j"), "Language level (for example '1.8')") - .withRequiredArg(); + .withRequiredArg(); this.language = option(Arrays.asList("language", "l"), "Programming language (for example 'java')") - .withRequiredArg(); + .withRequiredArg(); this.bootVersion = option(Arrays.asList("boot-version", "b"), - "Spring Boot version (for example '1.2.0.RELEASE')").withRequiredArg(); + "Spring Boot version (for example '1.2.0.RELEASE')") + .withRequiredArg(); this.dependencies = option(Arrays.asList("dependencies", "d"), "Comma-separated list of dependency identifiers to include in the generated project") - .withRequiredArg(); + .withRequiredArg(); } private void otherOptions() { diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/Installer.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/Installer.java index cf96a510a4..89a0aed15f 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/Installer.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/Installer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +57,7 @@ class Installer { private static GroovyCompilerConfiguration createCompilerConfiguration(OptionSet options, CompilerOptionHandler compilerOptionHandler) { List repositoryConfiguration = RepositoryConfigurationFactory - .createDefaultRepositoryConfiguration(); + .createDefaultRepositoryConfiguration(); return new OptionSetGroovyCompilerConfiguration(options, compilerOptionHandler, repositoryConfiguration) { @Override public boolean isAutoconfigure() { diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/CompilerOptionHandler.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/CompilerOptionHandler.java index 35102545ef..d7e6db4572 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/CompilerOptionHandler.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/CompilerOptionHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,9 +43,11 @@ public class CompilerOptionHandler extends OptionHandler { this.noGuessImportsOption = option("no-guess-imports", "Do not attempt to guess imports"); this.noGuessDependenciesOption = option("no-guess-dependencies", "Do not attempt to guess dependencies"); this.autoconfigureOption = option("autoconfigure", "Add autoconfigure compiler transformations") - .withOptionalArg().ofType(Boolean.class).defaultsTo(true); + .withOptionalArg() + .ofType(Boolean.class) + .defaultsTo(true); this.classpathOption = option(Arrays.asList("classpath", "cp"), "Additional classpath entries") - .withRequiredArg(); + .withRequiredArg(); doOptions(); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java index 1cc5541232..4f018fa789 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -152,7 +152,7 @@ public class OptionHandler { @Override public String format(Map options) { Comparator comparator = Comparator - .comparing((optionDescriptor) -> optionDescriptor.options().iterator().next()); + .comparing((optionDescriptor) -> optionDescriptor.options().iterator().next()); Set sorted = new TreeSet<>(comparator); sorted.addAll(options.values()); for (OptionDescriptor descriptor : sorted) { diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/RunCommand.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/RunCommand.java index 6fb408657d..e1a407ca6a 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/RunCommand.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/RunCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -99,7 +99,7 @@ public class RunCommand extends OptionParsingCommand { SourceOptions sourceOptions = new SourceOptions(options); List repositoryConfiguration = RepositoryConfigurationFactory - .createDefaultRepositoryConfiguration(); + .createDefaultRepositoryConfiguration(); repositoryConfiguration.add(0, new RepositoryConfiguration("local", new File("repository").toURI(), true)); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunner.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunner.java index bc9d31b98e..ecc07ffa8b 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunner.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/run/SpringApplicationRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -165,7 +165,7 @@ public class SpringApplicationRunner { synchronized (this.monitor) { try { this.applicationContext = new SpringApplicationLauncher(getContextClassLoader()) - .launch(this.compiledSources, SpringApplicationRunner.this.args); + .launch(this.compiledSources, SpringApplicationRunner.this.args); } catch (Exception ex) { ex.printStackTrace(); 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..b8779af6aa 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -114,7 +114,7 @@ public class Shell { this.consoleReader.setBellEnabled(false); this.consoleReader.setExpandEvents(false); this.consoleReader - .addCompleter(new CommandCompleter(this.consoleReader, this.argumentDelimiter, this.commandRunner)); + .addCompleter(new CommandCompleter(this.consoleReader, this.argumentDelimiter, this.commandRunner)); this.consoleReader.setCompletionHandler(new CandidateListCompletionHandler()); } 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..d5abd82e72 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,9 +67,9 @@ public abstract class AnnotatedNodeASTTransformation implements ASTTransformatio visitAnnotatedNode(importNode, annotationNodes); } module.getStaticImports() - .forEach((name, importNode) -> visitAnnotatedNode(importNode, annotationNodes)); + .forEach((name, importNode) -> visitAnnotatedNode(importNode, annotationNodes)); module.getStaticStarImports() - .forEach((name, importNode) -> visitAnnotatedNode(importNode, annotationNodes)); + .forEach((name, importNode) -> visitAnnotatedNode(importNode, annotationNodes)); for (ClassNode classNode : module.getClasses()) { visitAnnotatedNode(classNode, annotationNodes); classNode.visitContents(classVisitor); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyCustomizer.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyCustomizer.java index 2b2068c54c..3a0c277880 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyCustomizer.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -217,7 +217,7 @@ public class DependencyCustomizer { public DependencyCustomizer add(String module, String classifier, String type, boolean transitive) { if (canAdd()) { ArtifactCoordinatesResolver artifactCoordinatesResolver = this.dependencyResolutionContext - .getArtifactCoordinatesResolver(); + .getArtifactCoordinatesResolver(); this.classNode.addAnnotation(createGrabAnnotation(artifactCoordinatesResolver.getGroupId(module), artifactCoordinatesResolver.getArtifactId(module), artifactCoordinatesResolver.getVersion(module), classifier, type, transitive)); 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..3f66bdcb8a 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,8 +71,8 @@ public class DependencyManagementBomTransformation extends AnnotatedNodeASTTrans public static final int ORDER = Ordered.HIGHEST_PRECEDENCE + 100; private static final Set DEPENDENCY_MANAGEMENT_BOM_ANNOTATION_NAMES = Collections - .unmodifiableSet(new HashSet<>(Arrays.asList(DependencyManagementBom.class.getName(), - DependencyManagementBom.class.getSimpleName()))); + .unmodifiableSet(new HashSet<>( + Arrays.asList(DependencyManagementBom.class.getName(), DependencyManagementBom.class.getSimpleName()))); private final DependencyResolutionContext resolutionContext; 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..9a9b30ad17 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -249,8 +249,10 @@ public class GroovyCompiler { private int getIndexOfASTTransformationVisitor(List conversionOperations) { for (int index = 0; index < conversionOperations.size(); index++) { - if (conversionOperations.get(index).getClass().getName() - .startsWith(ASTTransformationVisitor.class.getName())) { + if (conversionOperations.get(index) + .getClass() + .getName() + .startsWith(ASTTransformationVisitor.class.getName())) { return index; } } 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..d7b94ef3ae 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ public class ResolveDependencyCoordinatesTransformation extends AnnotatedNodeAST public static final int ORDER = DependencyManagementBomTransformation.ORDER + 300; private static final Set GRAB_ANNOTATION_NAMES = Collections - .unmodifiableSet(new HashSet<>(Arrays.asList(Grab.class.getName(), Grab.class.getSimpleName()))); + .unmodifiableSet(new HashSet<>(Arrays.asList(Grab.class.getName(), Grab.class.getSimpleName()))); private final DependencyResolutionContext resolutionContext; diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringIntegrationCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringIntegrationCompilerAutoConfiguration.java index ac7a8864c4..664df59d5a 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringIntegrationCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringIntegrationCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ public class SpringIntegrationCompilerAutoConfiguration extends CompilerAutoConf @Override public void applyDependencies(DependencyCustomizer dependencies) { dependencies.ifAnyMissingClasses("org.springframework.integration.config.EnableIntegration") - .add("spring-boot-starter-integration"); + .add("spring-boot-starter-integration"); } @Override diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringMvcCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringMvcCompilerAutoConfiguration.java index 0d5dd70f66..9fe5774948 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringMvcCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringMvcCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ public class SpringMvcCompilerAutoConfiguration extends CompilerAutoConfiguratio @Override public void applyDependencies(DependencyCustomizer dependencies) { dependencies.ifAnyMissingClasses("org.springframework.web.servlet.mvc.Controller") - .add("spring-boot-starter-web"); + .add("spring-boot-starter-web"); dependencies.ifAnyMissingClasses("groovy.text.TemplateEngine").add("groovy-templates"); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringRetryCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringRetryCompilerAutoConfiguration.java index 6148bd0991..caf763f946 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringRetryCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringRetryCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,8 @@ public class SpringRetryCompilerAutoConfiguration extends CompilerAutoConfigurat @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies.ifAnyMissingClasses("org.springframework.retry.annotation.EnableRetry").add("spring-retry", - "spring-boot-starter-aop"); + dependencies.ifAnyMissingClasses("org.springframework.retry.annotation.EnableRetry") + .add("spring-retry", "spring-boot-starter-aop"); } @Override diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSecurityCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSecurityCompilerAutoConfiguration.java index bc42f54cde..ddd3343975 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSecurityCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringSecurityCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,20 +38,21 @@ public class SpringSecurityCompilerAutoConfiguration extends CompilerAutoConfigu @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies.ifAnyMissingClasses( - "org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity") - .add("spring-boot-starter-security"); + dependencies + .ifAnyMissingClasses( + "org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity") + .add("spring-boot-starter-security"); } @Override public void applyImports(ImportCustomizer imports) { - imports.addImports("org.springframework.security.core.Authentication", - "org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity", - "org.springframework.security.core.authority.AuthorityUtils") - .addStarImports("org.springframework.security.config.annotation.web.configuration", - "org.springframework.security.authentication", - "org.springframework.security.config.annotation.web", - "org.springframework.security.config.annotation.web.builders"); + imports + .addImports("org.springframework.security.core.Authentication", + "org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity", + "org.springframework.security.core.authority.AuthorityUtils") + .addStarImports("org.springframework.security.config.annotation.web.configuration", + "org.springframework.security.authentication", "org.springframework.security.config.annotation.web", + "org.springframework.security.config.annotation.web.builders"); } } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringTestCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringTestCompilerAutoConfiguration.java index 891721bbac..8ddc1d7c88 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringTestCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringTestCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,12 +62,13 @@ public class SpringTestCompilerAutoConfiguration extends CompilerAutoConfigurati @Override public void applyImports(ImportCustomizer imports) throws CompilationFailedException { - imports.addStarImports("org.junit.runner", "org.springframework.boot.test", - "org.springframework.boot.test.context", "org.springframework.boot.test.web.client", - "org.springframework.http", "org.springframework.test.context.junit4", - "org.springframework.test.annotation") - .addImports("org.springframework.boot.test.context.SpringBootTest.WebEnvironment", - "org.springframework.boot.test.web.client.TestRestTemplate"); + imports + .addStarImports("org.junit.runner", "org.springframework.boot.test", + "org.springframework.boot.test.context", "org.springframework.boot.test.web.client", + "org.springframework.http", "org.springframework.test.context.junit4", + "org.springframework.test.annotation") + .addImports("org.springframework.boot.test.context.SpringBootTest.WebEnvironment", + "org.springframework.boot.test.web.client.TestRestTemplate"); } } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringWebsocketCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringWebsocketCompilerAutoConfiguration.java index 530aa0acc3..7faf30915e 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringWebsocketCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/SpringWebsocketCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,16 +39,18 @@ public class SpringWebsocketCompilerAutoConfiguration extends CompilerAutoConfig @Override public void applyDependencies(DependencyCustomizer dependencies) { dependencies.ifAnyMissingClasses("org.springframework.web.socket.config.annotation.EnableWebSocket") - .add("spring-boot-starter-websocket").add("spring-messaging"); + .add("spring-boot-starter-websocket") + .add("spring-messaging"); } @Override public void applyImports(ImportCustomizer imports) { - imports.addStarImports("org.springframework.messaging.handler.annotation", - "org.springframework.messaging.simp.config", "org.springframework.web.socket.handler", - "org.springframework.web.socket.sockjs.transport.handler", - "org.springframework.web.socket.config.annotation") - .addImports("org.springframework.web.socket.WebSocketHandler"); + imports + .addStarImports("org.springframework.messaging.handler.annotation", + "org.springframework.messaging.simp.config", "org.springframework.web.socket.handler", + "org.springframework.web.socket.sockjs.transport.handler", + "org.springframework.web.socket.config.annotation") + .addImports("org.springframework.web.socket.WebSocketHandler"); } } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/TransactionManagementCompilerAutoConfiguration.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/TransactionManagementCompilerAutoConfiguration.java index b75203fa18..6ce204da62 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/TransactionManagementCompilerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/autoconfigure/TransactionManagementCompilerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,8 @@ public class TransactionManagementCompilerAutoConfiguration extends CompilerAuto @Override public void applyDependencies(DependencyCustomizer dependencies) { - dependencies.ifAnyMissingClasses("org.springframework.transaction.annotation.Transactional").add("spring-tx", - "spring-boot-starter-aop"); + dependencies.ifAnyMissingClasses("org.springframework.transaction.annotation.Transactional") + .add("spring-tx", "spring-boot-starter-aop"); } @Override diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagement.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagement.java index 436a3f7e3b..895ea5e92d 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagement.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagement.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ public class SpringBootDependenciesDependencyManagement extends MavenModelDepend try { return modelProcessor.read(SpringBootDependenciesDependencyManagement.class - .getResourceAsStream("spring-boot-dependencies-effective-bom.xml"), null); + .getResourceAsStream("spring-boot-dependencies-effective-bom.xml"), null); } catch (IOException ex) { throw new IllegalStateException("Failed to build model from effective pom", ex); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineFactory.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineFactory.java index 1f695ae4af..c73112c862 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineFactory.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ public abstract class AetherGrapeEngineFactory { RepositorySystem repositorySystem = createServiceLocator().getService(RepositorySystem.class); DefaultRepositorySystemSession repositorySystemSession = MavenRepositorySystemUtils.newSession(); ServiceLoader autoConfigurations = ServiceLoader - .load(RepositorySystemSessionAutoConfiguration.class); + .load(RepositorySystemSessionAutoConfiguration.class); for (RepositorySystemSessionAutoConfiguration autoConfiguration : autoConfigurations) { autoConfiguration.apply(repositorySystemSession, repositorySystem); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContext.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContext.java index d0f0a8e08e..4da7d2f03d 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContext.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,10 +85,10 @@ public class DependencyResolutionContext { public void addDependencyManagement(DependencyManagement dependencyManagement) { for (org.springframework.boot.cli.compiler.dependencies.Dependency dependency : dependencyManagement - .getDependencies()) { + .getDependencies()) { List aetherExclusions = new ArrayList<>(); for (org.springframework.boot.cli.compiler.dependencies.Dependency.Exclusion exclusion : dependency - .getExclusions()) { + .getExclusions()) { aetherExclusions.add(new Exclusion(exclusion.getGroupId(), exclusion.getArtifactId(), "*", "*")); } Dependency aetherDependency = new Dependency(new DefaultArtifact(dependency.getGroupId(), diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/MavenResolverGrapeEngineFactory.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/MavenResolverGrapeEngineFactory.java index 9e2adf63b1..95535af00b 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/MavenResolverGrapeEngineFactory.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/MavenResolverGrapeEngineFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,7 @@ public abstract class MavenResolverGrapeEngineFactory { RepositorySystem repositorySystem = createServiceLocator().getService(RepositorySystem.class); DefaultRepositorySystemSession repositorySystemSession = MavenRepositorySystemUtils.newSession(); ServiceLoader autoConfigurations = ServiceLoader - .load(RepositorySystemSessionAutoConfiguration.class); + .load(RepositorySystemSessionAutoConfiguration.class); for (RepositorySystemSessionAutoConfiguration autoConfiguration : autoConfigurations) { autoConfiguration.apply(repositorySystemSession, repositorySystem); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettings.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettings.java index 58b80c4d6e..9286acc83b 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettings.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/maven/MavenSettings.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -114,7 +114,8 @@ public class MavenSettings { DefaultProxySelector selector = new DefaultProxySelector(); for (Proxy proxy : decryptedSettings.getProxies()) { Authentication authentication = new AuthenticationBuilder().addUsername(proxy.getUsername()) - .addPassword(proxy.getPassword()).build(); + .addPassword(proxy.getPassword()) + .build(); selector.add(new org.eclipse.aether.repository.Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), authentication), proxy.getNonProxyHosts()); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/util/ResourceUtils.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/util/ResourceUtils.java index 51a27cff57..1075ac5a6e 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/util/ResourceUtils.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/util/ResourceUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -98,7 +98,7 @@ public abstract class ResourceUtils { private static List getUrlsFromPrefixedWildcardPath(String path, ClassLoader classLoader) throws IOException { Resource[] resources = new PathMatchingResourcePatternResolver(new FileSearchResourceLoader(classLoader)) - .getResources(path); + .getResources(path); List result = new ArrayList<>(); for (Resource resource : resources) { if (resource.exists()) { diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java index 6c8874e0d5..627a296a92 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,8 +68,8 @@ class GrabCommandIntegrationTests { @Test void duplicateDependencyManagementBomAnnotationsProducesAnError() { assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> this.cli.grab("duplicateDependencyManagementBom.groovy")) - .withMessageContaining("Duplicate @DependencyManagementBom annotation"); + .isThrownBy(() -> this.cli.grab("duplicateDependencyManagementBom.groovy")) + .withMessageContaining("Duplicate @DependencyManagementBom annotation"); } @Test diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ReproIntegrationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ReproIntegrationTests.java index 36b10c7e64..f9c735dc0d 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ReproIntegrationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ReproIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,8 +66,8 @@ class ReproIntegrationTests { @Test void jarFileExtensionNeeded() { assertThatExceptionOfType(ExecutionException.class) - .isThrownBy(() -> this.cli.jar("secure.groovy", "data-jpa.groovy")) - .withMessageContaining("is not a JAR file"); + .isThrownBy(() -> this.cli.jar("secure.groovy", "data-jpa.groovy")) + .withMessageContaining("is not a JAR file"); } } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java index 2df55b6a7e..53c439fa34 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,8 +76,8 @@ class SpringApplicationLauncherTests { assertThat(args == TestSpringApplication.args).isTrue(); Map defaultProperties = TestSpringApplication.defaultProperties; - assertThat(defaultProperties).hasSize(1).containsEntry("spring.groovy.template.check-template-location", - "false"); + assertThat(defaultProperties).hasSize(1) + .containsEntry("spring.groovy.template.check-template-location", "false"); } private Set launch() { diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java index 462cd0c2cf..4f628d8423 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -160,7 +160,7 @@ class CommandRunnerTests { @Test void exceptionMessages() { assertThat(new NoSuchCommandException("name").getMessage()) - .isEqualTo("'name' is not a valid command. See 'help'."); + .isEqualTo("'name' is not a valid command. See 'help'."); } @Test @@ -172,13 +172,13 @@ class CommandRunnerTests { @Test void helpNoCommand() { assertThatExceptionOfType(NoHelpCommandArgumentsException.class) - .isThrownBy(() -> this.commandRunner.run("help")); + .isThrownBy(() -> this.commandRunner.run("help")); } @Test void helpUnknownCommand() { assertThatExceptionOfType(NoSuchCommandException.class) - .isThrownBy(() -> this.commandRunner.run("help", "missing")); + .isThrownBy(() -> this.commandRunner.run("help", "missing")); } private enum Call { diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java index 3b53eb236a..4838dcd5a3 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -104,7 +104,7 @@ class ResourceMatcherTests { void jarFileAlwaysMatches() throws Exception { ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"), Arrays.asList("**/*.jar")); List found = resourceMatcher - .find(Arrays.asList(new File("src/test/resources/templates"), new File("src/test/resources/foo.jar"))); + .find(Arrays.asList(new File("src/test/resources/templates"), new File("src/test/resources/foo.jar"))); assertThat(found).areAtLeastOne(new Condition() { @Override @@ -120,9 +120,9 @@ class ResourceMatcherTests { ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("alpha/**", "bravo/*", "*"), Arrays.asList(".*", "alpha/**/excluded")); List matchedResources = resourceMatcher - .find(Arrays.asList(new File("src/test/resources/resource-matcher/one"), - new File("src/test/resources/resource-matcher/two"), - new File("src/test/resources/resource-matcher/three"))); + .find(Arrays.asList(new File("src/test/resources/resource-matcher/one"), + new File("src/test/resources/resource-matcher/two"), + new File("src/test/resources/resource-matcher/three"))); List paths = new ArrayList<>(); for (MatchedResource resource : matchedResources) { paths.add(resource.getName()); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommandTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommandTests.java index 2980ae3b08..1dec74abf3 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommandTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommandTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,7 +63,7 @@ class EncodePasswordCommandTests { then(this.log).should().info(this.message.capture()); assertThat(this.message.getValue()).startsWith("{bcrypt}"); assertThat(PasswordEncoderFactories.createDelegatingPasswordEncoder().matches("boot", this.message.getValue())) - .isTrue(); + .isTrue(); assertThat(status).isEqualTo(ExitStatus.OK); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java index 4006c15602..496e710e14 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,7 +77,7 @@ class InitializrServiceTests extends AbstractHttpClientMockTests { ProjectGenerationRequest request = new ProjectGenerationRequest(); request.getDependencies().add("foo:bar"); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) - .withMessageContaining(jsonMessage); + .withMessageContaining(jsonMessage); } @Test @@ -85,7 +85,7 @@ class InitializrServiceTests extends AbstractHttpClientMockTests { mockProjectGenerationError(400, null); ProjectGenerationRequest request = new ProjectGenerationRequest(); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) - .withMessageContaining("unexpected 400 error"); + .withMessageContaining("unexpected 400 error"); } @Test @@ -96,7 +96,7 @@ class InitializrServiceTests extends AbstractHttpClientMockTests { given(this.http.execute(isA(HttpGet.class))).willReturn(response); ProjectGenerationRequest request = new ProjectGenerationRequest(); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) - .withMessageContaining("No content received from server"); + .withMessageContaining("No content received from server"); } @Test @@ -105,7 +105,7 @@ class InitializrServiceTests extends AbstractHttpClientMockTests { mockMetadataGetError(500, jsonMessage); ProjectGenerationRequest request = new ProjectGenerationRequest(); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) - .withMessageContaining(jsonMessage); + .withMessageContaining(jsonMessage); } @Test @@ -116,7 +116,7 @@ class InitializrServiceTests extends AbstractHttpClientMockTests { given(this.http.execute(isA(HttpGet.class))).willReturn(response); ProjectGenerationRequest request = new ProjectGenerationRequest(); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) - .withMessageContaining("Invalid content received from server"); + .withMessageContaining("Invalid content received from server"); } @Test @@ -126,7 +126,7 @@ class InitializrServiceTests extends AbstractHttpClientMockTests { given(this.http.execute(isA(HttpGet.class))).willReturn(response); ProjectGenerationRequest request = new ProjectGenerationRequest(); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) - .withMessageContaining("No content received from server"); + .withMessageContaining("No content received from server"); } private ProjectGenerationResponse generateProject(ProjectGenerationRequest request, diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java index 55d5bcb554..151b40c248 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,21 +57,21 @@ class ProjectGenerationRequestTests { this.request.setServiceUrl(customServerUrl); this.request.getDependencies().add("security"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(new URI(customServerUrl + "/starter.zip?dependencies=security&type=test-type")); + .isEqualTo(new URI(customServerUrl + "/starter.zip?dependencies=security&type=test-type")); } @Test void customBootVersion() { this.request.setBootVersion("1.2.0.RELEASE"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?type=test-type&bootVersion=1.2.0.RELEASE")); + .isEqualTo(createDefaultUrl("?type=test-type&bootVersion=1.2.0.RELEASE")); } @Test void singleDependency() { this.request.getDependencies().add("web"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?dependencies=web&type=test-type")); + .isEqualTo(createDefaultUrl("?dependencies=web&type=test-type")); } @Test @@ -79,21 +79,21 @@ class ProjectGenerationRequestTests { this.request.getDependencies().add("web"); this.request.getDependencies().add("data-jpa"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?dependencies=web%2Cdata-jpa&type=test-type")); + .isEqualTo(createDefaultUrl("?dependencies=web%2Cdata-jpa&type=test-type")); } @Test void customJavaVersion() { this.request.setJavaVersion("1.8"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?type=test-type&javaVersion=1.8")); + .isEqualTo(createDefaultUrl("?type=test-type&javaVersion=1.8")); } @Test void customPackageName() { this.request.setPackageName("demo.foo"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?packageName=demo.foo&type=test-type")); + .isEqualTo(createDefaultUrl("?packageName=demo.foo&type=test-type")); } @Test @@ -110,14 +110,14 @@ class ProjectGenerationRequestTests { void customPackaging() { this.request.setPackaging("war"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?type=test-type&packaging=war")); + .isEqualTo(createDefaultUrl("?type=test-type&packaging=war")); } @Test void customLanguage() { this.request.setLanguage("groovy"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?type=test-type&language=groovy")); + .isEqualTo(createDefaultUrl("?type=test-type&language=groovy")); } @Test @@ -127,29 +127,29 @@ class ProjectGenerationRequestTests { this.request.setVersion("1.0.1-SNAPSHOT"); this.request.setDescription("Spring Boot Test"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?groupId=org.acme&artifactId=sample&version=1.0.1-SNAPSHOT" - + "&description=Spring+Boot+Test&type=test-type")); + .isEqualTo(createDefaultUrl("?groupId=org.acme&artifactId=sample&version=1.0.1-SNAPSHOT" + + "&description=Spring+Boot+Test&type=test-type")); } @Test void outputCustomizeArtifactId() { this.request.setOutput("my-project"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?artifactId=my-project&type=test-type")); + .isEqualTo(createDefaultUrl("?artifactId=my-project&type=test-type")); } @Test void outputArchiveCustomizeArtifactId() { this.request.setOutput("my-project.zip"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?artifactId=my-project&type=test-type")); + .isEqualTo(createDefaultUrl("?artifactId=my-project&type=test-type")); } @Test void outputArchiveWithDotsCustomizeArtifactId() { this.request.setOutput("my.nice.project.zip"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?artifactId=my.nice.project&type=test-type")); + .isEqualTo(createDefaultUrl("?artifactId=my.nice.project&type=test-type")); } @Test @@ -157,7 +157,7 @@ class ProjectGenerationRequestTests { this.request.setOutput("my-project"); this.request.setArtifactId("my-id"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?artifactId=my-id&type=test-type")); + .isEqualTo(createDefaultUrl("?artifactId=my-id&type=test-type")); } @Test @@ -165,7 +165,7 @@ class ProjectGenerationRequestTests { InitializrServiceMetadata metadata = readMetadata(); setBuildAndFormat("does-not-exist", null); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.request.generateUrl(metadata)) - .withMessageContaining("does-not-exist"); + .withMessageContaining("does-not-exist"); } @Test @@ -173,7 +173,8 @@ class ProjectGenerationRequestTests { InitializrServiceMetadata metadata = readMetadata("types-conflict"); setBuildAndFormat("gradle", null); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.request.generateUrl(metadata)) - .withMessageContaining("gradle-project").withMessageContaining("gradle-project-2"); + .withMessageContaining("gradle-project") + .withMessageContaining("gradle-project-2"); } @Test @@ -195,14 +196,14 @@ class ProjectGenerationRequestTests { void invalidType() { this.request.setType("does-not-exist"); assertThatExceptionOfType(ReportableException.class) - .isThrownBy(() -> this.request.generateUrl(createDefaultMetadata())); + .isThrownBy(() -> this.request.generateUrl(createDefaultMetadata())); } @Test void noTypeAndNoDefault() { assertThatExceptionOfType(ReportableException.class) - .isThrownBy(() -> this.request.generateUrl(readMetadata("types-conflict"))) - .withMessageContaining("no default is defined"); + .isThrownBy(() -> this.request.generateUrl(readMetadata("types-conflict"))) + .withMessageContaining("no default is defined"); } private static URI createUrl(String actionAndParam) { diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java index 49851cc01d..842bd11fd8 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -112,7 +112,7 @@ class GroovyGrabDependencyResolverTests { @Test void resolveMultipleArtifacts() throws Exception { List resolved = this.resolver - .resolve(Arrays.asList("junit:junit:4.11", "commons-logging:commons-logging:1.1.3")); + .resolve(Arrays.asList("junit:junit:4.11", "commons-logging:commons-logging:1.1.3")); assertThat(resolved).hasSize(4); assertThat(getNames(resolved)).containsOnly("junit-4.11.jar", "commons-logging-1.1.3.jar", "hamcrest-core-2.2.jar", "hamcrest-2.2.jar"); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java index a0679245e7..7759ba8761 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,9 +37,8 @@ class SpringApplicationRunnerTests { given(configuration.getClasspath()).willReturn(new String[] { "foo", "bar" }); given(configuration.getLogLevel()).willReturn(Level.INFO); assertThatExceptionOfType(RuntimeException.class) - .isThrownBy( - () -> new SpringApplicationRunner(configuration, new String[] { "foo", "bar" }).compileAndRun()) - .withMessage("No classes found in '[foo, bar]'"); + .isThrownBy(() -> new SpringApplicationRunner(configuration, new String[] { "foo", "bar" }).compileAndRun()) + .withMessage("No classes found in '[foo, bar]'"); } } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java index 23990bb7d8..ec5ca99e25 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -116,7 +116,7 @@ class DependencyCustomizerTests { @Test void anyMissingClassesWithMixtureOfClassesPerformsAdd() { this.dependencyCustomizer.ifAnyMissingClasses(getClass().getName(), "does.not.Exist") - .add("spring-boot-starter-logging"); + .add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1); } @@ -135,56 +135,68 @@ class DependencyCustomizerTests { @Test void allMissingClassesWithMixtureOfClassesDoesNotPerformAdd() { this.dependencyCustomizer.ifAllMissingClasses(getClass().getName(), "does.not.Exist") - .add("spring-boot-starter-logging"); + .add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty(); } @Test void allMissingClassesWithAllClassesMissingPerformsAdd() { this.dependencyCustomizer.ifAllMissingClasses("does.not.Exist", "does.not.exist.Either") - .add("spring-boot-starter-logging"); + .add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1); } @Test void allResourcesPresentWithAllResourcesPresentPerformsAdd() { - this.dependencyCustomizer.ifAllResourcesPresent("dependency-customizer-tests/resource1.txt", - "dependency-customizer-tests/resource2.txt").add("spring-boot-starter-logging"); + this.dependencyCustomizer + .ifAllResourcesPresent("dependency-customizer-tests/resource1.txt", + "dependency-customizer-tests/resource2.txt") + .add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1); } @Test void allResourcesPresentWithSomeResourcesPresentDoesNotPerformAdd() { - this.dependencyCustomizer.ifAllResourcesPresent("dependency-customizer-tests/resource1.txt", - "dependency-customizer-tests/does-not-exist.txt").add("spring-boot-starter-logging"); + this.dependencyCustomizer + .ifAllResourcesPresent("dependency-customizer-tests/resource1.txt", + "dependency-customizer-tests/does-not-exist.txt") + .add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty(); } @Test void allResourcesPresentWithNoResourcesPresentDoesNotPerformAdd() { - this.dependencyCustomizer.ifAllResourcesPresent("dependency-customizer-tests/does-not-exist", - "dependency-customizer-tests/does-not-exist-either.txt").add("spring-boot-starter-logging"); + this.dependencyCustomizer + .ifAllResourcesPresent("dependency-customizer-tests/does-not-exist", + "dependency-customizer-tests/does-not-exist-either.txt") + .add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty(); } @Test void anyResourcesPresentWithAllResourcesPresentPerformsAdd() { - this.dependencyCustomizer.ifAnyResourcesPresent("dependency-customizer-tests/resource1.txt", - "dependency-customizer-tests/resource2.txt").add("spring-boot-starter-logging"); + this.dependencyCustomizer + .ifAnyResourcesPresent("dependency-customizer-tests/resource1.txt", + "dependency-customizer-tests/resource2.txt") + .add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1); } @Test void anyResourcesPresentWithSomeResourcesPresentPerforms() { - this.dependencyCustomizer.ifAnyResourcesPresent("dependency-customizer-tests/resource1.txt", - "dependency-customizer-tests/does-not-exist.txt").add("spring-boot-starter-logging"); + this.dependencyCustomizer + .ifAnyResourcesPresent("dependency-customizer-tests/resource1.txt", + "dependency-customizer-tests/does-not-exist.txt") + .add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1); } @Test void anyResourcesPresentWithNoResourcesPresentDoesNotPerformAdd() { - this.dependencyCustomizer.ifAnyResourcesPresent("dependency-customizer-tests/does-not-exist", - "dependency-customizer-tests/does-not-exist-either.txt").add("spring-boot-starter-logging"); + this.dependencyCustomizer + .ifAnyResourcesPresent("dependency-customizer-tests/does-not-exist", + "dependency-customizer-tests/does-not-exist-either.txt") + .add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty(); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java index b784f3d422..b46e3ba640 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,7 +38,7 @@ class RepositoryConfigurationFactoryTests { void defaultRepositories() { TestPropertyValues.of("user.home:src/test/resources/maven-settings/basic").applyToSystemProperties(() -> { List repositoryConfiguration = RepositoryConfigurationFactory - .createDefaultRepositoryConfiguration(); + .createDefaultRepositoryConfiguration(); assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot", "spring-milestone"); return null; @@ -48,49 +48,49 @@ class RepositoryConfigurationFactoryTests { @Test void snapshotRepositoriesDisabled() { TestPropertyValues.of("user.home:src/test/resources/maven-settings/basic", "disableSpringSnapshotRepos:true") - .applyToSystemProperties(() -> { - List repositoryConfiguration = RepositoryConfigurationFactory - .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", "local"); - return null; - }); + .applyToSystemProperties(() -> { + List repositoryConfiguration = RepositoryConfigurationFactory + .createDefaultRepositoryConfiguration(); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local"); + return null; + }); } @Test void activeByDefaultProfileRepositories() { TestPropertyValues.of("user.home:src/test/resources/maven-settings/active-profile-repositories") - .applyToSystemProperties(() -> { - List repositoryConfiguration = RepositoryConfigurationFactory - .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot", - "spring-milestone", "active-by-default"); - return null; - }); + .applyToSystemProperties(() -> { + List repositoryConfiguration = RepositoryConfigurationFactory + .createDefaultRepositoryConfiguration(); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot", + "spring-milestone", "active-by-default"); + return null; + }); } @Test void activeByPropertyProfileRepositories() { TestPropertyValues.of("user.home:src/test/resources/maven-settings/active-profile-repositories", "foo:bar") - .applyToSystemProperties(() -> { - List repositoryConfiguration = RepositoryConfigurationFactory - .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot", - "spring-milestone", "active-by-property"); - return null; - }); + .applyToSystemProperties(() -> { + List repositoryConfiguration = RepositoryConfigurationFactory + .createDefaultRepositoryConfiguration(); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot", + "spring-milestone", "active-by-property"); + return null; + }); } @Test void interpolationProfileRepositories() { TestPropertyValues - .of("user.home:src/test/resources/maven-settings/active-profile-repositories", "interpolate:true") - .applyToSystemProperties(() -> { - List repositoryConfiguration = RepositoryConfigurationFactory - .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot", - "spring-milestone", "interpolate-releases", "interpolate-snapshots"); - return null; - }); + .of("user.home:src/test/resources/maven-settings/active-profile-repositories", "interpolate:true") + .applyToSystemProperties(() -> { + List repositoryConfiguration = RepositoryConfigurationFactory + .createDefaultRepositoryConfiguration(); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot", + "spring-milestone", "interpolate-releases", "interpolate-snapshots"); + return null; + }); } private void assertRepositoryConfiguration(List configurations, String... expectedNames) { diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java index 27bf910460..b8cc0af98c 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,14 +45,14 @@ class CompositeDependencyManagementTests { given(this.dependencyManagement1.getSpringBootVersion()).willReturn(null); given(this.dependencyManagement2.getSpringBootVersion()).willReturn(null); assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) - .getSpringBootVersion()).isNull(); + .getSpringBootVersion()).isNull(); } @Test void knownSpringBootVersion() { given(this.dependencyManagement1.getSpringBootVersion()).willReturn("1.2.3"); assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) - .getSpringBootVersion()).isEqualTo("1.2.3"); + .getSpringBootVersion()).isEqualTo("1.2.3"); } @Test @@ -60,25 +60,25 @@ class CompositeDependencyManagementTests { given(this.dependencyManagement1.find("artifact")).willReturn(null); given(this.dependencyManagement2.find("artifact")).willReturn(null); assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) - .find("artifact")).isNull(); + .find("artifact")).isNull(); } @Test void knownDependency() { given(this.dependencyManagement1.find("artifact")).willReturn(new Dependency("test", "artifact", "1.2.3")); assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) - .find("artifact")).isEqualTo(new Dependency("test", "artifact", "1.2.3")); + .find("artifact")).isEqualTo(new Dependency("test", "artifact", "1.2.3")); } @Test void getDependencies() { given(this.dependencyManagement1.getDependencies()) - .willReturn(Arrays.asList(new Dependency("test", "artifact", "1.2.3"))); + .willReturn(Arrays.asList(new Dependency("test", "artifact", "1.2.3"))); given(this.dependencyManagement2.getDependencies()) - .willReturn(Arrays.asList(new Dependency("test", "artifact", "1.2.4"))); + .willReturn(Arrays.asList(new Dependency("test", "artifact", "1.2.4"))); assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) - .getDependencies()).containsOnly(new Dependency("test", "artifact", "1.2.3"), - new Dependency("test", "artifact", "1.2.4")); + .getDependencies()) + .containsOnly(new Dependency("test", "artifact", "1.2.3"), new Dependency("test", "artifact", "1.2.4")); } } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java index 0ecfb31e80..cec5dbeff2 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +57,7 @@ final class DetailedProgressReporterTests { TransferEvent startedEvent = new TransferEvent.Builder(this.session, this.resource).build(); this.session.getTransferListener().transferStarted(startedEvent); assertThat(new String(this.baos.toByteArray())) - .isEqualTo(String.format("Downloading: %s%s%n", REPOSITORY, ARTIFACT)); + .isEqualTo(String.format("Downloading: %s%s%n", REPOSITORY, ARTIFACT)); } @Test @@ -65,7 +65,7 @@ final class DetailedProgressReporterTests { // Ensure some transfer time Thread.sleep(100); TransferEvent completedEvent = new TransferEvent.Builder(this.session, this.resource).addTransferredBytes(4096) - .build(); + .build(); this.session.getTransferListener().transferSucceeded(completedEvent); String message = new String(this.baos.toByteArray()).replace("\\", "/"); assertThat(message).startsWith("Downloaded: " + REPOSITORY + ARTIFACT); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java index 001c79e642..0f90602154 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,15 +54,15 @@ class GrapeRootRepositorySystemSessionAutoConfigurationTests { @Test void noLocalRepositoryWhenNoGrapeRoot() { new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session, this.repositorySystem); - then(this.repositorySystem).should(never()).newLocalRepositoryManager(eq(this.session), - any(LocalRepository.class)); + then(this.repositorySystem).should(never()) + .newLocalRepositoryManager(eq(this.session), any(LocalRepository.class)); assertThat(this.session.getLocalRepository()).isNull(); } @Test void grapeRootConfiguresLocalRepositoryLocation() { given(this.repositorySystem.newLocalRepositoryManager(eq(this.session), any(LocalRepository.class))) - .willAnswer(new LocalRepositoryManagerAnswer()); + .willAnswer(new LocalRepositoryManagerAnswer()); System.setProperty("grape.root", "foo"); try { @@ -76,7 +76,7 @@ class GrapeRootRepositorySystemSessionAutoConfigurationTests { assertThat(this.session.getLocalRepository()).isNotNull(); assertThat(this.session.getLocalRepository().getBasedir().getAbsolutePath()) - .endsWith(File.separatorChar + "foo" + File.separatorChar + "repository"); + .endsWith(File.separatorChar + "foo" + File.separatorChar + "repository"); } private class LocalRepositoryManagerAnswer implements Answer { @@ -85,7 +85,7 @@ class GrapeRootRepositorySystemSessionAutoConfigurationTests { public LocalRepositoryManager answer(InvocationOnMock invocation) throws Throwable { LocalRepository localRepository = invocation.getArgument(1); return new SimpleLocalRepositoryManagerFactory() - .newInstance(GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session, localRepository); + .newInstance(GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session, localRepository); } } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/MavenResolverGrapeEngineTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/MavenResolverGrapeEngineTests.java index 2b39dd1c00..aaf9b08fb3 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/MavenResolverGrapeEngineTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/MavenResolverGrapeEngineTests.java @@ -57,7 +57,7 @@ class MavenResolverGrapeEngineTests { private GrapeEngine createGrapeEngine(RepositoryConfiguration... additionalRepositories) { List repositoryConfigurations = new ArrayList<>(); repositoryConfigurations - .add(new RepositoryConfiguration("central", URI.create("https://repo.maven.apache.org/maven2"), false)); + .add(new RepositoryConfiguration("central", URI.create("https://repo.maven.apache.org/maven2"), false)); repositoryConfigurations.addAll(Arrays.asList(additionalRepositories)); DependencyResolutionContext dependencyResolutionContext = new DependencyResolutionContext(); dependencyResolutionContext.addDependencyManagement(new SpringBootDependenciesDependencyManagement()); @@ -78,7 +78,7 @@ class MavenResolverGrapeEngineTests { doWithCustomUserHome(() -> { GrapeEngine grapeEngine = createGrapeEngine(); DefaultRepositorySystemSession session = (DefaultRepositorySystemSession) ReflectionTestUtils - .getField(grapeEngine, "session"); + .getField(grapeEngine, "session"); assertThat(session.getProxySelector() instanceof CompositeProxySelector).isTrue(); }); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java index a7cb253f83..945a1aa0b5 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,18 +64,18 @@ class SettingsXmlRepositorySystemSessionAutoConfigurationTests { void propertyInterpolation() { final DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); given(this.repositorySystem.newLocalRepositoryManager(eq(session), any(LocalRepository.class))) - .willAnswer((invocation) -> { - LocalRepository localRepository = invocation.getArgument(1); - return new SimpleLocalRepositoryManagerFactory().newInstance(session, localRepository); - }); + .willAnswer((invocation) -> { + LocalRepository localRepository = invocation.getArgument(1); + return new SimpleLocalRepositoryManagerFactory().newInstance(session, localRepository); + }); TestPropertyValues.of("user.home:src/test/resources/maven-settings/property-interpolation", "foo:bar") - .applyToSystemProperties(() -> { - new SettingsXmlRepositorySystemSessionAutoConfiguration().apply(session, - SettingsXmlRepositorySystemSessionAutoConfigurationTests.this.repositorySystem); - return null; - }); + .applyToSystemProperties(() -> { + new SettingsXmlRepositorySystemSessionAutoConfiguration().apply(session, + SettingsXmlRepositorySystemSessionAutoConfigurationTests.this.repositorySystem); + return null; + }); assertThat(session.getLocalRepository().getBasedir().getAbsolutePath()) - .endsWith(File.separatorChar + "bar" + File.separatorChar + "repository"); + .endsWith(File.separatorChar + "bar" + File.separatorChar + "repository"); } private void assertSessionCustomization(String userHome) { @@ -86,7 +86,7 @@ class SettingsXmlRepositorySystemSessionAutoConfigurationTests { return null; }); RemoteRepository repository = new RemoteRepository.Builder("my-server", "default", "https://maven.example.com") - .build(); + .build(); assertMirrorSelectorConfiguration(session, repository); assertProxySelectorConfiguration(session, repository); assertAuthenticationSelectorConfiguration(session, repository); diff --git a/spring-boot-project/spring-boot-devtools/src/intTest/java/com/example/DevToolsTestApplication.java b/spring-boot-project/spring-boot-devtools/src/intTest/java/com/example/DevToolsTestApplication.java index 6a8446235d..5dfae2d5db 100644 --- a/spring-boot-project/spring-boot-devtools/src/intTest/java/com/example/DevToolsTestApplication.java +++ b/spring-boot-project/spring-boot-devtools/src/intTest/java/com/example/DevToolsTestApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ public class DevToolsTestApplication { public static void main(String[] args) { new SpringApplicationBuilder(DevToolsTestApplication.class).listeners(new WebServerPortFileWriter(args[0])) - .run(args); + .run(args); } } diff --git a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/AbstractApplicationLauncher.java b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/AbstractApplicationLauncher.java index 67b7366088..9d054d3632 100644 --- a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/AbstractApplicationLauncher.java +++ b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/AbstractApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,8 +45,9 @@ abstract class AbstractApplicationLauncher implements ApplicationLauncher { } protected final List getDependencyJarPaths() { - return Stream.of(this.directories.getDependenciesDirectory().listFiles()).map(File::getAbsolutePath) - .collect(Collectors.toList()); + return Stream.of(this.directories.getDependenciesDirectory().listFiles()) + .map(File::getAbsolutePath) + .collect(Collectors.toList()); } protected final Directories getDirectories() { diff --git a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/AbstractDevToolsIntegrationTests.java b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/AbstractDevToolsIntegrationTests.java index 80848cac56..d0a90c246a 100644 --- a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/AbstractDevToolsIntegrationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/AbstractDevToolsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,9 +66,9 @@ abstract class AbstractDevToolsIntegrationTests { protected int awaitServerPort() throws Exception { int port = Awaitility.waitAtMost(Duration.ofMinutes(3)) - .until(() -> new ApplicationState(this.serverPortFile, this.launchedApplication), - ApplicationState::hasServerPort) - .getServerPort(); + .until(() -> new ApplicationState(this.serverPortFile, this.launchedApplication), + ApplicationState::hasServerPort) + .getServerPort(); this.serverPortFile.delete(); this.launchedApplication.restartRemote(port); Thread.sleep(1000); @@ -98,12 +98,15 @@ abstract class AbstractDevToolsIntegrationTests { } protected void build() throws Exception { - DynamicType.Builder builder = new ByteBuddy().subclass(Object.class).name(this.name) - .annotateType(AnnotationDescription.Builder.ofType(RestController.class).build()); + DynamicType.Builder builder = new ByteBuddy().subclass(Object.class) + .name(this.name) + .annotateType(AnnotationDescription.Builder.ofType(RestController.class).build()); for (String mapping : this.mappings) { builder = builder.defineMethod(mapping, String.class, Visibility.PUBLIC) - .intercept(FixedValue.value(mapping)).annotateMethod(AnnotationDescription.Builder - .ofType(RequestMapping.class).defineArray("value", mapping).build()); + .intercept(FixedValue.value(mapping)) + .annotateMethod(AnnotationDescription.Builder.ofType(RequestMapping.class) + .defineArray("value", mapping) + .build()); } builder.make().saveIn(this.classesDirectory); } diff --git a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java index 24c2f9434a..6dfe05f4c7 100644 --- a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ class DevToolsIntegrationTests extends AbstractDevToolsIntegrationTests { String urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(this.template.getForEntity(urlBase + "/two", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); controller("com.example.ControllerOne").withRequestMapping("one").withRequestMapping("two").build(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); @@ -64,7 +64,7 @@ class DevToolsIntegrationTests extends AbstractDevToolsIntegrationTests { controller("com.example.ControllerOne").build(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForEntity(urlBase + "/one", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); } @ParameterizedTest(name = "{0}") @@ -74,7 +74,7 @@ class DevToolsIntegrationTests extends AbstractDevToolsIntegrationTests { String urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(this.template.getForEntity(urlBase + "/two", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); controller("com.example.ControllerTwo").withRequestMapping("two").build(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); @@ -89,7 +89,7 @@ class DevToolsIntegrationTests extends AbstractDevToolsIntegrationTests { String urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(this.template.getForEntity(urlBase + "/two", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); controller("com.example.ControllerTwo").withRequestMapping("two").build(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); @@ -107,7 +107,7 @@ class DevToolsIntegrationTests extends AbstractDevToolsIntegrationTests { String urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(this.template.getForEntity(urlBase + "/two", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); controller("com.example.ControllerTwo").withRequestMapping("two").build(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); @@ -126,10 +126,10 @@ class DevToolsIntegrationTests extends AbstractDevToolsIntegrationTests { String urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(new File(this.launchedApplication.getClassesDirectory(), "com/example/ControllerOne.class").delete()) - .isTrue(); + .isTrue(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForEntity(urlBase + "/one", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); } @@ -140,16 +140,16 @@ class DevToolsIntegrationTests extends AbstractDevToolsIntegrationTests { String urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(this.template.getForEntity(urlBase + "/two", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); controller("com.example.ControllerTwo").withRequestMapping("two").build(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(this.template.getForObject(urlBase + "/two", String.class)).isEqualTo("two"); assertThat(new File(this.launchedApplication.getClassesDirectory(), "com/example/ControllerTwo.class").delete()) - .isTrue(); + .isTrue(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForEntity(urlBase + "/two", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); } static Object[] parameters() { diff --git a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/DevToolsWithLazyInitializationIntegrationTests.java b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/DevToolsWithLazyInitializationIntegrationTests.java index 135bcdbfb0..d5666384a4 100644 --- a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/DevToolsWithLazyInitializationIntegrationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/DevToolsWithLazyInitializationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,7 +40,7 @@ class DevToolsWithLazyInitializationIntegrationTests extends AbstractDevToolsInt String urlBase = "http://localhost:" + awaitServerPort(); assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(template.getForEntity(urlBase + "/two", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); controller("com.example.ControllerOne").withRequestMapping("one").withRequestMapping("two").build(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); diff --git a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/JvmLauncher.java b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/JvmLauncher.java index 757ed11f87..bbda1c26d1 100644 --- a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/JvmLauncher.java +++ b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/JvmLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,7 +59,8 @@ class JvmLauncher implements BeforeTestExecutionCallback { File standardOut = new File(this.outputDirectory, name + ".out"); File standardError = new File(this.outputDirectory, name + ".err"); Process process = new ProcessBuilder(StringUtils.toStringArray(command)).redirectError(standardError) - .redirectOutput(standardOut).start(); + .redirectOutput(standardOut) + .start(); return new LaunchedJvm(process, standardOut, standardError); } diff --git a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/RemoteApplicationLauncher.java b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/RemoteApplicationLauncher.java index 0fcf1d4787..51199d8289 100644 --- a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/RemoteApplicationLauncher.java +++ b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/RemoteApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -102,15 +102,15 @@ abstract class RemoteApplicationLauncher extends AbstractApplicationLauncher { private int awaitServerPort(LaunchedJvm jvm, File serverPortFile) { return Awaitility.waitAtMost(Duration.ofMinutes(3)) - .until(() -> new ApplicationState(serverPortFile, jvm), ApplicationState::hasServerPort) - .getServerPort(); + .until(() -> new ApplicationState(serverPortFile, jvm), ApplicationState::hasServerPort) + .getServerPort(); } private void awaitRemoteSpringApplication(LaunchedJvm launchedJvm) { FileContents contents = new FileContents(launchedJvm.getStandardOut()); try { - Awaitility.waitAtMost(Duration.ofMinutes(3)).until(contents::get, - containsString("Started RemoteSpringApplication")); + Awaitility.waitAtMost(Duration.ofMinutes(3)) + .until(contents::get, containsString("Started RemoteSpringApplication")); } catch (ConditionTimeoutException ex) { if (!launchedJvm.getProcess().isAlive()) { diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java index b09e5e0d26..99644ac573 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -189,8 +189,9 @@ public class DevToolsDataSourceAutoConfiguration { if (dataSourceDefinition instanceof AnnotatedBeanDefinition && ((AnnotatedBeanDefinition) dataSourceDefinition).getFactoryMethodMetadata() != null && ((AnnotatedBeanDefinition) dataSourceDefinition).getFactoryMethodMetadata() - .getDeclaringClassName().startsWith(DataSourceAutoConfiguration.class.getPackage().getName() - + ".DataSourceConfiguration$")) { + .getDeclaringClassName() + .startsWith(DataSourceAutoConfiguration.class.getPackage().getName() + + ".DataSourceConfiguration$")) { return ConditionOutcome.match(message.foundExactly("auto-configured DataSource")); } return ConditionOutcome.noMatch(message.didNotFind("an auto-configured DataSource").atAll()); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsR2dbcAutoConfiguration.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsR2dbcAutoConfiguration.java index c59b9fc2bf..90090d252d 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsR2dbcAutoConfiguration.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsR2dbcAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -75,7 +75,8 @@ public class DevToolsR2dbcAutoConfiguration { public void destroy() throws Exception { if (shouldShutdown()) { Mono.usingWhen(this.connectionFactory.create(), this::executeShutdown, this::closeConnection, - this::closeConnection, this::closeConnection).block(); + this::closeConnection, this::closeConnection) + .block(); this.eventPublisher.publishEvent(new R2dbcDatabaseShutdownEvent(this.connectionFactory)); } } @@ -128,7 +129,7 @@ public class DevToolsR2dbcAutoConfiguration { private boolean isAutoConfigured(AnnotatedBeanDefinition beanDefinition) { MethodMetadata methodMetadata = beanDefinition.getFactoryMethodMetadata(); return methodMetadata != null && methodMetadata.getDeclaringClassName() - .startsWith(R2dbcAutoConfiguration.class.getPackage().getName()); + .startsWith(R2dbcAutoConfiguration.class.getPackage().getName()); } } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/RemoteDevtoolsSecurityConfiguration.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/RemoteDevtoolsSecurityConfiguration.java index 53247b595a..2429f6cd7d 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/RemoteDevtoolsSecurityConfiguration.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/RemoteDevtoolsSecurityConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,13 @@ class RemoteDevtoolsSecurityConfiguration { @ConditionalOnMissingBean(org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.class) @SuppressWarnings("deprecation") SecurityFilterChain devtoolsSecurityFilterChain(HttpSecurity http) throws Exception { - http.requestMatcher(new AntPathRequestMatcher(this.url)).authorizeRequests().anyRequest().anonymous().and() - .csrf().disable(); + http.requestMatcher(new AntPathRequestMatcher(this.url)) + .authorizeRequests() + .anyRequest() + .anonymous() + .and() + .csrf() + .disable(); return http.build(); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathChangedEvent.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathChangedEvent.java index 982a9e4714..b08ce3beff 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathChangedEvent.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathChangedEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,7 +70,8 @@ public class ClassPathChangedEvent extends ApplicationEvent { @Override public String toString() { return new ToStringCreator(this).append("changeSet", this.changeSet) - .append("restartRequired", this.restartRequired).toString(); + .append("restartRequired", this.restartRequired) + .toString(); } /** diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessor.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessor.java index e8dd2bfe31..232df1adb9 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessor.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -134,7 +134,7 @@ public class DevToolsHomePropertiesPostProcessor implements EnvironmentPostProce private boolean canLoadFileExtension(PropertySourceLoader loader, String name) { return Arrays.stream(loader.getFileExtensions()) - .anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(name, fileExtension)); + .anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(name, fileExtension)); } protected File getHomeDirectory() { diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java index 26c28ceace..e1ab68a78f 100755 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,7 +65,7 @@ public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostPro static { Properties properties = new Properties(); try (InputStream stream = DevToolsPropertyDefaultsPostProcessor.class - .getResourceAsStream("devtools-property-defaults.properties")) { + .getResourceAsStream("devtools-property-defaults.properties")) { properties.load(stream); } catch (IOException ex) { diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/Connection.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/Connection.java index 7c332ef3bc..058e682efe 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/Connection.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/Connection.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -96,7 +96,8 @@ class Connection { this.outputStream.writeHeaders("HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Accept: " + accept); new Frame("{\"command\":\"hello\",\"protocols\":[\"http://livereload.com/protocols/official-7\"]," - + "\"serverName\":\"spring-boot\"}").write(this.outputStream); + + "\"serverName\":\"spring-boot\"}") + .write(this.outputStream); while (this.running) { readWebSocketFrame(); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java index fe1d58d233..51a61df9b5 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -95,7 +95,7 @@ public class RemoteClientConfiguration implements InitializingBean { Proxy proxy = this.properties.getRemote().getProxy(); if (proxy.getHost() != null && proxy.getPort() != null) { requestFactory - .setProxy(new java.net.Proxy(Type.HTTP, new InetSocketAddress(proxy.getHost(), proxy.getPort()))); + .setProxy(new java.net.Proxy(Type.HTTP, new InetSocketAddress(proxy.getHost(), proxy.getPort()))); } return new InterceptingClientHttpRequestFactory(requestFactory, interceptors); } 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..9df04b462b 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -106,7 +106,8 @@ final class ChangeableUrls implements Iterable { return ((URLClassLoader) classLoader).getURLs(); } return Stream.of(ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) - .map(ChangeableUrls::toURL).toArray(URL[]::new); + .map(ChangeableUrls::toURL) + .toArray(URL[]::new); } private static URL toURL(String classPathEntry) { diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolver.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolver.java index 239d190e19..593dbf35b8 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolver.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,7 +74,7 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe ClassLoaderFiles classLoaderFiles) { this.classLoaderFiles = classLoaderFiles; this.patternResolverDelegate = getResourcePatternResolverFactory() - .getResourcePatternResolver(applicationContext, retrieveResourceLoader(applicationContext)); + .getResourcePatternResolver(applicationContext, retrieveResourceLoader(applicationContext)); } private ResourceLoader retrieveResourceLoader(ApplicationContext applicationContext) { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java index 24f24b53f0..a6b5cbf3cf 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,8 @@ class RemoteUrlPropertyExtractorTests { @AfterEach void preventRunFailuresFromPollutingLoggerContext() { ((Logger) LoggerFactory.getLogger(RemoteUrlPropertyExtractorTests.class)).getLoggerContext() - .getTurboFilterList().clear(); + .getTurboFilterList() + .clear(); } @Test @@ -50,14 +51,14 @@ class RemoteUrlPropertyExtractorTests { @Test void malformedUrl() { assertThatIllegalStateException().isThrownBy(() -> doTest("::://wibble")) - .withMessageContaining("Malformed URL '::://wibble'"); + .withMessageContaining("Malformed URL '::://wibble'"); } @Test void multipleUrls() { assertThatIllegalStateException().isThrownBy(() -> doTest("http://localhost:8080", "http://localhost:9090")) - .withMessageContaining("Multiple URLs specified"); + .withMessageContaining("Multiple URLs specified"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java index 0db015da50..5acc1ecd7a 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -132,16 +132,17 @@ class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevToolsDat jdbc.execute("SELECT 1 FROM SYSIBM.SYSDUMMY1"); HikariPoolMXBean pool = dataSource.getHikariPoolMXBean(); // Prevent a race between Hikari's initialization and Derby shutdown - Awaitility.await().atMost(Duration.ofSeconds(30)).until(pool::getIdleConnections, - (idle) -> idle == dataSource.getMinimumIdle()); + Awaitility.await() + .atMost(Duration.ofSeconds(30)) + .until(pool::getIdleConnections, (idle) -> idle == dataSource.getMinimumIdle()); context.close(); // Connect should fail as DB no longer exists assertThatExceptionOfType(SQLException.class) - .isThrownBy(() -> new EmbeddedDriver().connect("jdbc:derby:memory:test", new Properties())) - .satisfies((ex) -> assertThat(ex.getSQLState()).isEqualTo("XJ004")); + .isThrownBy(() -> new EmbeddedDriver().connect("jdbc:derby:memory:test", new Properties())) + .satisfies((ex) -> assertThat(ex.getSQLState()).isEqualTo("XJ004")); // Shut Derby down fully so that it closes its log file assertThatExceptionOfType(SQLException.class) - .isThrownBy(() -> new EmbeddedDriver().connect("jdbc:derby:;shutdown=true", new Properties())); + .isThrownBy(() -> new EmbeddedDriver().connect("jdbc:derby:;shutdown=true", new Properties())); } } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java index 9155b232d8..478e6ff283 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -153,7 +153,7 @@ class LocalDevToolsAutoConfigurationTests { properties.put("spring.devtools.livereload.enabled", false); this.context = getContext(() -> initializeAndRun(Config.class, properties)); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(OptionalLiveReloadServer.class)); + .isThrownBy(() -> this.context.getBean(OptionalLiveReloadServer.class)); } @Test @@ -185,7 +185,7 @@ class LocalDevToolsAutoConfigurationTests { properties.put("spring.devtools.restart.enabled", false); this.context = getContext(() -> initializeAndRun(Config.class, properties)); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(ClassPathFileSystemWatcher.class)); + .isThrownBy(() -> this.context.getBean(ClassPathFileSystemWatcher.class)); } @Test @@ -208,19 +208,20 @@ class LocalDevToolsAutoConfigurationTests { Object watcher = ReflectionTestUtils.getField(classPathWatcher, "fileSystemWatcher"); @SuppressWarnings("unchecked") Map directories = (Map) ReflectionTestUtils.getField(watcher, "directories"); - assertThat(directories).hasSize(2).containsKey(new File("src/main/java").getAbsoluteFile()) - .containsKey(new File("src/test/java").getAbsoluteFile()); + assertThat(directories).hasSize(2) + .containsKey(new File("src/main/java").getAbsoluteFile()) + .containsKey(new File("src/test/java").getAbsoluteFile()); } @Test void devToolsSwitchesJspServletToDevelopmentMode() throws Exception { this.context = getContext(() -> initializeAndRun(Config.class)); TomcatWebServer tomcatContainer = (TomcatWebServer) ((ServletWebServerApplicationContext) this.context) - .getWebServer(); + .getWebServer(); Container context = tomcatContainer.getTomcat().getHost().findChildren()[0]; StandardWrapper jspServletWrapper = (StandardWrapper) context.findChild("jsp"); EmbeddedServletOptions options = (EmbeddedServletOptions) ReflectionTestUtils - .getField(jspServletWrapper.getServlet(), "options"); + .getField(jspServletWrapper.getServlet(), "options"); assertThat(options.getDevelopment()).isTrue(); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java index ff32ce4db4..18869036af 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -96,7 +96,7 @@ class RemoteDevToolsAutoConfigurationTests { void disabledIfRemoteSecretIsMissing() throws Exception { this.context = getContext(() -> loadContext("a:b")); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(DispatcherFilter.class)); + .isThrownBy(() -> this.context.getBean(DispatcherFilter.class)); } @Test @@ -153,10 +153,14 @@ class RemoteDevToolsAutoConfigurationTests { void securityConfigurationShouldAllowAccess() throws Exception { this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()).addFilter(filter) - .build(); - mockMvc.perform(MockMvcRequestBuilders.get(DEFAULT_CONTEXT_PATH + "/restart").header(DEFAULT_SECRET_HEADER_NAME, - "supersecret")).andExpect(status().isOk()); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) + .apply(springSecurity()) + .addFilter(filter) + .build(); + mockMvc + .perform(MockMvcRequestBuilders.get(DEFAULT_CONTEXT_PATH + "/restart") + .header(DEFAULT_SECRET_HEADER_NAME, "supersecret")) + .andExpect(status().isOk()); assertRestartInvoked(true); assertThat(this.context.containsBean("devtoolsSecurityFilterChain")).isTrue(); } @@ -166,11 +170,14 @@ class RemoteDevToolsAutoConfigurationTests { this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret", "server.servlet.context-path:/test", "spring.devtools.remote.context-path:/custom")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()).addFilter(filter) - .build(); - mockMvc.perform( - MockMvcRequestBuilders.get("/test/custom/restart").header(DEFAULT_SECRET_HEADER_NAME, "supersecret")) - .andExpect(status().isOk()); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) + .apply(springSecurity()) + .addFilter(filter) + .build(); + mockMvc + .perform(MockMvcRequestBuilders.get("/test/custom/restart") + .header(DEFAULT_SECRET_HEADER_NAME, "supersecret")) + .andExpect(status().isOk()); assertRestartInvoked(true); } @@ -179,8 +186,10 @@ class RemoteDevToolsAutoConfigurationTests { this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); Filter securityFilterChain = this.context.getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN, Filter.class); - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).addFilter(securityFilterChain) - .addFilter(filter).build(); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) + .addFilter(securityFilterChain) + .addFilter(filter) + .build(); mockMvc.perform(MockMvcRequestBuilders.get("/my-path")).andExpect(status().isUnauthorized()); } @@ -196,10 +205,14 @@ class RemoteDevToolsAutoConfigurationTests { return context; }); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()).addFilter(filter) - .build(); - mockMvc.perform(MockMvcRequestBuilders.get(DEFAULT_CONTEXT_PATH + "/restart").header(DEFAULT_SECRET_HEADER_NAME, - "supersecret")).andExpect(status().isOk()); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) + .apply(springSecurity()) + .addFilter(filter) + .build(); + mockMvc + .perform(MockMvcRequestBuilders.get(DEFAULT_CONTEXT_PATH + "/restart") + .header(DEFAULT_SECRET_HEADER_NAME, "supersecret")) + .andExpect(status().isOk()); assertRestartInvoked(true); } @@ -208,7 +221,7 @@ class RemoteDevToolsAutoConfigurationTests { this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret", "spring.devtools.remote.restart.enabled:false")); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean("remoteRestartHandlerMapper")); + .isThrownBy(() -> this.context.getBean("remoteRestartHandlerMapper")); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java index 1e7257e2e9..458a5826d5 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ class TriggerFileFilterTests { @Test void nameMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new TriggerFileFilter(null)) - .withMessageContaining("Name must not be null"); + .withMessageContaining("Name must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java index 0b2641a98d..3f7c92e041 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,7 +38,7 @@ class ClassPathChangedEventTests { @Test void changeSetMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassPathChangedEvent(this.source, null, false)) - .withMessageContaining("ChangeSet must not be null"); + .withMessageContaining("ChangeSet must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java index 10d24c88ea..1247722343 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,15 +63,15 @@ class ClassPathFileChangeListenerTests { @Test void eventPublisherMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassPathFileChangeListener(null, this.restartStrategy, this.fileSystemWatcher)) - .withMessageContaining("EventPublisher must not be null"); + .isThrownBy(() -> new ClassPathFileChangeListener(null, this.restartStrategy, this.fileSystemWatcher)) + .withMessageContaining("EventPublisher must not be null"); } @Test void restartStrategyMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassPathFileChangeListener(this.eventPublisher, null, this.fileSystemWatcher)) - .withMessageContaining("RestartStrategy must not be null"); + .isThrownBy(() -> new ClassPathFileChangeListener(this.eventPublisher, null, this.fileSystemWatcher)) + .withMessageContaining("RestartStrategy must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java index f98c92a44c..a91c220566 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,9 +53,9 @@ class ClassPathFileSystemWatcherTests { @Test void urlsMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassPathFileSystemWatcher(mock(FileSystemWatcherFactory.class), - mock(ClassPathRestartStrategy.class), (URL[]) null)) - .withMessageContaining("Urls must not be null"); + .isThrownBy(() -> new ClassPathFileSystemWatcher(mock(FileSystemWatcherFactory.class), + mock(ClassPathRestartStrategy.class), (URL[]) null)) + .withMessageContaining("Urls must not be null"); } @Test @@ -83,7 +83,7 @@ class ClassPathFileSystemWatcherTests { } assertThat(events).hasSize(1); assertThat(events.get(0).getChangeSet().iterator().next()).extracting(ChangedFile::getFile) - .containsExactly(classFile); + .containsExactly(classFile); context.close(); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java index a5a0d62002..1ebbac1bf4 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,7 +87,7 @@ class DevToolPropertiesIntegrationTests { application.setWebApplicationType(WebApplicationType.NONE); this.context = getContext(application::run); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(MyBean.class)); + .isThrownBy(() -> this.context.getBean(MyBean.class)); } @Test @@ -109,10 +109,10 @@ class DevToolPropertiesIntegrationTests { ConfigurableEnvironment environment = this.context.getEnvironment(); String includeStackTrace = environment.getProperty("server.error.include-stacktrace"); assertThat(includeStackTrace) - .isEqualTo(ErrorProperties.IncludeAttribute.ALWAYS.toString().toLowerCase(Locale.ENGLISH)); + .isEqualTo(ErrorProperties.IncludeAttribute.ALWAYS.toString().toLowerCase(Locale.ENGLISH)); String includeMessage = environment.getProperty("server.error.include-message"); assertThat(includeMessage) - .isEqualTo(ErrorProperties.IncludeAttribute.ALWAYS.toString().toLowerCase(Locale.ENGLISH)); + .isEqualTo(ErrorProperties.IncludeAttribute.ALWAYS.toString().toLowerCase(Locale.ENGLISH)); } protected ConfigurableApplicationContext getContext(Supplier supplier) diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java index bb5c3a344e..7a59b90c06 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,22 +39,23 @@ class ChangedFileTests { @Test void sourceDirectoryMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ChangedFile(null, new File(this.tempDir, "file"), Type.ADD)) - .withMessageContaining("SourceDirectory must not be null"); + .isThrownBy(() -> new ChangedFile(null, new File(this.tempDir, "file"), Type.ADD)) + .withMessageContaining("SourceDirectory must not be null"); } @Test void fileMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ChangedFile(new File(this.tempDir, "directory"), null, Type.ADD)) - .withMessageContaining("File must not be null"); + .isThrownBy(() -> new ChangedFile(new File(this.tempDir, "directory"), null, Type.ADD)) + .withMessageContaining("File must not be null"); } @Test void typeMustNotBeNull() { - assertThatIllegalArgumentException().isThrownBy( - () -> new ChangedFile(new File(this.tempDir, "file"), new File(this.tempDir, "directory"), null)) - .withMessageContaining("Type must not be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new ChangedFile(new File(this.tempDir, "file"), new File(this.tempDir, "directory"), null)) + .withMessageContaining("Type must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/DirectorySnapshotTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/DirectorySnapshotTests.java index 517bc60314..5d235d5cec 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/DirectorySnapshotTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/DirectorySnapshotTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ class DirectorySnapshotTests { @Test void directoryMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new DirectorySnapshot(null)) - .withMessageContaining("Directory must not be null"); + .withMessageContaining("Directory must not be null"); } @Test @@ -61,7 +61,7 @@ class DirectorySnapshotTests { File file = new File(this.tempDir, "file"); file.createNewFile(); assertThatIllegalArgumentException().isThrownBy(() -> new DirectorySnapshot(file)) - .withMessageContaining("Directory '" + file + "' must not be a file"); + .withMessageContaining("Directory '" + file + "' must not be a file"); } @Test @@ -103,14 +103,14 @@ class DirectorySnapshotTests { @Test void getChangedFilesSnapshotMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.initialSnapshot.getChangedFiles(null, null)) - .withMessageContaining("Snapshot must not be null"); + .withMessageContaining("Snapshot must not be null"); } @Test void getChangedFilesSnapshotMustBeTheSameSourceDirectory() { assertThatIllegalArgumentException().isThrownBy( () -> this.initialSnapshot.getChangedFiles(new DirectorySnapshot(createTestDirectoryStructure()), null)) - .withMessageContaining("Snapshot source directory must be '" + this.directory + "'"); + .withMessageContaining("Snapshot source directory must be '" + this.directory + "'"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java index 267222aa6b..155fef7e9e 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ class FileSnapshotTests { @Test void fileMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new FileSnapshot(null)) - .withMessageContaining("File must not be null"); + .withMessageContaining("File must not be null"); } @Test @@ -55,7 +55,7 @@ class FileSnapshotTests { File file = new File(this.tempDir, "file"); file.mkdir(); assertThatIllegalArgumentException().isThrownBy(() -> new FileSnapshot(file)) - .withMessageContaining("File must not be a directory"); + .withMessageContaining("File must not be a directory"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java index 52c56ab951..8d3f411148 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,41 +63,41 @@ class FileSystemWatcherTests { @Test void pollIntervalMustBePositive() { assertThatIllegalArgumentException() - .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(0), Duration.ofMillis(1))) - .withMessageContaining("PollInterval must be positive"); + .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(0), Duration.ofMillis(1))) + .withMessageContaining("PollInterval must be positive"); } @Test void quietPeriodMustBePositive() { assertThatIllegalArgumentException() - .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(1), Duration.ofMillis(0))) - .withMessageContaining("QuietPeriod must be positive"); + .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(1), Duration.ofMillis(0))) + .withMessageContaining("QuietPeriod must be positive"); } @Test void pollIntervalMustBeGreaterThanQuietPeriod() { assertThatIllegalArgumentException() - .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(1), Duration.ofMillis(1))) - .withMessageContaining("PollInterval must be greater than QuietPeriod"); + .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(1), Duration.ofMillis(1))) + .withMessageContaining("PollInterval must be greater than QuietPeriod"); } @Test void listenerMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.watcher.addListener(null)) - .withMessageContaining("FileChangeListener must not be null"); + .withMessageContaining("FileChangeListener must not be null"); } @Test void cannotAddListenerToStartedListener() { this.watcher.start(); assertThatIllegalStateException().isThrownBy(() -> this.watcher.addListener(mock(FileChangeListener.class))) - .withMessageContaining("FileSystemWatcher already started"); + .withMessageContaining("FileSystemWatcher already started"); } @Test void sourceDirectoryMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.watcher.addSourceDirectory(null)) - .withMessageContaining("Directory must not be null"); + .withMessageContaining("Directory must not be null"); } @Test @@ -106,14 +106,14 @@ class FileSystemWatcherTests { assertThat(file.createNewFile()).isTrue(); assertThat(file.isFile()).isTrue(); assertThatIllegalArgumentException().isThrownBy(() -> this.watcher.addSourceDirectory(file)) - .withMessageContaining("Directory '" + file + "' must not be a file"); + .withMessageContaining("Directory '" + file + "' must not be a file"); } @Test void cannotAddSourceDirectoryToStartedListener() { this.watcher.start(); assertThatIllegalStateException().isThrownBy(() -> this.watcher.addSourceDirectory(this.tempDir)) - .withMessageContaining("FileSystemWatcher already started"); + .withMessageContaining("FileSystemWatcher already started"); } @Test @@ -313,8 +313,10 @@ class FileSystemWatcherTests { } private Set getAllFileChanges(List> changes) { - return changes.stream().flatMap(Set::stream) - .flatMap((changedFiles) -> changedFiles.getFiles().stream()).collect(Collectors.toSet()); + return changes.stream() + .flatMap(Set::stream) + .flatMap((changedFiles) -> changedFiles.getFiles().stream()) + .collect(Collectors.toSet()); } private File touch(File file) throws IOException { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java index 37b7c8278b..3331d28f7f 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,7 +68,7 @@ class ConnectionInputStreamTests { byte[] buffer = new byte[100]; ConnectionInputStream inputStream = new ConnectionInputStream(new ByteArrayInputStream(NO_BYTES)); assertThatIOException().isThrownBy(() -> inputStream.checkedRead(buffer, 0, buffer.length)) - .withMessageContaining("End of stream"); + .withMessageContaining("End of stream"); } static class LimitedInputStream extends FilterInputStream { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java index 3a4d49ae55..d54764ffef 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,13 +36,13 @@ class FrameTests { @Test void payloadMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new Frame((String) null)) - .withMessageContaining("Payload must not be null"); + .withMessageContaining("Payload must not be null"); } @Test void typeMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new Frame((Frame.Type) null)) - .withMessageContaining("Type must not be null"); + .withMessageContaining("Type must not be null"); } @Test @@ -88,14 +88,14 @@ class FrameTests { void readFragmentedNotSupported() { byte[] bytes = new byte[] { 0x0F }; assertThatIllegalStateException().isThrownBy(() -> Frame.read(newConnectionInputStream(bytes))) - .withMessageContaining("Fragmented frames are not supported"); + .withMessageContaining("Fragmented frames are not supported"); } @Test void readLargeFramesNotSupported() { byte[] bytes = new byte[] { (byte) 0x80, (byte) 0xFF }; assertThatIllegalStateException().isThrownBy(() -> Frame.read(newConnectionInputStream(bytes))) - .withMessageContaining("Large frames are not supported"); + .withMessageContaining("Large frames are not supported"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java index 195dce640e..263b4d5ae5 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -113,8 +113,8 @@ class LiveReloadServerTests { void triggerReload() throws Exception { LiveReloadWebSocketHandler handler = connect(); this.server.triggerReload(); - List messages = await().atMost(Duration.ofSeconds(10)).until(handler::getMessages, - (msgs) -> msgs.size() == 2); + List messages = await().atMost(Duration.ofSeconds(10)) + .until(handler::getMessages, (msgs) -> msgs.size() == 2); assertThat(messages.get(0)).contains("http://livereload.com/protocols/official-7"); assertThat(messages.get(1)).contains("command\":\"reload\""); } @@ -123,8 +123,8 @@ class LiveReloadServerTests { void triggerReloadWithUppercaseHeaders() throws Exception { LiveReloadWebSocketHandler handler = connect(UppercaseWebSocketClient::new); this.server.triggerReload(); - List messages = await().atMost(Duration.ofSeconds(10)).until(handler::getMessages, - (msgs) -> msgs.size() == 2); + List messages = await().atMost(Duration.ofSeconds(10)) + .until(handler::getMessages, (msgs) -> msgs.size() == 2); assertThat(messages.get(0)).contains("http://livereload.com/protocols/official-7"); assertThat(messages.get(1)).contains("command\":\"reload\""); } @@ -152,8 +152,8 @@ class LiveReloadServerTests { void serverClose() throws Exception { LiveReloadWebSocketHandler handler = connect(); this.server.stop(); - CloseStatus closeStatus = await().atMost(Duration.ofSeconds(10)).until(handler::getCloseStatus, - Objects::nonNull); + CloseStatus closeStatus = await().atMost(Duration.ofSeconds(10)) + .until(handler::getCloseStatus, Objects::nonNull); assertThat(closeStatus.getCode()).isEqualTo(1006); } @@ -302,10 +302,11 @@ class LiveReloadServerTests { StandardWebSocketSession session = new StandardWebSocketSession(headers, attributes, localAddress, remoteAddress); ClientEndpointConfig endpointConfig = ClientEndpointConfig.Builder.create() - .configurator(new UppercaseWebSocketClientConfigurator(headers)).preferredSubprotocols(protocols) - .extensions(extensions.stream().map(WebSocketToStandardExtensionAdapter::new) - .collect(Collectors.toList())) - .build(); + .configurator(new UppercaseWebSocketClientConfigurator(headers)) + .preferredSubprotocols(protocols) + .extensions( + extensions.stream().map(WebSocketToStandardExtensionAdapter::new).collect(Collectors.toList())) + .build(); endpointConfig.getUserProperties().putAll(getUserProperties()); Endpoint endpoint = new StandardWebSocketHandlerAdapter(webSocketHandler, session); Callable connectTask = () -> { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java index e1c232eff7..a9f5c66fc4 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,27 +67,27 @@ class ClassPathChangeUploaderTests { @Test void urlMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassPathChangeUploader(null, this.requestFactory)) - .withMessageContaining("URL must not be empty"); + .withMessageContaining("URL must not be empty"); } @Test void urlMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassPathChangeUploader("", this.requestFactory)) - .withMessageContaining("URL must not be empty"); + .withMessageContaining("URL must not be empty"); } @Test void requestFactoryMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassPathChangeUploader("http://localhost:8080", null)) - .withMessageContaining("RequestFactory must not be null"); + .isThrownBy(() -> new ClassPathChangeUploader("http://localhost:8080", null)) + .withMessageContaining("RequestFactory must not be null"); } @Test void urlMustNotBeMalformed() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassPathChangeUploader("htttttp:///ttest", this.requestFactory)) - .withMessageContaining("Malformed URL 'htttttp:///ttest'"); + .isThrownBy(() -> new ClassPathChangeUploader("htttttp:///ttest", this.requestFactory)) + .withMessageContaining("Malformed URL 'htttttp:///ttest'"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java index 5845181f60..df10274811 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,29 +76,29 @@ class DelayedLiveReloadTriggerTests { @Test void liveReloadServerMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DelayedLiveReloadTrigger(null, this.requestFactory, URL)) - .withMessageContaining("LiveReloadServer must not be null"); + .isThrownBy(() -> new DelayedLiveReloadTrigger(null, this.requestFactory, URL)) + .withMessageContaining("LiveReloadServer must not be null"); } @Test void requestFactoryMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, null, URL)) - .withMessageContaining("RequestFactory must not be null"); + .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, null, URL)) + .withMessageContaining("RequestFactory must not be null"); } @Test void urlMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, null)) - .withMessageContaining("URL must not be empty"); + .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, null)) + .withMessageContaining("URL must not be empty"); } @Test void urlMustNotBeEmpty() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, "")) - .withMessageContaining("URL must not be empty"); + .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, "")) + .withMessageContaining("URL must not be empty"); } @Test @@ -108,7 +108,7 @@ class DelayedLiveReloadTriggerTests { given(this.errorResponse.getStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR); given(this.okResponse.getStatusCode()).willReturn(HttpStatus.OK); given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)).willThrow(new IOException()) - .willReturn(this.errorRequest, this.okRequest); + .willReturn(this.errorRequest, this.okRequest); long startTime = System.currentTimeMillis(); this.trigger.setTimings(10, 200, 30000); this.trigger.run(); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java index 86e4ce66cf..5140994e32 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,25 +74,25 @@ class HttpHeaderInterceptorTests { @Test void constructorNullHeaderName() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor(null, this.value)) - .withMessageContaining("Name must not be empty"); + .withMessageContaining("Name must not be empty"); } @Test void constructorEmptyHeaderName() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor("", this.value)) - .withMessageContaining("Name must not be empty"); + .withMessageContaining("Name must not be empty"); } @Test void constructorNullHeaderValue() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor(this.name, null)) - .withMessageContaining("Value must not be empty"); + .withMessageContaining("Value must not be empty"); } @Test void constructorEmptyHeaderValue() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor(this.name, "")) - .withMessageContaining("Value must not be empty"); + .withMessageContaining("Value must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java index 824f5e911e..8b024eee90 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -98,7 +98,7 @@ class RemoteClientConfigurationTests { @Test void failIfNoSecret() { assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> configure("http://localhost", false)) - .withMessageContaining("required to secure your connection"); + .withMessageContaining("required to secure your connection"); } @Test @@ -115,14 +115,14 @@ class RemoteClientConfigurationTests { void liveReloadDisabled() { configure("spring.devtools.livereload.enabled:false"); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(OptionalLiveReloadServer.class)); + .isThrownBy(() -> this.context.getBean(OptionalLiveReloadServer.class)); } @Test void remoteRestartDisabled() { configure("spring.devtools.remote.restart.enabled:false"); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(ClassPathFileSystemWatcher.class)); + .isThrownBy(() -> this.context.getBean(ClassPathFileSystemWatcher.class)); } private void configure(String... pairs) { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java index 5f24095117..21fe8a4769 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,7 +74,7 @@ class DispatcherFilterTests { @Test void dispatcherMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new DispatcherFilter(null)) - .withMessageContaining("Dispatcher must not be null"); + .withMessageContaining("Dispatcher must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java index 43b883149b..583728b74c 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,13 +63,13 @@ class DispatcherTests { @Test void accessManagerMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new Dispatcher(null, Collections.emptyList())) - .withMessageContaining("AccessManager must not be null"); + .withMessageContaining("AccessManager must not be null"); } @Test void mappersMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new Dispatcher(this.accessManager, null)) - .withMessageContaining("Mappers must not be null"); + .withMessageContaining("Mappers must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java index a55c836139..1a234cad6e 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,25 +54,25 @@ class HttpHeaderAccessManagerTests { @Test void headerNameMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager(null, SECRET)) - .withMessageContaining("HeaderName must not be empty"); + .withMessageContaining("HeaderName must not be empty"); } @Test void headerNameMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager("", SECRET)) - .withMessageContaining("HeaderName must not be empty"); + .withMessageContaining("HeaderName must not be empty"); } @Test void expectedSecretMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager(HEADER, null)) - .withMessageContaining("ExpectedSecret must not be empty"); + .withMessageContaining("ExpectedSecret must not be empty"); } @Test void expectedSecretMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager(HEADER, "")) - .withMessageContaining("ExpectedSecret must not be empty"); + .withMessageContaining("ExpectedSecret must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java index 59ae3a8963..4adef39624 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,7 +56,7 @@ class HttpStatusHandlerTests { @Test void statusMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpStatusHandler(null)) - .withMessageContaining("Status must not be null"); + .withMessageContaining("Status must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java index d4f425bf7e..3cb768a026 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,19 +41,19 @@ class UrlHandlerMapperTests { @Test void requestUriMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new UrlHandlerMapper(null, this.handler)) - .withMessageContaining("URL must not be empty"); + .withMessageContaining("URL must not be empty"); } @Test void requestUriMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new UrlHandlerMapper("", this.handler)) - .withMessageContaining("URL must not be empty"); + .withMessageContaining("URL must not be empty"); } @Test void requestUrlMustStartWithSlash() { assertThatIllegalArgumentException().isThrownBy(() -> new UrlHandlerMapper("tunnel", this.handler)) - .withMessageContaining("URL must start with '/'"); + .withMessageContaining("URL must start with '/'"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java index a7f0eb4b59..f11f99bc67 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -114,8 +114,8 @@ class ChangeableUrlsTests { File classpathJar = new File(this.tempDir, "classpath.jar"); Manifest manifest = new Manifest(); manifest.getMainAttributes().putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0"); - manifest.getMainAttributes().putValue(Attributes.Name.CLASS_PATH.toString(), - StringUtils.arrayToDelimitedString(urls, " ")); + manifest.getMainAttributes() + .putValue(Attributes.Name.CLASS_PATH.toString(), StringUtils.arrayToDelimitedString(urls, " ")); new JarOutputStream(new FileOutputStream(classpathJar), manifest).close(); return classpathJar; } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java index bb0761fbe4..5fe407a427 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ class MainMethodTests { @Test void threadMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new MainMethod(null)) - .withMessageContaining("Thread must not be null"); + .withMessageContaining("Thread must not be null"); } @Test @@ -59,13 +59,13 @@ class MainMethodTests { @Test void missingArgsMainMethod() { assertThatIllegalStateException().isThrownBy(() -> new TestThread(MissingArgs::main).test()) - .withMessageContaining("Unable to find main method"); + .withMessageContaining("Unable to find main method"); } @Test void nonStatic() { assertThatIllegalStateException().isThrownBy(() -> new TestThread(() -> new NonStaticMain().main()).test()) - .withMessageContaining("Unable to find main method"); + .withMessageContaining("Unable to find main method"); } static class TestThread extends Thread { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java index cd19dd5bbd..7c329dd786 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -75,7 +75,7 @@ class RestarterTests { void cantGetInstanceBeforeInitialize() { Restarter.clearInstance(); assertThatIllegalStateException().isThrownBy(Restarter::getInstance) - .withMessageContaining("Restarter has not been initialized"); + .withMessageContaining("Restarter has not been initialized"); } @Test @@ -102,7 +102,7 @@ class RestarterTests { @Test void addUrlsMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> Restarter.getInstance().addUrls(null)) - .withMessageContaining("Urls must not be null"); + .withMessageContaining("Urls must not be null"); } @Test @@ -119,7 +119,7 @@ class RestarterTests { @Test void addClassLoaderFilesMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> Restarter.getInstance().addClassLoaderFiles(null)) - .withMessageContaining("ClassLoaderFiles must not be null"); + .withMessageContaining("ClassLoaderFiles must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java index 982c6318df..db89e0b2d7 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,25 +35,25 @@ class ClassLoaderFileTests { @Test void kindMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(null, null)) - .withMessageContaining("Kind must not be null"); + .withMessageContaining("Kind must not be null"); } @Test void addedContentsMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(Kind.ADDED, null)) - .withMessageContaining("Contents must not be null"); + .withMessageContaining("Contents must not be null"); } @Test void modifiedContentsMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(Kind.MODIFIED, null)) - .withMessageContaining("Contents must not be null"); + .withMessageContaining("Contents must not be null"); } @Test void deletedContentsMustBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(Kind.DELETED, new byte[10])) - .withMessageContaining("Contents must be null"); + .withMessageContaining("Contents must be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java index 65ea8dab2a..e29e109d46 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,13 +43,13 @@ class ClassLoaderFilesTests { @Test void addFileNameMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.files.addFile(null, mock(ClassLoaderFile.class))) - .withMessageContaining("Name must not be null"); + .withMessageContaining("Name must not be null"); } @Test void addFileFileMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.files.addFile("test", null)) - .withMessageContaining("File must not be null"); + .withMessageContaining("File must not be null"); } @Test @@ -153,7 +153,7 @@ class ClassLoaderFilesTests { @Test void classLoaderFilesMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFiles(null)) - .withMessageContaining("ClassLoaderFiles must not be null"); + .withMessageContaining("ClassLoaderFiles must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java index 261b8b452f..d05f9283f7 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -104,14 +104,14 @@ class RestartClassLoaderTests { @Test void parentMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new RestartClassLoader(null, new URL[] {})) - .withMessageContaining("Parent must not be null"); + .withMessageContaining("Parent must not be null"); } @Test void updatedFilesMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new RestartClassLoader(this.parentClassLoader, new URL[] {}, null)) - .withMessageContaining("UpdatedFiles must not be null"); + .isThrownBy(() -> new RestartClassLoader(this.parentClassLoader, new URL[] {}, null)) + .withMessageContaining("UpdatedFiles must not be null"); } @Test @@ -189,7 +189,7 @@ class RestartClassLoaderTests { String name = PACKAGE_PATH + "/Sample.class"; this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.DELETED, null)); assertThatExceptionOfType(ClassNotFoundException.class) - .isThrownBy(() -> Class.forName(PACKAGE + ".Sample", false, this.reloadClassLoader)); + .isThrownBy(() -> Class.forName(PACKAGE + ".Sample", false, this.reloadClassLoader)); } @Test @@ -197,7 +197,7 @@ class RestartClassLoaderTests { String name = PACKAGE_PATH + "/Sample.class"; this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.MODIFIED, new byte[10])); assertThatExceptionOfType(ClassFormatError.class) - .isThrownBy(() -> Class.forName(PACKAGE + ".Sample", false, this.reloadClassLoader)); + .isThrownBy(() -> Class.forName(PACKAGE + ".Sample", false, this.reloadClassLoader)); } @Test @@ -222,13 +222,14 @@ class RestartClassLoaderTests { try (RestartClassLoader restartClassLoader = new RestartClassLoader(ExampleTransactional.class.getClassLoader(), new URL[] { this.sampleJarFile.toURI().toURL() }, this.updatedFiles)) { new ApplicationContextRunner().withClassLoader(restartClassLoader) - .withUserConfiguration(ProxyConfiguration.class).run((context) -> { - assertThat(context).hasNotFailed(); - ExampleTransactional transactional = context.getBean(ExampleTransactional.class); - assertThat(AopUtils.isCglibProxy(transactional)).isTrue(); - assertThat(transactional.getClass().getClassLoader()) - .isEqualTo(ExampleTransactional.class.getClassLoader()); - }); + .withUserConfiguration(ProxyConfiguration.class) + .run((context) -> { + assertThat(context).hasNotFailed(); + ExampleTransactional transactional = context.getBean(ExampleTransactional.class); + assertThat(AopUtils.isCglibProxy(transactional)).isTrue(); + assertThat(transactional.getClass().getClassLoader()) + .isEqualTo(ExampleTransactional.class.getClassLoader()); + }); } } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java index 25c6c7cb4c..8d0ec158fc 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ class HttpRestartServerHandlerTests { @Test void serverMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpRestartServerHandler(null)) - .withMessageContaining("Server must not be null"); + .withMessageContaining("Server must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java index 7c70e4c11f..d63349ab7e 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,13 +64,13 @@ class HttpRestartServerTests { @Test void sourceDirectoryUrlFilterMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpRestartServer((SourceDirectoryUrlFilter) null)) - .withMessageContaining("SourceDirectoryUrlFilter must not be null"); + .withMessageContaining("SourceDirectoryUrlFilter must not be null"); } @Test void restartServerMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpRestartServer((RestartServer) null)) - .withMessageContaining("RestartServer must not be null"); + .withMessageContaining("RestartServer must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java index 2f48b2f3f7..1305a65d48 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,7 @@ class RestartServerTests { @Test void sourceDirectoryUrlFilterMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new RestartServer((SourceDirectoryUrlFilter) null)) - .withMessageContaining("SourceDirectoryUrlFilter must not be null"); + .withMessageContaining("SourceDirectoryUrlFilter must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java index 717e778a43..b1995cda93 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,26 +73,26 @@ class HttpTunnelConnectionTests { @Test void urlMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelConnection(null, this.requestFactory)) - .withMessageContaining("URL must not be empty"); + .withMessageContaining("URL must not be empty"); } @Test void urlMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelConnection("", this.requestFactory)) - .withMessageContaining("URL must not be empty"); + .withMessageContaining("URL must not be empty"); } @Test void urlMustNotBeMalformed() { assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpTunnelConnection("htttttp:///ttest", this.requestFactory)) - .withMessageContaining("Malformed URL 'htttttp:///ttest'"); + .isThrownBy(() -> new HttpTunnelConnection("htttttp:///ttest", this.requestFactory)) + .withMessageContaining("Malformed URL 'htttttp:///ttest'"); } @Test void requestFactoryMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelConnection(this.url, null)) - .withMessageContaining("RequestFactory must not be null"); + .withMessageContaining("RequestFactory must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java index cd920e1796..7968f674a4 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,13 +46,13 @@ class TunnelClientTests { @Test void listenPortMustNotBeNegative() { assertThatIllegalArgumentException().isThrownBy(() -> new TunnelClient(-5, this.tunnelConnection)) - .withMessageContaining("ListenPort must be greater than or equal to 0"); + .withMessageContaining("ListenPort must be greater than or equal to 0"); } @Test void tunnelConnectionMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new TunnelClient(1, null)) - .withMessageContaining("TunnelConnection must not be null"); + .withMessageContaining("TunnelConnection must not be null"); } @Test @@ -73,8 +73,9 @@ class TunnelClientTests { TunnelClient client = new TunnelClient(0, this.tunnelConnection); int port = client.start(); SocketChannel channel = SocketChannel.open(new InetSocketAddress(port)); - Awaitility.await().atMost(Duration.ofSeconds(30)).until(this.tunnelConnection::getOpenedTimes, - (open) -> open == 1); + Awaitility.await() + .atMost(Duration.ofSeconds(30)) + .until(this.tunnelConnection::getOpenedTimes, (open) -> open == 1); channel.close(); client.getServerThread().stopAcceptingConnections(); client.getServerThread().join(2000); @@ -87,8 +88,9 @@ class TunnelClientTests { TunnelClient client = new TunnelClient(0, this.tunnelConnection); int port = client.start(); SocketChannel channel = SocketChannel.open(new InetSocketAddress(port)); - Awaitility.await().atMost(Duration.ofSeconds(30)).until(this.tunnelConnection::getOpenedTimes, - (times) -> times == 1); + Awaitility.await() + .atMost(Duration.ofSeconds(30)) + .until(this.tunnelConnection::getOpenedTimes, (times) -> times == 1); assertThat(this.tunnelConnection.isOpen()).isTrue(); client.stop(); assertThat(this.tunnelConnection.isOpen()).isFalse(); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java index 4d0499c8af..5907ee1845 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ class HttpTunnelPayloadForwarderTests { @Test void targetChannelMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelPayloadForwarder(null)) - .withMessageContaining("TargetChannel must not be null"); + .withMessageContaining("TargetChannel must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java index b53974b267..a65312f6e4 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,13 +51,13 @@ class HttpTunnelPayloadTests { @Test void sequenceMustBePositive() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelPayload(0, ByteBuffer.allocate(1))) - .withMessageContaining("Sequence must be positive"); + .withMessageContaining("Sequence must be positive"); } @Test void dataMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelPayload(1, null)) - .withMessageContaining("Data must not be null"); + .withMessageContaining("Data must not be null"); } @Test @@ -98,7 +98,7 @@ class HttpTunnelPayloadTests { servletRequest.setContent("hello".getBytes()); HttpInputMessage request = new ServletServerHttpRequest(servletRequest); assertThatIllegalStateException().isThrownBy(() -> HttpTunnelPayload.get(request)) - .withMessageContaining("Missing sequence header"); + .withMessageContaining("Missing sequence header"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java index 50f8907fa8..b046248393 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ class HttpTunnelServerHandlerTests { @Test void serverMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelServerHandler(null)) - .withMessageContaining("Server must not be null"); + .withMessageContaining("Server must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java index 2f1304e3f6..a4f64d07f5 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -99,7 +99,7 @@ class HttpTunnelServerTests { @Test void serverConnectionIsRequired() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelServer(null)) - .withMessageContaining("ServerConnection must not be null"); + .withMessageContaining("ServerConnection must not be null"); } @Test @@ -121,7 +121,7 @@ class HttpTunnelServerTests { @Test void longPollTimeoutMustBePositiveValue() { assertThatIllegalArgumentException().isThrownBy(() -> this.server.setLongPollTimeout(0)) - .withMessageContaining("LongPollTimeout must be a positive value"); + .withMessageContaining("LongPollTimeout must be a positive value"); } @Test @@ -239,12 +239,14 @@ class HttpTunnelServerTests { this.server.setLongPollTimeout(100); MockHttpConnection h1 = new MockHttpConnection(); this.server.handle(h1); - Awaitility.await().atMost(Duration.ofSeconds(30)).until(h1.getServletResponse()::getStatus, - (status) -> status == 204); + Awaitility.await() + .atMost(Duration.ofSeconds(30)) + .until(h1.getServletResponse()::getStatus, (status) -> status == 204); MockHttpConnection h2 = new MockHttpConnection(); this.server.handle(h2); - Awaitility.await().atMost(Duration.ofSeconds(30)).until(h2.getServletResponse()::getStatus, - (status) -> status == 204); + Awaitility.await() + .atMost(Duration.ofSeconds(30)) + .until(h2.getServletResponse()::getStatus, (status) -> status == 204); this.serverChannel.disconnect(); this.server.getServerThread().join(JOIN_TIMEOUT); } @@ -264,7 +266,7 @@ class HttpTunnelServerTests { @Test void disconnectTimeoutMustBePositive() { assertThatIllegalArgumentException().isThrownBy(() -> this.server.setDisconnectTimeout(0)) - .withMessageContaining("DisconnectTimeout must be a positive value"); + .withMessageContaining("DisconnectTimeout must be a positive value"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java index 07b1e75b29..d6a3e951db 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,11 +76,11 @@ class SocketTargetServerConnectionTests { ByteChannel channel = this.connection.open(10); long startTime = System.currentTimeMillis(); assertThatExceptionOfType(SocketTimeoutException.class).isThrownBy(() -> channel.read(ByteBuffer.allocate(5))) - .satisfies((ex) -> { - long runTime = System.currentTimeMillis() - startTime; - assertThat(runTime).isGreaterThanOrEqualTo(10L); - assertThat(runTime).isLessThan(10000L); - }); + .satisfies((ex) -> { + long runTime = System.currentTimeMillis() - startTime; + assertThat(runTime).isGreaterThanOrEqualTo(10L); + assertThat(runTime).isLessThan(10000L); + }); } static class MockServer { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java index bba395acac..961074e8e3 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ class StaticPortProviderTests { @Test void portMustBePositive() { assertThatIllegalArgumentException().isThrownBy(() -> new StaticPortProvider(0)) - .withMessageContaining("Port must be positive"); + .withMessageContaining("Port must be positive"); } @Test diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/data/nosql/neo4j/connecting/MyBean.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/data/nosql/neo4j/connecting/MyBean.java index 1fa1035b27..ce2fcf3b93 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/data/nosql/neo4j/connecting/MyBean.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/data/nosql/neo4j/connecting/MyBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,10 +34,13 @@ public class MyBean { // @fold:on // ... public String someMethod(String message) { try (Session session = this.driver.session()) { - return session.writeTransaction((transaction) -> transaction - .run("CREATE (a:Greeting) SET a.message = $message RETURN a.message + ', from node ' + id(a)", - Values.parameters("message", message)) - .single().get(0).asString()); + return session.writeTransaction( + (transaction) -> transaction + .run("CREATE (a:Greeting) SET a.message = $message RETURN a.message + ', from node ' + id(a)", + Values.parameters("message", message)) + .single() + .get(0) + .asString()); } } // @fold:off diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/developingautoconfiguration/testing/MyServiceAutoConfigurationTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/developingautoconfiguration/testing/MyServiceAutoConfigurationTests.java index 03269ecf55..ca771b29fa 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/developingautoconfiguration/testing/MyServiceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/developingautoconfiguration/testing/MyServiceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ class MyServiceAutoConfigurationTests { // tag::runner[] private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MyServiceAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MyServiceAutoConfiguration.class)); // end::runner[] @@ -48,7 +48,7 @@ class MyServiceAutoConfigurationTests { @Test void serviceIsIgnoredIfLibraryIsNotPresent() { this.contextRunner.withClassLoader(new FilteredClassLoader(MyService.class)) - .run((context) -> assertThat(context).doesNotHaveBean("myService")); + .run((context) -> assertThat(context).doesNotHaveBean("myService")); } // end::test-classloader[] diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/jsontests/MyJsonAssertJTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/jsontests/MyJsonAssertJTests.java index 3f108b5205..354009771c 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/jsontests/MyJsonAssertJTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/jsontests/MyJsonAssertJTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ class MyJsonAssertJTests { void someTest() throws Exception { SomeObject value = new SomeObject(0.152f); assertThat(this.json.write(value)).extractingJsonPathNumberValue("@.test.numberValue") - .satisfies((number) -> assertThat(number.floatValue()).isCloseTo(0.15f, within(0.01f))); + .satisfies((number) -> assertThat(number.floatValue()).isCloseTo(0.15f, within(0.01f))); } // end::code[] diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/springgraphqltests/GraphQlIntegrationTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/springgraphqltests/GraphQlIntegrationTests.java index 2ff2a08ea6..5e07dd2c85 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/springgraphqltests/GraphQlIntegrationTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/springgraphqltests/GraphQlIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,11 +30,13 @@ class GraphQlIntegrationTests { @Test void shouldGreetWithSpecificName(@Autowired HttpGraphQlTester graphQlTester) { HttpGraphQlTester authenticatedTester = graphQlTester.mutate() - .webTestClient( - (client) -> client.defaultHeaders((headers) -> headers.setBasicAuth("admin", "ilovespring"))) - .build(); - authenticatedTester.document("{ greeting(name: \"Alice\") } ").execute().path("greeting").entity(String.class) - .isEqualTo("Hello, Alice!"); + .webTestClient((client) -> client.defaultHeaders((headers) -> headers.setBasicAuth("admin", "ilovespring"))) + .build(); + authenticatedTester.document("{ greeting(name: \"Alice\") } ") + .execute() + .path("greeting") + .entity(String.class) + .isEqualTo("Hello, Alice!"); } } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/springgraphqltests/GreetingControllerTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/springgraphqltests/GreetingControllerTests.java index 951bd126d0..a1de2f6e05 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/springgraphqltests/GreetingControllerTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/springgraphqltests/GreetingControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,14 +31,20 @@ class GreetingControllerTests { @Test void shouldGreetWithSpecificName() { - this.graphQlTester.document("{ greeting(name: \"Alice\") } ").execute().path("greeting").entity(String.class) - .isEqualTo("Hello, Alice!"); + this.graphQlTester.document("{ greeting(name: \"Alice\") } ") + .execute() + .path("greeting") + .entity(String.class) + .isEqualTo("Hello, Alice!"); } @Test void shouldGreetWithDefaultName() { - this.graphQlTester.document("{ greeting } ").execute().path("greeting").entity(String.class) - .isEqualTo("Hello, Spring!"); + this.graphQlTester.document("{ greeting } ") + .execute() + .path("greeting") + .entity(String.class) + .isEqualTo("Hello, Spring!"); } } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/utilities/testresttemplate/MySpringBootTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/utilities/testresttemplate/MySpringBootTests.java index f4dc7bb957..77847fdf40 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/utilities/testresttemplate/MySpringBootTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/utilities/testresttemplate/MySpringBootTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,7 @@ class MySpringBootTests { @Bean RestTemplateBuilder restTemplateBuilder() { return new RestTemplateBuilder().setConnectTimeout(Duration.ofSeconds(1)) - .setReadTimeout(Duration.ofSeconds(1)); + .setReadTimeout(Duration.ofSeconds(1)); } } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/howto/webserver/usetomcatlegacycookieprocessor/MyLegacyCookieProcessorConfiguration.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/howto/webserver/usetomcatlegacycookieprocessor/MyLegacyCookieProcessorConfiguration.java index fb1702f99d..c3cd7c39be 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/howto/webserver/usetomcatlegacycookieprocessor/MyLegacyCookieProcessorConfiguration.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/howto/webserver/usetomcatlegacycookieprocessor/MyLegacyCookieProcessorConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,7 @@ public class MyLegacyCookieProcessorConfiguration { @Bean public WebServerFactoryCustomizer cookieProcessorCustomizer() { return (factory) -> factory - .addContextCustomizers((context) -> context.setCookieProcessor(new LegacyCookieProcessor())); + .addContextCustomizers((context) -> context.setCookieProcessor(new LegacyCookieProcessor())); } } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/io/restclient/resttemplate/customization/MyRestTemplateBuilderConfiguration.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/io/restclient/resttemplate/customization/MyRestTemplateBuilderConfiguration.java index e271157fae..7a13e2df9b 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/io/restclient/resttemplate/customization/MyRestTemplateBuilderConfiguration.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/io/restclient/resttemplate/customization/MyRestTemplateBuilderConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,9 @@ public class MyRestTemplateBuilderConfiguration { @Bean public RestTemplateBuilder restTemplateBuilder(RestTemplateBuilderConfigurer configurer) { - return configurer.configure(new RestTemplateBuilder()).setConnectTimeout(Duration.ofSeconds(5)) - .setReadTimeout(Duration.ofSeconds(2)); + return configurer.configure(new RestTemplateBuilder()) + .setConnectTimeout(Duration.ofSeconds(5)) + .setReadTimeout(Duration.ofSeconds(2)); } } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/graphql/transports/rsocket/RSocketGraphQlClientExample.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/graphql/transports/rsocket/RSocketGraphQlClientExample.java index 9df5ff0c53..8e5a25279a 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/graphql/transports/rsocket/RSocketGraphQlClientExample.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/graphql/transports/rsocket/RSocketGraphQlClientExample.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,8 @@ public class RSocketGraphQlClientExample { public void rsocketOverTcp() { // tag::request[] Mono book = this.graphQlClient.document("{ bookById(id: \"book-1\"){ id name pageCount author } }") - .retrieve("bookById").toEntity(Book.class); + .retrieve("bookById") + .toEntity(Book.class); // end::request[] book.block(Duration.ofSeconds(5)); } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/security/saml2/relyingparty/MySamlRelyingPartyConfiguration.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/security/saml2/relyingparty/MySamlRelyingPartyConfiguration.java index 6cd3bc68f3..e47cd31863 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/security/saml2/relyingparty/MySamlRelyingPartyConfiguration.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/security/saml2/relyingparty/MySamlRelyingPartyConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,7 @@ public class MySamlRelyingPartyConfiguration { http.authorizeRequests().anyRequest().authenticated(); http.saml2Login(); http.saml2Logout((saml2) -> saml2.logoutRequest((request) -> request.logoutUrl("/SLOService.saml2")) - .logoutResponse((response) -> response.logoutUrl("/SLOService.saml2"))); + .logoutResponse((response) -> response.logoutUrl("/SLOService.saml2"))); return http.build(); } diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/conversion/durations/constructorbinding/MyPropertiesTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/conversion/durations/constructorbinding/MyPropertiesTests.java index 6e3d9c6a3c..6740b9d9b6 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/conversion/durations/constructorbinding/MyPropertiesTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/conversion/durations/constructorbinding/MyPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,33 +36,33 @@ import static org.assertj.core.api.Assertions.assertThat; class MyPropertiesTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(Config.class); + .withUserConfiguration(Config.class); @Test void bindWithDefaultUnit() { this.contextRunner.withPropertyValues("my.session-timeout=40", "my.read-timeout=5000") - .run(assertBinding((properties) -> { - assertThat(properties.getSessionTimeout()).hasSeconds(40); - assertThat(properties.getReadTimeout()).hasMillis(5000); - })); + .run(assertBinding((properties) -> { + assertThat(properties.getSessionTimeout()).hasSeconds(40); + assertThat(properties.getReadTimeout()).hasMillis(5000); + })); } @Test void bindWithExplicitUnit() { this.contextRunner.withPropertyValues("my.session-timeout=1h", "my.read-timeout=5s") - .run(assertBinding((properties) -> { - assertThat(properties.getSessionTimeout()).hasMinutes(60); - assertThat(properties.getReadTimeout()).hasMillis(5000); - })); + .run(assertBinding((properties) -> { + assertThat(properties.getSessionTimeout()).hasMinutes(60); + assertThat(properties.getReadTimeout()).hasMillis(5000); + })); } @Test void bindWithIso8601Format() { this.contextRunner.withPropertyValues("my.session-timeout=PT15S", "my.read-timeout=PT0.5S") - .run(assertBinding((properties) -> { - assertThat(properties.getSessionTimeout()).hasSeconds(15); - assertThat(properties.getReadTimeout()).hasMillis(500); - })); + .run(assertBinding((properties) -> { + assertThat(properties.getSessionTimeout()).hasSeconds(15); + assertThat(properties.getReadTimeout()).hasMillis(500); + })); } private ContextConsumer assertBinding(Consumer properties) { diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/conversion/durations/javabeanbinding/MyPropertiesTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/conversion/durations/javabeanbinding/MyPropertiesTests.java index d5652489ff..cd1540d0ba 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/conversion/durations/javabeanbinding/MyPropertiesTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/conversion/durations/javabeanbinding/MyPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,33 +36,33 @@ import static org.assertj.core.api.Assertions.assertThat; class MyPropertiesTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(Config.class); + .withUserConfiguration(Config.class); @Test void bindWithDefaultUnit() { this.contextRunner.withPropertyValues("my.session-timeout=40", "my.read-timeout=5000") - .run(assertBinding((properties) -> { - assertThat(properties.getSessionTimeout()).hasSeconds(40); - assertThat(properties.getReadTimeout()).hasMillis(5000); - })); + .run(assertBinding((properties) -> { + assertThat(properties.getSessionTimeout()).hasSeconds(40); + assertThat(properties.getReadTimeout()).hasMillis(5000); + })); } @Test void bindWithExplicitUnit() { this.contextRunner.withPropertyValues("my.session-timeout=1h", "my.read-timeout=5s") - .run(assertBinding((properties) -> { - assertThat(properties.getSessionTimeout()).hasMinutes(60); - assertThat(properties.getReadTimeout()).hasMillis(5000); - })); + .run(assertBinding((properties) -> { + assertThat(properties.getSessionTimeout()).hasMinutes(60); + assertThat(properties.getReadTimeout()).hasMillis(5000); + })); } @Test void bindWithIso8601Format() { this.contextRunner.withPropertyValues("my.session-timeout=PT15S", "my.read-timeout=PT0.5S") - .run(assertBinding((properties) -> { - assertThat(properties.getSessionTimeout()).hasSeconds(15); - assertThat(properties.getReadTimeout()).hasMillis(500); - })); + .run(assertBinding((properties) -> { + assertThat(properties.getSessionTimeout()).hasSeconds(15); + assertThat(properties.getReadTimeout()).hasMillis(500); + })); } private ContextConsumer assertBinding(Consumer properties) { diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/howto/webserver/usetomcatlegacycookieprocessor/MyLegacyCookieProcessorConfigurationTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/howto/webserver/usetomcatlegacycookieprocessor/MyLegacyCookieProcessorConfigurationTests.java index 29fde8b168..f90be262ed 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/howto/webserver/usetomcatlegacycookieprocessor/MyLegacyCookieProcessorConfigurationTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/howto/webserver/usetomcatlegacycookieprocessor/MyLegacyCookieProcessorConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,9 +40,11 @@ class MyLegacyCookieProcessorConfigurationTests { @Test void cookieProcessorIsCustomized() { ServletWebServerApplicationContext applicationContext = (ServletWebServerApplicationContext) new SpringApplication( - TestConfiguration.class, MyLegacyCookieProcessorConfiguration.class).run(); - Context context = (Context) ((TomcatWebServer) applicationContext.getWebServer()).getTomcat().getHost() - .findChildren()[0]; + TestConfiguration.class, MyLegacyCookieProcessorConfiguration.class) + .run(); + Context context = (Context) ((TomcatWebServer) applicationContext.getWebServer()).getTomcat() + .getHost() + .findChildren()[0]; assertThat(context.getCookieProcessor()).isInstanceOf(LegacyCookieProcessor.class); } 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..e16594476e 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -78,7 +78,7 @@ public class PropertiesMigrationListener implements ApplicationListener> getContent( Function> extractor) { - return this.content.entrySet().stream().filter((entry) -> !extractor.apply(entry.getValue()).isEmpty()).collect( - Collectors.toMap(Map.Entry::getKey, (entry) -> new ArrayList<>(extractor.apply(entry.getValue())))); + return this.content.entrySet() + .stream() + .filter((entry) -> !extractor.apply(entry.getValue()).isEmpty()) + .collect( + Collectors.toMap(Map.Entry::getKey, (entry) -> new ArrayList<>(extractor.apply(entry.getValue())))); } private void append(StringBuilder report, Map> content) { @@ -118,8 +121,9 @@ class PropertiesMigrationReport { } List getUnsupported() { - return this.properties.stream().filter((property) -> !property.isCompatibleType()) - .collect(Collectors.toList()); + return this.properties.stream() + .filter((property) -> !property.isCompatibleType()) + .collect(Collectors.toList()); } } diff --git a/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporter.java b/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporter.java index 0c608d1939..8e495f8eb1 100644 --- a/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporter.java +++ b/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporter.java @@ -80,8 +80,9 @@ class PropertiesMigrationReporter { private PropertySource mapPropertiesWithReplacement(PropertiesMigrationReport report, String name, List properties) { report.add(name, properties); - List renamed = properties.stream().filter(PropertyMigration::isCompatibleType) - .collect(Collectors.toList()); + List renamed = properties.stream() + .filter(PropertyMigration::isCompatibleType) + .collect(Collectors.toList()); if (renamed.isEmpty()) { return null; } @@ -103,8 +104,10 @@ class PropertiesMigrationReporter { private Map> getMatchingProperties( Predicate filter) { MultiValueMap result = new LinkedMultiValueMap<>(); - List candidates = this.allProperties.values().stream().filter(filter) - .collect(Collectors.toList()); + List candidates = this.allProperties.values() + .stream() + .filter(filter) + .collect(Collectors.toList()); getPropertySourcesAsMap().forEach((propertySourceName, propertySource) -> candidates.forEach((metadata) -> { ConfigurationPropertyName metadataName = ConfigurationPropertyName.isValid(metadata.getId()) ? ConfigurationPropertyName.of(metadata.getId()) @@ -118,12 +121,13 @@ class PropertiesMigrationReporter { // Prefix match for maps if (isMapType(metadata) && propertySource instanceof IterableConfigurationPropertySource) { IterableConfigurationPropertySource iterableSource = (IterableConfigurationPropertySource) propertySource; - iterableSource.stream().filter(metadataName::isAncestorOf).map(propertySource::getConfigurationProperty) - .forEach((property) -> { - ConfigurationMetadataProperty replacement = determineReplacementMetadata(metadata); - result.add(propertySourceName, - new PropertyMigration(property, metadata, replacement, true)); - }); + iterableSource.stream() + .filter(metadataName::isAncestorOf) + .map(propertySource::getConfigurationProperty) + .forEach((property) -> { + ConfigurationMetadataProperty replacement = determineReplacementMetadata(metadata); + result.add(propertySourceName, new PropertyMigration(property, metadata, replacement, true)); + }); } })); return result; diff --git a/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertyMigration.java b/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertyMigration.java index e37ceabad0..4dc9043ad4 100644 --- a/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertyMigration.java +++ b/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertyMigration.java @@ -38,7 +38,7 @@ import org.springframework.util.StringUtils; class PropertyMigration { public static final Comparator COMPARATOR = Comparator - .comparing((property) -> property.getMetadata().getId()); + .comparing((property) -> property.getMetadata().getId()); private final ConfigurationProperty property; diff --git a/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListenerTests.java b/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListenerTests.java index 6bad1ac9bb..3e8dd69ef0 100644 --- a/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListenerTests.java +++ b/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,9 +48,10 @@ class PropertiesMigrationListenerTests { @Test void sampleReport(CapturedOutput output) { this.context = createSampleApplication().run("--logging.file=test.log"); - assertThat(output).contains("commandLineArgs").contains("logging.file.name") - .contains("Each configuration key has been temporarily mapped") - .doesNotContain("Please refer to the release notes"); + assertThat(output).contains("commandLineArgs") + .contains("logging.file.name") + .contains("Each configuration key has been temporarily mapped") + .doesNotContain("Please refer to the release notes"); } private SpringApplication createSampleApplication() { diff --git a/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporterTests.java b/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporterTests.java index 44382f77ca..b6e5135128 100644 --- a/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporterTests.java +++ b/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporterTests.java @@ -90,7 +90,7 @@ class PropertiesMigrationReporterTests { @Test void errorReport() throws IOException { this.environment.getPropertySources() - .addFirst(loadPropertySource("test1", "config/config-warnings.properties")); + .addFirst(loadPropertySource("test1", "config/config-warnings.properties")); this.environment.getPropertySources().addFirst(loadPropertySource("test2", "config/config-error.properties")); String report = createErrorReport(loadRepository("metadata/sample-metadata.json")); assertThat(report).isNotNull(); @@ -102,7 +102,7 @@ class PropertiesMigrationReporterTests { @Test void errorReportNoReplacement() throws IOException { this.environment.getPropertySources() - .addFirst(loadPropertySource("first", "config/config-error-no-replacement.properties")); + .addFirst(loadPropertySource("first", "config/config-error-no-replacement.properties")); this.environment.getPropertySources().addFirst(loadPropertySource("second", "config/config-error.properties")); String report = createErrorReport(loadRepository("metadata/sample-metadata.json")); assertThat(report).isNotNull(); @@ -134,7 +134,7 @@ class PropertiesMigrationReporterTests { @Test void reasonIsProvidedIfPropertyCouldNotBeRenamed() throws IOException { this.environment.getPropertySources() - .addFirst(loadPropertySource("test", "config/config-error-no-compatible-type.properties")); + .addFirst(loadPropertySource("test", "config/config-error-no-compatible-type.properties")); String report = createErrorReport(loadRepository("metadata/type-conversion-metadata.json")); assertThat(report).isNotNull(); assertThat(report).containsSubsequence("Property source 'test'", "wrong.inconvertible", "Line: 1", @@ -144,7 +144,7 @@ class PropertiesMigrationReporterTests { @Test void invalidReplacementHandled() throws IOException { this.environment.getPropertySources() - .addFirst(loadPropertySource("first", "config/config-error-invalid-replacement.properties")); + .addFirst(loadPropertySource("first", "config/config-error-invalid-replacement.properties")); String report = createErrorReport(loadRepository("metadata/sample-metadata-invalid-replacement.json")); assertThat(report).isNotNull(); assertThat(report).containsSubsequence("Property source 'first'", "deprecated.six.test", "Line: 1", "Reason", @@ -155,7 +155,7 @@ class PropertiesMigrationReporterTests { @Test void invalidNameHandledGracefully() { this.environment.getPropertySources() - .addFirst(new MapPropertySource("first", Collections.singletonMap("invalid.property-name", "value"))); + .addFirst(new MapPropertySource("first", Collections.singletonMap("invalid.property-name", "value"))); String report = createWarningReport(loadRepository("metadata/sample-metadata-invalid-name.json")); assertThat(report).isNotNull(); assertThat(report).contains("Key: invalid.propertyname").contains("Replacement: valid.property-name"); @@ -163,42 +163,46 @@ class PropertiesMigrationReporterTests { @Test void mapPropertiesDeprecatedNoReplacement() throws IOException { - this.environment.getPropertySources().addFirst( - new MapPropertySource("first", Collections.singletonMap("custom.map-no-replacement.key", "value"))); + this.environment.getPropertySources() + .addFirst( + new MapPropertySource("first", Collections.singletonMap("custom.map-no-replacement.key", "value"))); String report = createErrorReport(loadRepository("metadata/sample-metadata.json")); assertThat(report).isNotNull(); assertThat(report).contains("Key: custom.map-no-replacement.key") - .contains("Reason: This is no longer supported."); + .contains("Reason: This is no longer supported."); } @Test void mapPropertiesDeprecatedWithReplacement() throws IOException { - this.environment.getPropertySources().addFirst( - new MapPropertySource("first", Collections.singletonMap("custom.map-with-replacement.key", "value"))); + this.environment.getPropertySources() + .addFirst(new MapPropertySource("first", + Collections.singletonMap("custom.map-with-replacement.key", "value"))); String report = createWarningReport(loadRepository("metadata/sample-metadata.json")); assertThat(report).isNotNull(); assertThat(report).contains("Key: custom.map-with-replacement.key") - .contains("Replacement: custom.the-map-replacement.key"); + .contains("Replacement: custom.the-map-replacement.key"); } @Test void mapPropertiesDeprecatedWithReplacementRelaxedBindingUnderscore() { - this.environment.getPropertySources().addFirst( - new MapPropertySource("first", Collections.singletonMap("custom.map_with_replacement.key", "value"))); + this.environment.getPropertySources() + .addFirst(new MapPropertySource("first", + Collections.singletonMap("custom.map_with_replacement.key", "value"))); String report = createWarningReport(loadRepository("metadata/sample-metadata.json")); assertThat(report).isNotNull(); assertThat(report).contains("Key: custom.mapwithreplacement.key") - .contains("Replacement: custom.the-map-replacement.key"); + .contains("Replacement: custom.the-map-replacement.key"); } @Test void mapPropertiesDeprecatedWithReplacementRelaxedBindingCamelCase() { - this.environment.getPropertySources().addFirst( - new MapPropertySource("first", Collections.singletonMap("custom.MapWithReplacement.key", "value"))); + this.environment.getPropertySources() + .addFirst( + new MapPropertySource("first", Collections.singletonMap("custom.MapWithReplacement.key", "value"))); String report = createWarningReport(loadRepository("metadata/sample-metadata.json")); assertThat(report).isNotNull(); assertThat(report).contains("Key: custom.mapwithreplacement.key") - .contains("Replacement: custom.the-map-replacement.key"); + .contains("Replacement: custom.the-map-replacement.key"); } private List mapToNames(PropertySources sources) { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListener.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListener.java index 84fc4397fe..2a9f6afdd9 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListener.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ public class SpringBootDependencyInjectionTestExecutionListener extends Dependen ApplicationContext context = testContext.getApplicationContext(); if (context instanceof ConfigurableApplicationContext) { ConditionEvaluationReport report = ConditionEvaluationReport - .get(((ConfigurableApplicationContext) context).getBeanFactory()); + .get(((ConfigurableApplicationContext) context).getBeanFactory()); System.err.println(new ConditionEvaluationReportMessage(report)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/actuate/metrics/MetricsExportContextCustomizerFactory.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/actuate/metrics/MetricsExportContextCustomizerFactory.java index 01cf079e9b..e8ffe4a979 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/actuate/metrics/MetricsExportContextCustomizerFactory.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/actuate/metrics/MetricsExportContextCustomizerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,9 @@ class MetricsExportContextCustomizerFactory implements ContextCustomizerFactory @Override public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedContextConfiguration) { - TestPropertyValues.of("management.metrics.export.defaults.enabled=false", - "management.metrics.export.simple.enabled=true").applyTo(context); + TestPropertyValues + .of("management.metrics.export.defaults.enabled=false", "management.metrics.export.simple.enabled=true") + .applyTo(context); } @Override diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/cassandra/DataCassandraTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/cassandra/DataCassandraTestContextBootstrapper.java index c0fc1a76c2..4238e64b5d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/cassandra/DataCassandraTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/cassandra/DataCassandraTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,10 @@ class DataCassandraTestContextBootstrapper extends SpringBootTestContextBootstra @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataCassandraTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataCassandraTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestContextBootstrapper.java index f25b62de58..86fb4c2dc6 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,10 @@ class DataCouchbaseTestContextBootstrapper extends SpringBootTestContextBootstra @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataCouchbaseTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataCouchbaseTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestContextBootstrapper.java index 77b276c969..e23e629505 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,10 @@ class DataElasticsearchTestContextBootstrapper extends SpringBootTestContextBoot @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataElasticsearchTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataElasticsearchTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestContextBootstrapper.java index 691403e1cb..9c99f9b296 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,10 @@ class DataJdbcTestContextBootstrapper extends SpringBootTestContextBootstrapper @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataJdbcTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataJdbcTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestContextBootstrapper.java index 66a74aaf8b..827c313c20 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,10 @@ class DataLdapTestContextBootstrapper extends SpringBootTestContextBootstrapper @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataLdapTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataLdapTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestContextBootstrapper.java index 1c63e98ba1..6a973d302d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,10 @@ class DataMongoTestContextBootstrapper extends SpringBootTestContextBootstrapper @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataMongoTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataMongoTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestContextBootstrapper.java index 0a958a7586..85bc9639d5 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,10 @@ class DataNeo4jTestContextBootstrapper extends SpringBootTestContextBootstrapper @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataNeo4jTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataNeo4jTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/r2dbc/DataR2dbcTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/r2dbc/DataR2dbcTestContextBootstrapper.java index 3da527a338..26e1308e98 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/r2dbc/DataR2dbcTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/r2dbc/DataR2dbcTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,10 @@ class DataR2dbcTestContextBootstrapper extends SpringBootTestContextBootstrapper @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataR2dbcTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataR2dbcTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestContextBootstrapper.java index 98a9dec100..a5530b4bea 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,10 @@ class DataRedisTestContextBootstrapper extends SpringBootTestContextBootstrapper @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataRedisTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataRedisTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/StandardAnnotationCustomizableTypeExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/StandardAnnotationCustomizableTypeExcludeFilter.java index 9ada5057cc..a80cf042cb 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/StandardAnnotationCustomizableTypeExcludeFilter.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/StandardAnnotationCustomizableTypeExcludeFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ public abstract class StandardAnnotationCustomizableTypeExcludeFilter testClass) { this.annotation = MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) - .get(getAnnotationType()); + .get(getAnnotationType()); } protected final MergedAnnotation getAnnotation() { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactory.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactory.java index e0c748fd49..791d9b477b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactory.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ class TypeExcludeFiltersContextCustomizerFactory implements ContextCustomizerFac public ContextCustomizer createContextCustomizer(Class testClass, List configurationAttributes) { AnnotationDescriptor descriptor = TestContextAnnotationUtils - .findAnnotationDescriptor(testClass, TypeExcludeFilters.class); + .findAnnotationDescriptor(testClass, TypeExcludeFilters.class); Class[] filterClasses = (descriptor != null) ? descriptor.getAnnotation().value() : NO_FILTERS; if (ObjectUtils.isEmpty(filterClasses)) { return null; diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/graphql/GraphQlTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/graphql/GraphQlTestContextBootstrapper.java index 5e05495cde..4f8971fe09 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/graphql/GraphQlTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/graphql/GraphQlTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2021 the original author or authors. + * Copyright 2020-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,9 @@ class GraphQlTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override protected String[] getProperties(Class testClass) { return MergedAnnotations.from(testClass, MergedAnnotations.SearchStrategy.INHERITED_ANNOTATIONS) - .get(GraphQlTest.class).getValue("properties", String[].class).orElse(null); + .get(GraphQlTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestContextBootstrapper.java index d91547ab4e..a2eebe37d6 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,10 @@ class JdbcTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(JdbcTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(JdbcTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfiguration.java index 8ba0d3ce9a..aea1e4228a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -177,7 +177,7 @@ public class TestDatabaseAutoConfiguration { source.put("spring.datasource.schema-username", ""); source.put("spring.sql.init.username", ""); ((ConfigurableEnvironment) environment).getPropertySources() - .addFirst(new MapPropertySource("testDatabase", source)); + .addFirst(new MapPropertySource("testDatabase", source)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestContextBootstrapper.java index 24b9849500..770bdd79b0 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,10 @@ class JooqTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(JooqTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(JooqTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestContextBootstrapper.java index 6dc84ac874..55a2119879 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,10 @@ class JsonTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(JsonTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(JsonTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestContextBootstrapper.java index 3d30008d75..0fdbbb9c37 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,10 @@ class DataJpaTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataJpaTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataJpaTest.class) + .getValue("properties", String[].class) + .orElse(null); } } 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..8f553cd97a 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,18 +64,20 @@ public class AnnotationsPropertySource extends EnumerablePropertySource } private void getProperties(Class source, Map properties) { - MergedAnnotations.from(source, SearchStrategy.SUPERCLASS).stream() - .filter(MergedAnnotationPredicates.unique(MergedAnnotation::getType)).forEach((annotation) -> { - Class type = annotation.getType(); - MergedAnnotation typeMapping = MergedAnnotations.from(type).get(PropertyMapping.class, - MergedAnnotation::isDirectlyPresent); - String prefix = typeMapping.getValue(MergedAnnotation.VALUE, String.class).orElse(""); - SkipPropertyMapping defaultSkip = typeMapping.getValue("skip", SkipPropertyMapping.class) - .orElse(SkipPropertyMapping.YES); - for (Method attribute : type.getDeclaredMethods()) { - collectProperties(prefix, defaultSkip, annotation, attribute, properties); - } - }); + MergedAnnotations.from(source, SearchStrategy.SUPERCLASS) + .stream() + .filter(MergedAnnotationPredicates.unique(MergedAnnotation::getType)) + .forEach((annotation) -> { + Class type = annotation.getType(); + MergedAnnotation typeMapping = MergedAnnotations.from(type) + .get(PropertyMapping.class, MergedAnnotation::isDirectlyPresent); + String prefix = typeMapping.getValue(MergedAnnotation.VALUE, String.class).orElse(""); + SkipPropertyMapping defaultSkip = typeMapping.getValue("skip", SkipPropertyMapping.class) + .orElse(SkipPropertyMapping.YES); + for (Method attribute : type.getDeclaredMethods()) { + collectProperties(prefix, defaultSkip, annotation, attribute, properties); + } + }); if (TestContextAnnotationUtils.searchEnclosingClass(source)) { getProperties(source.getEnclosingClass(), properties); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizer.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizer.java index 03a5911fb0..2dde81b33d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizer.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,8 +51,9 @@ class PropertyMappingContextCustomizer implements ContextCustomizer { if (!this.propertySource.isEmpty()) { context.getEnvironment().getPropertySources().addFirst(this.propertySource); } - context.getBeanFactory().registerSingleton(PropertyMappingCheckBeanPostProcessor.class.getName(), - new PropertyMappingCheckBeanPostProcessor()); + context.getBeanFactory() + .registerSingleton(PropertyMappingCheckBeanPostProcessor.class.getName(), + new PropertyMappingCheckBeanPostProcessor()); } @Override @@ -76,10 +77,12 @@ class PropertyMappingContextCustomizer implements ContextCustomizer { public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { Class beanClass = bean.getClass(); MergedAnnotations annotations = MergedAnnotations.from(beanClass, SearchStrategy.SUPERCLASS); - Set> components = annotations.stream(Component.class).map(this::getRoot) - .collect(Collectors.toSet()); - Set> propertyMappings = annotations.stream(PropertyMapping.class).map(this::getRoot) - .collect(Collectors.toSet()); + Set> components = annotations.stream(Component.class) + .map(this::getRoot) + .collect(Collectors.toSet()); + Set> propertyMappings = annotations.stream(PropertyMapping.class) + .map(this::getRoot) + .collect(Collectors.toSet()); if (!components.isEmpty() && !propertyMappings.isEmpty()) { throw new IllegalStateException("The @PropertyMapping " + getAnnotationsDescription(propertyMappings) + " cannot be used in combination with the @Component " diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfiguration.java index a43aa8f56f..c24918a205 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,9 +62,9 @@ public class RestDocsAutoConfiguration { ObjectProvider configurationCustomizers, RestDocumentationContextProvider contextProvider) { MockMvcRestDocumentationConfigurer configurer = MockMvcRestDocumentation - .documentationConfiguration(contextProvider); + .documentationConfiguration(contextProvider); configurationCustomizers.orderedStream() - .forEach((configurationCustomizer) -> configurationCustomizer.customize(configurer)); + .forEach((configurationCustomizer) -> configurationCustomizer.customize(configurer)); return configurer; } @@ -88,9 +88,9 @@ public class RestDocsAutoConfiguration { ObjectProvider configurationCustomizers, RestDocumentationContextProvider contextProvider) { RestAssuredRestDocumentationConfigurer configurer = RestAssuredRestDocumentation - .documentationConfiguration(contextProvider); + .documentationConfiguration(contextProvider); configurationCustomizers.orderedStream() - .forEach((configurationCustomizer) -> configurationCustomizer.customize(configurer)); + .forEach((configurationCustomizer) -> configurationCustomizer.customize(configurer)); return new RequestSpecBuilder().addFilter(configurer).build(); } @@ -114,9 +114,9 @@ public class RestDocsAutoConfiguration { ObjectProvider configurationCustomizers, RestDocumentationContextProvider contextProvider) { WebTestClientRestDocumentationConfigurer configurer = WebTestClientRestDocumentation - .documentationConfiguration(contextProvider); + .documentationConfiguration(contextProvider); configurationCustomizers.orderedStream() - .forEach((configurationCustomizer) -> configurationCustomizer.customize(configurer)); + .forEach((configurationCustomizer) -> configurationCustomizer.customize(configurer)); return configurer; } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsRestAssuredBuilderCustomizer.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsRestAssuredBuilderCustomizer.java index b87dbdf345..7ef1e895ba 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsRestAssuredBuilderCustomizer.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsRestAssuredBuilderCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,8 @@ class RestDocsRestAssuredBuilderCustomizer implements InitializingBean { PropertyMapper map = PropertyMapper.get(); String host = this.properties.getUriHost(); map.from(this.properties::getUriScheme) - .when((scheme) -> StringUtils.hasText(scheme) && StringUtils.hasText(host)) - .to((scheme) -> this.delegate.baseUri(scheme + "://" + host)); + .when((scheme) -> StringUtils.hasText(scheme) && StringUtils.hasText(host)) + .to((scheme) -> this.delegate.baseUri(scheme + "://" + host)); map.from(this.properties::getUriPort).whenNonNull().to(this.delegate::port); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocumentationContextProviderRegistrar.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocumentationContextProviderRegistrar.java index 36cb4227c1..6a56125e81 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocumentationContextProviderRegistrar.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocumentationContextProviderRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,9 +37,9 @@ class RestDocumentationContextProviderRegistrar implements ImportBeanDefinitionR @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { Map annotationAttributes = importingClassMetadata - .getAnnotationAttributes(AutoConfigureRestDocs.class.getName()); + .getAnnotationAttributes(AutoConfigureRestDocs.class.getName()); BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder - .genericBeanDefinition(ManualRestDocumentation.class); + .genericBeanDefinition(ManualRestDocumentation.class); String outputDir = (String) annotationAttributes.get("outputDir"); if (StringUtils.hasText(outputDir)) { definitionBuilder.addConstructorArgValue(outputDir); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerAutoConfiguration.java index d6c33fba62..186536b356 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,7 +64,7 @@ public class MockRestServiceServerAutoConfiguration { private MockRestServiceServer createDeferredMockRestServiceServer(MockServerRestTemplateCustomizer customizer) throws Exception { Constructor constructor = MockRestServiceServer.class - .getDeclaredConstructor(RequestExpectationManager.class); + .getDeclaredConstructor(RequestExpectationManager.class); constructor.setAccessible(true); return constructor.newInstance(new DeferredRequestExpectationManager(customizer)); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestContextBootstrapper.java index b96c685b48..726489cae0 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,10 @@ class RestClientTestContextBootstrapper extends SpringBootTestContextBootstrappe @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(RestClientTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(RestClientTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTestContextBootstrapper.java index 8f25e8c04e..da6d72dd5a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,10 @@ class WebFluxTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(WebFluxTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(WebFluxTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfiguration.java index 22eb70e798..6d429eb4fa 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -132,7 +132,7 @@ public class MockMvcAutoConfiguration { dispatcherServlet.setDispatchOptionsRequest(this.webMvcProperties.isDispatchOptionsRequest()); dispatcherServlet.setDispatchTraceRequest(this.webMvcProperties.isDispatchTraceRequest()); dispatcherServlet - .setThrowExceptionIfNoHandlerFound(this.webMvcProperties.isThrowExceptionIfNoHandlerFound()); + .setThrowExceptionIfNoHandlerFound(this.webMvcProperties.isThrowExceptionIfNoHandlerFound()); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebDriverAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebDriverAutoConfiguration.java index e19cedfec3..202cbb0ab5 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebDriverAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebDriverAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ public class MockMvcWebDriverAutoConfiguration { @ConditionalOnBean(MockMvc.class) public MockMvcHtmlUnitDriverBuilder mockMvcHtmlUnitDriverBuilder(MockMvc mockMvc, Environment environment) { return MockMvcHtmlUnitDriverBuilder.mockMvcSetup(mockMvc) - .withDelegate(new LocalHostWebConnectionHtmlUnitDriver(environment, BrowserVersion.CHROME)); + .withDelegate(new LocalHostWebConnectionHtmlUnitDriver(environment, BrowserVersion.CHROME)); } @Bean diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizer.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizer.java index efee0f6ae2..82bd990f35 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizer.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizer.java @@ -108,9 +108,10 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi private void addFilters(ConfigurableMockMvcBuilder builder) { FilterRegistrationBeans registrations = new FilterRegistrationBeans(this.context); - registrations.stream().map(AbstractFilterRegistrationBean.class::cast) - .filter(AbstractFilterRegistrationBean::isEnabled) - .forEach((registration) -> addFilter(builder, registration)); + registrations.stream() + .map(AbstractFilterRegistrationBean.class::cast) + .filter(AbstractFilterRegistrationBean::isEnabled) + .forEach((registration) -> addFilter(builder, registration)); } private void addFilter(ConfigurableMockMvcBuilder builder, AbstractFilterRegistrationBean registration) { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestContextBootstrapper.java index c8a92f24b7..fc366bc2ca 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,10 @@ class WebMvcTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(WebMvcTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(WebMvcTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientTestContextBootstrapper.java index d3d4bc0132..931e76e5ce 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,10 @@ class WebServiceClientTestContextBootstrapper extends SpringBootTestContextBoots @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(WebServiceClientTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(WebServiceClientTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/webservices/server/WebServiceServerTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/webservices/server/WebServiceServerTestContextBootstrapper.java index 817fbd073d..2e5cbe01f3 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/webservices/server/WebServiceServerTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/webservices/server/WebServiceServerTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,10 @@ class WebServiceServerTestContextBootstrapper extends SpringBootTestContextBoots @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(WebServiceServerTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(WebServiceServerTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/AutoConfigurationImportedCondition.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/AutoConfigurationImportedCondition.java index d1c789359a..0cf44e791d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/AutoConfigurationImportedCondition.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/AutoConfigurationImportedCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,7 +40,7 @@ public final class AutoConfigurationImportedCondition extends Condition this.reportListener.prepareTestInstance(testContext)) - .isEqualTo(originalFailure); + .isEqualTo(originalFailure); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/actuate/metrics/MetricsExportContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/actuate/metrics/MetricsExportContextCustomizerFactoryTests.java index 000753cce0..6aa152707b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/actuate/metrics/MetricsExportContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/actuate/metrics/MetricsExportContextCustomizerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ class MetricsExportContextCustomizerFactoryTests { ConfigurableApplicationContext context = new GenericApplicationContext(); customizer.customizeContext(context, null); assertThat(context.getEnvironment().getProperty("management.metrics.export.defaults.enabled")) - .isEqualTo("false"); + .isEqualTo("false"); assertThat(context.getEnvironment().getProperty("management.metrics.export.simple.enabled")).isEqualTo("true"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java index 7536126a75..b4987dfdad 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -78,7 +78,8 @@ class ImportsContextCustomizerFactoryWithAutoConfigurationTests { private void executeTests(Class testClass) { LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() - .selectors(DiscoverySelectors.selectClass(testClass)).build(); + .selectors(DiscoverySelectors.selectClass(testClass)) + .build(); Launcher launcher = LauncherFactory.create(); launcher.execute(request); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/cassandra/DataCassandraTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/cassandra/DataCassandraTestIntegrationTests.java index 0b568c96bb..f71caf3754 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/cassandra/DataCassandraTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/cassandra/DataCassandraTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,7 +71,7 @@ class DataCassandraTestIntegrationTests { @Test void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestIntegrationTests.java index d8c58eb8c3..1261a74edc 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +48,9 @@ class DataCouchbaseTestIntegrationTests { @Container static final CouchbaseContainer couchbase = new CouchbaseContainer(DockerImageNames.couchbase()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)) - .withBucket(new BucketDefinition(BUCKET_NAME)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)) + .withBucket(new BucketDefinition(BUCKET_NAME)); @DynamicPropertySource static void couchbaseProperties(DynamicPropertyRegistry registry) { @@ -71,7 +72,7 @@ class DataCouchbaseTestIntegrationTests { @Test void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestReactiveIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestReactiveIntegrationTests.java index 8ce3bc0e9b..27be882a85 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestReactiveIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,8 +46,9 @@ class DataCouchbaseTestReactiveIntegrationTests { @Container static final CouchbaseContainer couchbase = new CouchbaseContainer(DockerImageNames.couchbase()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)) - .withBucket(new BucketDefinition(BUCKET_NAME)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)) + .withBucket(new BucketDefinition(BUCKET_NAME)); @DynamicPropertySource static void couchbaseProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestWithIncludeFilterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestWithIncludeFilterIntegrationTests.java index ba8d393805..1e779b709b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestWithIncludeFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestWithIncludeFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,9 @@ class DataCouchbaseTestWithIncludeFilterIntegrationTests { @Container static final CouchbaseContainer couchbase = new CouchbaseContainer(DockerImageNames.couchbase()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)) - .withBucket(new BucketDefinition(BUCKET_NAME)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)) + .withBucket(new BucketDefinition(BUCKET_NAME)); @DynamicPropertySource static void couchbaseProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestIntegrationTests.java index fdd3311f0b..e57852a4e0 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,8 @@ class DataElasticsearchTestIntegrationTests { @Container static final ElasticsearchContainer elasticsearch = new ElasticsearchContainer(DockerImageNames.elasticsearch()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void elasticsearchProperties(DynamicPropertyRegistry registry) { @@ -65,7 +66,7 @@ class DataElasticsearchTestIntegrationTests { @Test void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestPropertiesIntegrationTests.java index b0f2f6941a..9a15e17e98 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,8 @@ class DataElasticsearchTestPropertiesIntegrationTests { @Container static final ElasticsearchContainer elasticsearch = new ElasticsearchContainer(DockerImageNames.elasticsearch()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void elasticsearchProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestReactiveIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestReactiveIntegrationTests.java index e82e0474fd..99e6b7fb69 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestReactiveIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,8 @@ class DataElasticsearchTestReactiveIntegrationTests { @Container static final ElasticsearchContainer elasticsearch = new ElasticsearchContainer(DockerImageNames.elasticsearch()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void elasticsearchProperties(DynamicPropertyRegistry registry) { @@ -63,7 +64,7 @@ class DataElasticsearchTestReactiveIntegrationTests { exampleDocument = this.exampleReactiveRepository.save(exampleDocument).block(Duration.ofSeconds(30)); assertThat(exampleDocument.getId()).isNotNull(); assertThat(this.elasticsearchTemplate.exists(exampleDocument.getId(), ExampleDocument.class) - .block(Duration.ofSeconds(30))).isTrue(); + .block(Duration.ofSeconds(30))).isTrue(); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestWithIncludeFilterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestWithIncludeFilterIntegrationTests.java index 2c0112494a..18ebfef088 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestWithIncludeFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestWithIncludeFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,8 @@ class DataElasticsearchTestWithIncludeFilterIntegrationTests { @Container static final ElasticsearchContainer elasticsearch = new ElasticsearchContainer(DockerImageNames.elasticsearch()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void elasticsearchProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java index 81b8f7d030..5d4eb2d60c 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,7 +70,7 @@ class DataJdbcTestIntegrationTests { @Test void didNotInjectExampleComponent() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class)); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java index 08f693c248..93b22a47c3 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,15 +57,15 @@ class DataLdapTestIntegrationTests { Optional entry = this.exampleRepository.findOne(ldapQuery); assertThat(entry.isPresent()).isTrue(); assertThat(entry.get().getDn()) - .isEqualTo(LdapUtils.newLdapName("cn=Bob Smith,ou=company1,c=Sweden,dc=spring,dc=org")); + .isEqualTo(LdapUtils.newLdapName("cn=Bob Smith,ou=company1,c=Sweden,dc=spring,dc=org")); assertThat(this.ldapTemplate.findOne(ldapQuery, ExampleEntry.class).getDn()) - .isEqualTo(LdapUtils.newLdapName("cn=Bob Smith,ou=company1,c=Sweden,dc=spring,dc=org")); + .isEqualTo(LdapUtils.newLdapName("cn=Bob Smith,ou=company1,c=Sweden,dc=spring,dc=org")); } @Test void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestIntegrationTests.java index 3a3e5cdd6a..132eb9aa33 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,7 @@ class DataMongoTestIntegrationTests { @Container static final MongoDBContainer mongoDB = new MongoDBContainer(DockerImageNames.mongo()).withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(5)); + .withStartupTimeout(Duration.ofMinutes(5)); @Autowired private MongoTemplate mongoTemplate; @@ -68,7 +68,7 @@ class DataMongoTestIntegrationTests { @Test void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } @DynamicPropertySource diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestReactiveIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestReactiveIntegrationTests.java index 65003b8470..4259b537f7 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestReactiveIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class DataMongoTestReactiveIntegrationTests { @Container static final MongoDBContainer mongoDB = new MongoDBContainer(DockerImageNames.mongo()).withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(5)); + .withStartupTimeout(Duration.ofMinutes(5)); @Autowired private ReactiveMongoTemplate mongoTemplate; diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestWithIncludeFilterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestWithIncludeFilterIntegrationTests.java index 21e28dc89d..d2b99dfaf9 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestWithIncludeFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestWithIncludeFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ class DataMongoTestWithIncludeFilterIntegrationTests { @Container static final MongoDBContainer mongoDB = new MongoDBContainer(DockerImageNames.mongo()).withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(5)); + .withStartupTimeout(Duration.ofMinutes(5)); @Autowired private ExampleService service; diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/TransactionalDataMongoTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/TransactionalDataMongoTestIntegrationTests.java index a882d12fbf..d2ede5f559 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/TransactionalDataMongoTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/TransactionalDataMongoTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,7 @@ class TransactionalDataMongoTestIntegrationTests { @Container static final MongoDBContainer mongoDB = new MongoDBContainer(DockerImageNames.mongo()).withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(5)); + .withStartupTimeout(Duration.ofMinutes(5)); @Autowired private ExampleRepository exampleRepository; diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java index fb783b4f84..b0e882603a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,8 @@ class DataNeo4jTestIntegrationTests { @Container static final Neo4jContainer neo4j = new Neo4jContainer<>(DockerImageNames.neo4j()).withoutAuthentication() - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void neo4jProperties(DynamicPropertyRegistry registry) { @@ -75,7 +76,7 @@ class DataNeo4jTestIntegrationTests { @Test void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestPropertiesIntegrationTests.java index e334c40563..37413c4434 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,8 @@ class DataNeo4jTestPropertiesIntegrationTests { @Container static final Neo4jContainer neo4j = new Neo4jContainer<>(DockerImageNames.neo4j()).withoutAuthentication() - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void neo4jProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestReactiveIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestReactiveIntegrationTests.java index 2cc6479e93..64ba554c95 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestReactiveIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,7 +56,8 @@ class DataNeo4jTestReactiveIntegrationTests { @Container static final Neo4jContainer neo4j = new Neo4jContainer<>(DockerImageNames.neo4j()).withoutAuthentication() - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void neo4jProperties(DynamicPropertyRegistry registry) { @@ -74,15 +75,18 @@ class DataNeo4jTestReactiveIntegrationTests { @Test void testRepository() { - Mono.just(new ExampleGraph("Look, new @DataNeo4jTest with reactive!")).flatMap(this.exampleRepository::save) - .as(StepVerifier::create).expectNextCount(1).verifyComplete(); + Mono.just(new ExampleGraph("Look, new @DataNeo4jTest with reactive!")) + .flatMap(this.exampleRepository::save) + .as(StepVerifier::create) + .expectNextCount(1) + .verifyComplete(); StepVerifier.create(this.neo4jTemplate.count(ExampleGraph.class)).expectNext(1L).verifyComplete(); } @Test void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } @TestConfiguration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestWithIncludeFilterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestWithIncludeFilterIntegrationTests.java index 69be31fe2f..85b46d43ae 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestWithIncludeFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestWithIncludeFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,8 @@ class DataNeo4jTestWithIncludeFilterIntegrationTests { @Container static final Neo4jContainer neo4j = new Neo4jContainer<>(DockerImageNames.neo4j()).withoutAuthentication() - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void neo4jProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java index ef7d4b19a6..4fa8d9a051 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,14 +72,14 @@ class DataRedisTestIntegrationTests { PersonHash savedEntity = this.exampleRepository.save(personHash); assertThat(savedEntity.getId()).isNotNull(); assertThat(this.operations.execute((RedisConnection connection) -> connection - .exists(("persons:" + savedEntity.getId()).getBytes(CHARSET)))).isTrue(); + .exists(("persons:" + savedEntity.getId()).getBytes(CHARSET)))).isTrue(); this.exampleRepository.deleteAll(); } @Test void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestReactiveIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestReactiveIntegrationTests.java index 8bfa677a1d..bef8277190 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestReactiveIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,17 +60,19 @@ class DataRedisTestReactiveIntegrationTests { @Test void testRepository() { String id = UUID.randomUUID().toString(); - StepVerifier.create(this.operations.opsForValue().set(id, "Hello World")).expectNext(Boolean.TRUE) - .verifyComplete(); + StepVerifier.create(this.operations.opsForValue().set(id, "Hello World")) + .expectNext(Boolean.TRUE) + .verifyComplete(); StepVerifier.create(this.operations.opsForValue().get(id)).expectNext("Hello World").verifyComplete(); - StepVerifier.create(this.operations.execute((action) -> action.serverCommands().flushDb())).expectNext("OK") - .verifyComplete(); + StepVerifier.create(this.operations.execute((action) -> action.serverCommands().flushDb())) + .expectNext("OK") + .verifyComplete(); } @Test void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/graphql/tester/GraphQlTesterAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/graphql/tester/GraphQlTesterAutoConfigurationTests.java index 9708539009..693621b7a7 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/graphql/tester/GraphQlTesterAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/graphql/tester/GraphQlTesterAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,8 @@ import static org.mockito.Mockito.mock; */ class GraphQlTesterAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( - AutoConfigurations.of(JacksonAutoConfiguration.class, GraphQlTesterAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, GraphQlTesterAutoConfiguration.class)); @Test void shouldNotContributeTesterIfGraphQlServiceNotPresent() { @@ -47,7 +47,7 @@ class GraphQlTesterAutoConfigurationTests { @Test void shouldContributeTester() { this.contextRunner.withUserConfiguration(CustomGraphQlServiceConfiguration.class) - .run((context) -> assertThat(context).hasNotFailed().hasSingleBean(GraphQlTester.class)); + .run((context) -> assertThat(context).hasNotFailed().hasSingleBean(GraphQlTester.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java index f7a5eed4fc..50875c7095 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,7 +73,7 @@ class JdbcTestIntegrationTests { @Test void didNotInjectExampleRepository() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleRepository.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleRepository.class)); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java index cf494a2fd7..c23c99341c 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat; class TestDatabaseAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(TestDatabaseAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(TestDatabaseAutoConfiguration.class)); @Test void replaceWithNoDataSourceAvailable() { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java index eb66ac36b6..da8bda872f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ class JooqTestIntegrationTests { @Test void testDSLContext() { assertThat(this.dsl.selectCount().from("INFORMATION_SCHEMA.TABLES").fetchOne(0, Integer.class)) - .isGreaterThan(0); + .isGreaterThan(0); } @Test @@ -67,7 +67,7 @@ class JooqTestIntegrationTests { @Test void didNotInjectExampleComponent() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class)); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestIntegrationTests.java index b6214d651c..205ef537c0 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -98,7 +98,8 @@ class JsonTestIntegrationTests { ExampleJsonObjectWithView object = new ExampleJsonObjectWithView(); object.setValue("spring"); JsonContent content = this.jacksonWithViewJson - .forView(ExampleJsonObjectWithView.TestView.class).write(object); + .forView(ExampleJsonObjectWithView.TestView.class) + .write(object); assertThat(content).doesNotHaveJsonPathValue("id"); assertThat(content).isEqualToJson("example.json"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestAttributesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestAttributesIntegrationTests.java index 92ccce3c95..baa1fc5cca 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestAttributesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestAttributesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ class DataJpaTestAttributesIntegrationTests { @Test void bootstrapModeIsSet() { assertThat(this.environment.getProperty("spring.data.jpa.repositories.bootstrap-mode")) - .isEqualTo(BootstrapMode.DEFERRED.name()); + .isEqualTo(BootstrapMode.DEFERRED.name()); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java index 3f1d9e2631..e3e54de73f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -94,7 +94,7 @@ class DataJpaTestIntegrationTests { @Test void didNotInjectExampleComponent() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class)); } @Test @@ -110,7 +110,7 @@ class DataJpaTestIntegrationTests { @Test void bootstrapModeIsDefaultByDefault() { assertThat(this.applicationContext.getEnvironment().getProperty("spring.data.jpa.repositories.bootstrap-mode")) - .isEqualTo(BootstrapMode.DEFAULT.name()); + .isEqualTo(BootstrapMode.DEFAULT.name()); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestSchemaCredentialsIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestSchemaCredentialsIntegrationTests.java index acef5aefb1..2bb4899c10 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestSchemaCredentialsIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestSchemaCredentialsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,8 @@ class DataJpaTestSchemaCredentialsIntegrationTests { String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).isEqualTo("H2"); assertThat(new JdbcTemplate(this.dataSource).queryForList("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES", - String.class)).contains("EXAMPLE"); + String.class)) + .contains("EXAMPLE"); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java index 5fda3b046f..9a0282b5e7 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,15 +42,16 @@ import static org.mockito.Mockito.mock; class TestDatabaseAutoConfigurationNoEmbeddedTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(ExistingDataSourceConfiguration.class) - .withConfiguration(AutoConfigurations.of(TestDatabaseAutoConfiguration.class)); + .withUserConfiguration(ExistingDataSourceConfiguration.class) + .withConfiguration(AutoConfigurations.of(TestDatabaseAutoConfiguration.class)); @Test void applyAnyReplace() { - this.contextRunner.run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("Failed to replace DataSource with an embedded database for tests.") - .hasMessageContaining("If you want an embedded database please put a supported one on the classpath") - .hasMessageContaining("or tune the replace attribute of @AutoConfigureTestDatabase.")); + this.contextRunner.run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("Failed to replace DataSource with an embedded database for tests.") + .hasMessageContaining("If you want an embedded database please put a supported one on the classpath") + .hasMessageContaining("or tune the replace attribute of @AutoConfigureTestDatabase.")); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java index ed06824cbe..4fc908bacd 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,7 +62,7 @@ class TestEntityManagerTests { @Test void createWhenEntityManagerIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new TestEntityManager(null)) - .withMessageContaining("EntityManagerFactory must not be null"); + .withMessageContaining("EntityManagerFactory must not be null"); } @Test @@ -192,8 +192,8 @@ class TestEntityManagerTests { given(this.entityManagerFactory.getPersistenceUnitUtil()).willReturn(this.persistenceUnitUtil); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); assertThatIllegalArgumentException().isThrownBy(() -> this.testEntityManager.getId(entity, Long.class)) - .withMessageContaining("ID mismatch: Object of class [java.lang.Integer] " - + "must be an instance of class java.lang.Long"); + .withMessageContaining("ID mismatch: Object of class [java.lang.Integer] " + + "must be an instance of class java.lang.Long"); } @Test @@ -214,7 +214,7 @@ class TestEntityManagerTests { @Test void getEntityManagerWhenNotSetShouldThrowException() { assertThatIllegalStateException().isThrownBy(this.testEntityManager::getEntityManager) - .withMessageContaining("No transactional EntityManager found"); + .withMessageContaining("No transactional EntityManager found"); } private void bindEntityManager() { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java index e71ceebf9d..32132a1b17 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ class OverrideAutoConfigurationEnabledFalseIntegrationTests { ApplicationContext context = this.context; assertThat(context.getBean(ExampleTestConfig.class)).isNotNull(); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> context.getBean(ConfigurationPropertiesBindingPostProcessor.class)); + .isThrownBy(() -> context.getBean(ConfigurationPropertiesBindingPostProcessor.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java index d52d5730f1..01928c817f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class AnnotationsPropertySourceTests { @Test void createWhenSourceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new AnnotationsPropertySource(null)) - .withMessageContaining("Property source must not be null"); + .withMessageContaining("Property source must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java index 535d8f6f99..907073225f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -92,9 +92,9 @@ class PropertyMappingContextCustomizerFactoryTests { context.register(ConfigMapping.class); customizer.customizeContext(context, null); assertThatExceptionOfType(BeanCreationException.class).isThrownBy(context::refresh) - .withMessageContaining("The @PropertyMapping annotation " - + "@PropertyMappingContextCustomizerFactoryTests.TypeMappingAnnotation " - + "cannot be used in combination with the @Component annotation @Configuration"); + .withMessageContaining("The @PropertyMapping annotation " + + "@PropertyMappingContextCustomizerFactoryTests.TypeMappingAnnotation " + + "cannot be used in combination with the @Component annotation @Configuration"); } @NoMappingAnnotation diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java index 40d41b3c61..c543a3e2ec 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,7 +69,8 @@ class MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests { @Test void snippetGeneration() throws Exception { - this.mvc.perform(get("/")).andDo(this.documentationHandler + this.mvc.perform(get("/")) + .andDo(this.documentationHandler .document(links(linkWithRel("self").description("Canonical location of this resource")))); File defaultSnippetsDir = new File(this.generatedSnippets, "snippet-generation"); assertThat(defaultSnippetsDir).exists(); @@ -94,7 +95,7 @@ class MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests { @Bean RestDocsMockMvcConfigurationCustomizer defaultSnippetsCustomizer() { return (configurer) -> configurer.snippets() - .withAdditionalDefaults(responseFields(fieldWithPath("_links.self").description("Main URL"))); + .withAdditionalDefaults(responseFields(fieldWithPath("_links.self").description("Main URL"))); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java index f5a3dcdfde..68f118d482 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,9 +71,14 @@ class RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests @Test void snippetGeneration() { given(this.documentationSpec) - .filter(document("default-snippets", - preprocessRequest(modifyUris().scheme("https").host("api.example.com").removePort()))) - .when().port(this.port).get("/").then().assertThat().statusCode(is(200)); + .filter(document("default-snippets", + preprocessRequest(modifyUris().scheme("https").host("api.example.com").removePort()))) + .when() + .port(this.port) + .get("/") + .then() + .assertThat() + .statusCode(is(200)); File defaultSnippetsDir = new File(this.generatedSnippets, "default-snippets"); assertThat(defaultSnippetsDir).exists(); assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.md"))).contains("'https://api.example.com/'"); @@ -98,7 +103,7 @@ class RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests @Bean RestDocsRestAssuredConfigurationCustomizer defaultSnippetsCustomizer() { return (configurer) -> configurer.snippets() - .withAdditionalDefaults(responseFields(fieldWithPath("_links.self").description("Main URL"))); + .withAdditionalDefaults(responseFields(fieldWithPath("_links.self").description("Main URL"))); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationIntegrationTests.java index 92800c3ff1..56858535ba 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,9 +63,14 @@ class RestAssuredRestDocsAutoConfigurationIntegrationTests { @Test void defaultSnippetsAreWritten() { given(this.documentationSpec) - .filter(document("default-snippets", - preprocessRequest(modifyUris().scheme("https").host("api.example.com").removePort()))) - .when().port(this.port).get("/").then().assertThat().statusCode(is(200)); + .filter(document("default-snippets", + preprocessRequest(modifyUris().scheme("https").host("api.example.com").removePort()))) + .when() + .port(this.port) + .get("/") + .then() + .assertThat() + .statusCode(is(200)); File defaultSnippetsDir = new File(this.generatedSnippets, "default-snippets"); assertThat(defaultSnippetsDir).exists(); assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.adoc"))).contains("'https://api.example.com/'"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java index 0eb8748481..b4f661c52f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,8 +62,13 @@ class WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTest @Test void defaultSnippetsAreWritten() { - this.webTestClient.get().uri("/").exchange().expectStatus().is2xxSuccessful().expectBody() - .consumeWith(document("default-snippets")); + this.webTestClient.get() + .uri("/") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .consumeWith(document("default-snippets")); File defaultSnippetsDir = new File(this.generatedSnippets, "default-snippets"); assertThat(defaultSnippetsDir).exists(); assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.md"))).contains("'https://api.example.com/'"); @@ -88,7 +93,7 @@ class WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTest @Bean RestDocsWebTestClientConfigurationCustomizer defaultSnippetsCustomizer() { return (configurer) -> configurer.snippets() - .withAdditionalDefaults(responseFields(fieldWithPath("_links.self").description("Main URL"))); + .withAdditionalDefaults(responseFields(fieldWithPath("_links.self").description("Main URL"))); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationIntegrationTests.java index c02e04d8e3..efe9f41a25 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,8 +55,13 @@ class WebTestClientRestDocsAutoConfigurationIntegrationTests { @Test void defaultSnippetsAreWritten() { - this.webTestClient.get().uri("/").exchange().expectStatus().is2xxSuccessful().expectBody() - .consumeWith(document("default-snippets")); + this.webTestClient.get() + .uri("/") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .consumeWith(document("default-snippets")); File defaultSnippetsDir = new File(this.generatedSnippets, "default-snippets"); assertThat(defaultSnippetsDir).exists(); assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.adoc"))).contains("'https://api.example.com/'"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityIntegrationTests.java index 8a4ead9d31..6a215a5fd6 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,8 +55,10 @@ class MockMvcSecurityIntegrationTests { @Test void okResponseWithBasicAuthCredentialsForKnownUser() throws Exception { - this.mockMvc.perform(get("/").header(HttpHeaders.AUTHORIZATION, - "Basic " + Base64Utils.encodeToString("user:secret".getBytes()))).andExpect(status().isOk()); + this.mockMvc + .perform(get("/").header(HttpHeaders.AUTHORIZATION, + "Basic " + Base64Utils.encodeToString("user:secret".getBytes()))) + .andExpect(status().isOk()); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests.java index 52fcbdfdb7..68c31ee5bd 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests { @Test void mockServerRestTemplateCustomizerShouldNotBeRegistered() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(MockServerRestTemplateCustomizer.class)); + .isThrownBy(() -> this.applicationContext.getBean(MockServerRestTemplateCustomizer.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java index b2df64ab71..3966b197e2 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,8 +55,9 @@ class RestClientRestIntegrationTests { @Test void mockServerCallWithContent() { - this.server.expect(requestTo("/test")).andExpect(content().string("test")) - .andRespond(withSuccess("1", MediaType.TEXT_HTML)); + this.server.expect(requestTo("/test")) + .andExpect(content().string("test")) + .andRespond(withSuccess("1", MediaType.TEXT_HTML)); this.client.testPostWithBody("test"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java index c44fbbee7e..6ed3e63e46 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,13 +50,13 @@ class RestClientTestNoComponentIntegrationTests { @Test void exampleRestClientIsNotInjected() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleRestClient.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleRestClient.class)); } @Test void examplePropertiesIsNotInjected() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleProperties.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleProperties.class)); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java index 9645c05324..08e00159c6 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,22 +50,25 @@ class RestClientTestTwoComponentsIntegrationTests { @Test void serverShouldNotWork() { - assertThatIllegalStateException().isThrownBy( - () -> this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML))) - .withMessageContaining("Unable to use auto-configured"); + assertThatIllegalStateException() + .isThrownBy( + () -> this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML))) + .withMessageContaining("Unable to use auto-configured"); } @Test void client1RestCallViaCustomizer() { - this.customizer.getServer(this.client1.getRestTemplate()).expect(requestTo("/test")) - .andRespond(withSuccess("hello", MediaType.TEXT_HTML)); + this.customizer.getServer(this.client1.getRestTemplate()) + .expect(requestTo("/test")) + .andRespond(withSuccess("hello", MediaType.TEXT_HTML)); assertThat(this.client1.test()).isEqualTo("hello"); } @Test void client2RestCallViaCustomizer() { - this.customizer.getServer(this.client2.getRestTemplate()).expect(requestTo("/test")) - .andRespond(withSuccess("there", MediaType.TEXT_HTML)); + this.customizer.getServer(this.client2.getRestTemplate()) + .expect(requestTo("/test")) + .andRespond(withSuccess("there", MediaType.TEXT_HTML)); assertThat(this.client2.test()).isEqualTo("there"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithConfigurationPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithConfigurationPropertiesIntegrationTests.java index d94e53df5d..0a8a708a2b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithConfigurationPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithConfigurationPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ class RestClientTestWithConfigurationPropertiesIntegrationTests { @Test void configurationPropertiesCanBeAddedAsComponent() { assertThat(this.applicationContext.getBeansOfType(ExampleProperties.class).keySet()) - .containsOnly("example-org.springframework.boot.test.autoconfigure.web.client.ExampleProperties"); + .containsOnly("example-org.springframework.boot.test.autoconfigure.web.client.ExampleProperties"); assertThat(this.applicationContext.getBean(ExampleProperties.class).getName()).isEqualTo("Hello"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfigurationTests.java index df78ddd033..5e79def6ca 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ import static org.mockito.Mockito.mock; class WebTestClientAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(WebTestClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(WebTestClientAutoConfiguration.class)); @Test void shouldNotBeConfiguredWithoutWebHandler() { @@ -72,10 +72,11 @@ class WebTestClientAutoConfigurationTests { @Test void shouldCustomizeTimeout() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("spring.test.webtestclient.timeout=15m").run((context) -> { - WebTestClient webTestClient = context.getBean(WebTestClient.class); - assertThat(webTestClient).hasFieldOrPropertyWithValue("responseTimeout", Duration.ofMinutes(15)); - }); + .withPropertyValues("spring.test.webtestclient.timeout=15m") + .run((context) -> { + WebTestClient webTestClient = context.getBean(WebTestClient.class); + assertThat(webTestClient).hasFieldOrPropertyWithValue("responseTimeout", Duration.ofMinutes(15)); + }); } @Test @@ -97,17 +98,17 @@ class WebTestClientAutoConfigurationTests { @SuppressWarnings("unchecked") void shouldNotApplySpringSecurityConfigurerWhenSpringSecurityNotOnClassPath() { FilteredClassLoader classLoader = new FilteredClassLoader(SecurityMockServerConfigurers.class); - this.contextRunner.withUserConfiguration(BaseConfiguration.class).withClassLoader(classLoader) - .run((context) -> { - WebTestClient webTestClient = context.getBean(WebTestClient.class); - WebTestClient.Builder builder = (WebTestClient.Builder) ReflectionTestUtils.getField(webTestClient, - "builder"); - WebHttpHandlerBuilder httpHandlerBuilder = (WebHttpHandlerBuilder) ReflectionTestUtils - .getField(builder, "httpHandlerBuilder"); - List filters = (List) ReflectionTestUtils.getField(httpHandlerBuilder, - "filters"); - assertThat(filters).isEmpty(); - }); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .withClassLoader(classLoader) + .run((context) -> { + WebTestClient webTestClient = context.getBean(WebTestClient.class); + WebTestClient.Builder builder = (WebTestClient.Builder) ReflectionTestUtils.getField(webTestClient, + "builder"); + WebHttpHandlerBuilder httpHandlerBuilder = (WebHttpHandlerBuilder) ReflectionTestUtils.getField(builder, + "httpHandlerBuilder"); + List filters = (List) ReflectionTestUtils.getField(httpHandlerBuilder, "filters"); + assertThat(filters).isEmpty(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAutoConfigurationIntegrationTests.java index 2cef057e1d..97a54cbe09 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,7 +85,7 @@ class WebFluxTestAutoConfigurationIntegrationTests { @Test void oAuth2ResourceServerAutoConfigurationWasImported() { assertThat(this.applicationContext) - .has(importedAutoConfiguration(ReactiveOAuth2ResourceServerAutoConfiguration.class)); + .has(importedAutoConfiguration(ReactiveOAuth2ResourceServerAutoConfiguration.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestConverterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestConverterIntegrationTests.java index 41b2184319..df5d8e54b2 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestConverterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestConverterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,13 @@ class WebFluxTestConverterIntegrationTests { @Test void shouldFindConverter() { UUID id = UUID.randomUUID(); - this.webClient.get().uri("/two/" + id).exchange().expectStatus().isOk().expectBody(String.class) - .isEqualTo(id + "two"); + this.webClient.get() + .uri("/two/" + id) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo(id + "two"); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfigurationTests.java index 73feb850ca..4c88271d30 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ import static org.mockito.Mockito.mock; class MockMvcAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MockMvcAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MockMvcAutoConfiguration.class)); @Test void registersDispatcherServletFromMockMvc() { @@ -62,7 +62,7 @@ class MockMvcAutoConfigurationTests { @Test void shouldNotRegisterWebTestClientIfWebFluxMissing() { this.contextRunner.withClassLoader(new FilteredClassLoader(WebClient.class)) - .run((context) -> assertThat(context).doesNotHaveBean(WebTestClient.class)); + .run((context) -> assertThat(context).doesNotHaveBean(WebTestClient.class)); } @Test @@ -71,7 +71,7 @@ class MockMvcAutoConfigurationTests { assertThat(context).hasSingleBean(WebTestClient.class); assertThat(context).hasBean("myWebTestClientCustomizer"); then(context.getBean("myWebTestClientCustomizer", WebTestClientBuilderCustomizer.class)).should() - .customize(any(WebTestClient.Builder.class)); + .customize(any(WebTestClient.Builder.class)); }); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizerTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizerTests.java index 4ae8388bc9..c7e3995e30 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizerTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,7 +65,7 @@ class SpringBootMockMvcBuilderCustomizerTests { this.customizer = new SpringBootMockMvcBuilderCustomizer(context); this.customizer.customize(builder); FilterRegistrationBean registrationBean = (FilterRegistrationBean) context - .getBean("filterRegistrationBean"); + .getBean("filterRegistrationBean"); Filter testFilter = (Filter) context.getBean("testFilter"); Filter otherTestFilter = registrationBean.getFilter(); List filters = (List) ReflectionTestUtils.getField(builder, "filters"); @@ -99,7 +99,7 @@ class SpringBootMockMvcBuilderCustomizerTests { assertThat(delegate.allWritten).hasSize(10000); assertThat(delegate.allWritten) - .allSatisfy((written) -> assertThat(written).containsExactly("1", "2", "3", "4", "5")); + .allSatisfy((written) -> assertThat(written).containsExactly("1", "2", "3", "4", "5")); } private static final class CapturingLinesWriter implements LinesWriter { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java index 6e39d92300..c6d3352278 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,7 +76,7 @@ class WebMvcTestAutoConfigurationIntegrationTests { void asyncTaskExecutorWithApplicationTaskExecutor() { assertThat(this.applicationContext.getBeansOfType(AsyncTaskExecutor.class)).hasSize(1); assertThat(this.applicationContext.getBean(RequestMappingHandlerAdapter.class)).extracting("taskExecutor") - .isSameAs(this.applicationContext.getBean("applicationTaskExecutor")); + .isSameAs(this.applicationContext.getBean("applicationTaskExecutor")); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java index c5065ddd99..c5f2f4c8b2 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,8 +72,8 @@ class WebMvcTestAllControllersIntegrationTests { @Test void shouldRunValidationFailure() { assertThatExceptionOfType(NestedServletException.class) - .isThrownBy(() -> this.mvc.perform(get("/three/invalid"))) - .withCauseInstanceOf(ConstraintViolationException.class); + .isThrownBy(() -> this.mvc.perform(get("/three/invalid"))) + .withCauseInstanceOf(ConstraintViolationException.class); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestCustomDispatcherServletIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestCustomDispatcherServletIntegrationTests.java index fe1e30cc56..f7f5c8e5fc 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestCustomDispatcherServletIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestCustomDispatcherServletIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,8 +45,9 @@ class WebMvcTestCustomDispatcherServletIntegrationTests { @Test void dispatcherServletIsCustomized() throws Exception { - this.mvc.perform(get("/does-not-exist")).andExpect(status().isBadRequest()) - .andExpect(content().string("Invalid request: /does-not-exist")); + this.mvc.perform(get("/does-not-exist")) + .andExpect(status().isBadRequest()) + .andExpect(content().string("Invalid request: /does-not-exist")); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestHateoasIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestHateoasIntegrationTests.java index f22ef521d9..735ebb950f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestHateoasIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestHateoasIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,13 +42,13 @@ class WebMvcTestHateoasIntegrationTests { @Test void plainResponse() throws Exception { this.mockMvc.perform(get("/hateoas/plain")) - .andExpect(header().string(HttpHeaders.CONTENT_TYPE, "application/json")); + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, "application/json")); } @Test void hateoasResponse() throws Exception { this.mockMvc.perform(get("/hateoas/resource")) - .andExpect(header().string(HttpHeaders.CONTENT_TYPE, "application/hal+json")); + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, "application/hal+json")); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestNestedIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestNestedIntegrationTests.java index da07a8b300..7dcdb8ee99 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestNestedIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestNestedIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,8 +61,9 @@ class WebMvcTestNestedIntegrationTests { @Test void shouldFindController2() throws Exception { - WebMvcTestNestedIntegrationTests.this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")) - .andExpect(status().isOk()); + WebMvcTestNestedIntegrationTests.this.mvc.perform(get("/two")) + .andExpect(content().string("hellotwo")) + .andExpect(status().isOk()); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPageableIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPageableIntegrationTests.java index 07754328ed..7482bb090c 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPageableIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPageableIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,9 @@ class WebMvcTestPageableIntegrationTests { @Test void shouldSupportPageable() throws Exception { - this.mvc.perform(get("/paged").param("page", "2").param("size", "42")).andExpect(status().isOk()) - .andExpect(content().string("2:42")); + this.mvc.perform(get("/paged").param("page", "2").param("size", "42")) + .andExpect(status().isOk()) + .andExpect(content().string("2:42")); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultIntegrationTests.java index 539cfda167..ca3cb41e18 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,7 +63,8 @@ class WebMvcTestPrintDefaultIntegrationTests { private void executeTests(Class testClass) { LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() - .selectors(DiscoverySelectors.selectClass(testClass)).build(); + .selectors(DiscoverySelectors.selectClass(testClass)) + .build(); Launcher launcher = LauncherFactory.create(); launcher.execute(request); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java index fb9851f392..e2ce3c0632 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,13 +56,13 @@ class WebMvcTestWithAutoConfigureMockMvcIntegrationTests { @Test void shouldNotHaveWebDriver() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(WebDriver.class)); + .isThrownBy(() -> this.context.getBean(WebDriver.class)); } @Test void shouldNotHaveWebClient() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(WebClient.class)); + .isThrownBy(() -> this.context.getBean(WebClient.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/AutoConfigureMockWebServiceServerEnabledIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/AutoConfigureMockWebServiceServerEnabledIntegrationTests.java index 3c5b35930b..2aedc9496a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/AutoConfigureMockWebServiceServerEnabledIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/AutoConfigureMockWebServiceServerEnabledIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ class AutoConfigureMockWebServiceServerEnabledIntegrationTests { @Test void mockWebServiceServerShouldNotBeRegistered() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(MockWebServiceServer.class)); + .isThrownBy(() -> this.applicationContext.getBean(MockWebServiceServer.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/AutoConfigureWebServiceClientWebServiceTemplateIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/AutoConfigureWebServiceClientWebServiceTemplateIntegrationTests.java index bd7f5c2355..2822c77621 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/AutoConfigureWebServiceClientWebServiceTemplateIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/AutoConfigureWebServiceClientWebServiceTemplateIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,7 @@ class AutoConfigureWebServiceClientWebServiceTemplateIntegrationTests { @Test void webServiceTemplateTest() { this.server.expect(payload(new StringSource(""))) - .andRespond(withPayload(new StringSource(""))); + .andRespond(withPayload(new StringSource(""))); this.webServiceTemplate.marshalSendAndReceive("https://example.com", new Request()); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientIntegrationTests.java index 2cb674e1cd..c3bc31d3bd 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ class WebServiceClientIntegrationTests { @Test void mockServerCall() { this.server.expect(payload(new StringSource(""))) - .andRespond(withPayload(new StringSource("200"))); + .andRespond(withPayload(new StringSource("200"))); assertThat(this.client.test()).extracting(Response::getStatus).isEqualTo(200); } @@ -56,14 +56,14 @@ class WebServiceClientIntegrationTests { void mockServerCall1() { this.server.expect(connectionTo("https://example1")).andRespond(withPayload(new StringSource(""))); assertThatExceptionOfType(SourceAssertionError.class).isThrownBy(this.client::test) - .withMessageContaining("Unexpected connection expected"); + .withMessageContaining("Unexpected connection expected"); } @Test void mockServerCall2() { this.server.expect(payload(new StringSource(""))).andRespond(withError("Invalid Request")); assertThatExceptionOfType(WebServiceTransportException.class).isThrownBy(this.client::test) - .withMessageContaining("Invalid Request"); + .withMessageContaining("Invalid Request"); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientNoComponentIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientNoComponentIntegrationTests.java index fdf01f2a13..9fd5372578 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientNoComponentIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientNoComponentIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,14 +50,14 @@ class WebServiceClientNoComponentIntegrationTests { @Test void exampleClientIsNotInjected() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleWebServiceClient.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleWebServiceClient.class)); } @Test void manuallyCreateBean() { ExampleWebServiceClient client = new ExampleWebServiceClient(this.webServiceTemplateBuilder); this.server.expect(payload(new StringSource(""))) - .andRespond(withPayload(new StringSource("200"))); + .andRespond(withPayload(new StringSource("200"))); assertThat(client.test()).extracting(Response::getStatus).isEqualTo(200); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/server/MockWebServiceClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/server/MockWebServiceClientAutoConfigurationTests.java index ac279e87a0..5cd68084a2 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/server/MockWebServiceClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/server/MockWebServiceClientAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; class MockWebServiceClientAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MockWebServiceClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MockWebServiceClientAutoConfiguration.class)); @Test void shouldRegisterMockWebServiceClient() { @@ -45,7 +45,7 @@ class MockWebServiceClientAutoConfigurationTests { FilteredClassLoader classLoader = new FilteredClassLoader(MockWebServiceClient.class); this.contextRunner.withClassLoader(classLoader) - .run((context) -> assertThat(context).doesNotHaveBean(MockWebServiceClient.class)); + .run((context) -> assertThat(context).doesNotHaveBean(MockWebServiceClient.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/server/WebServiceServerIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/server/WebServiceServerIntegrationTests.java index 6261d8e099..7bafe07819 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/server/WebServiceServerIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/server/WebServiceServerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,9 +38,8 @@ class WebServiceServerIntegrationTests { @Test void payloadRootMethod() { this.mock - .sendRequest( - RequestCreators.withPayload(new StringSource("Hello"))) - .andExpect(ResponseMatchers.payload(new StringSource("42"))); + .sendRequest(RequestCreators.withPayload(new StringSource("Hello"))) + .andExpect(ResponseMatchers.payload(new StringSource("42"))); } } 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 973cab28b0..32c74edf77 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 @@ -212,7 +212,7 @@ public class SpringBootContextLoader extends AbstractContextLoader { } initializers.addAll(application.getInitializers()); for (Class> initializerClass : config - .getContextInitializerClasses()) { + .getContextInitializerClasses()) { initializers.add(BeanUtils.instantiateClass(initializerClass)); } if (config.getParent() != null) { @@ -222,8 +222,11 @@ public class SpringBootContextLoader extends AbstractContextLoader { } private boolean isEmbeddedWebEnvironment(MergedContextConfiguration config) { - return MergedAnnotations.from(config.getTestClass(), SearchStrategy.TYPE_HIERARCHY).get(SpringBootTest.class) - .getValue("webEnvironment", WebEnvironment.class).orElse(WebEnvironment.NONE).isEmbedded(); + return MergedAnnotations.from(config.getTestClass(), SearchStrategy.TYPE_HIERARCHY) + .get(SpringBootTest.class) + .getValue("webEnvironment", WebEnvironment.class) + .orElse(WebEnvironment.NONE) + .isEmbedded(); } @Override 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..3572103ce5 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,7 +40,9 @@ class SpringBootTestArgs implements ContextCustomizer { SpringBootTestArgs(Class testClass) { this.args = MergedAnnotations.from(testClass, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY) - .get(SpringBootTest.class).getValue("args", String[].class).orElse(NO_ARGS); + .get(SpringBootTest.class) + .getValue("args", String[].class) + .orElse(NO_ARGS); } @Override diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java index 24c2ae68da..ef5e6f8f1a 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -115,7 +115,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr protected Set> getDefaultTestExecutionListenerClasses() { Set> listeners = super.getDefaultTestExecutionListenerClasses(); List postProcessors = SpringFactoriesLoader - .loadFactories(DefaultTestExecutionListenersPostProcessor.class, getClass().getClassLoader()); + .loadFactories(DefaultTestExecutionListenersPostProcessor.class, getClass().getClassLoader()); for (DefaultTestExecutionListenersPostProcessor postProcessor : postProcessors) { listeners = postProcessor.postProcessDefaultTestExecutionListeners(listeners); } @@ -172,7 +172,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr TestPropertySourceUtils.convertInlinedPropertiesToMap(configuration.getPropertySourceProperties())); Binder binder = new Binder(source); return binder.bind("spring.main.web-application-type", Bindable.of(WebApplicationType.class)) - .orElseGet(this::deduceWebApplicationType); + .orElseGet(this::deduceWebApplicationType); } private WebApplicationType deduceWebApplicationType() { @@ -199,8 +199,9 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr */ protected String determineResourceBasePath(MergedContextConfiguration configuration) { return MergedAnnotations.from(configuration.getTestClass(), SearchStrategy.TYPE_HIERARCHY) - .get(WebAppConfiguration.class).getValue(MergedAnnotation.VALUE, String.class) - .orElse("src/main/webapp"); + .get(WebAppConfiguration.class) + .getValue(MergedAnnotation.VALUE, String.class) + .orElse("src/main/webapp"); } private boolean isWebEnvironmentSupported(MergedContextConfiguration mergedConfig) { @@ -232,7 +233,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr return classes; } Class found = new AnnotatedClassFinder(SpringBootConfiguration.class) - .findFromClass(mergedConfig.getTestClass()); + .findFromClass(mergedConfig.getTestClass()); Assert.state(found != null, "Unable to find a @SpringBootConfiguration, you need to use " + "@ContextConfiguration or @SpringBootTest(classes=...) with your test"); logger.info("Found @SpringBootConfiguration " + found.getName() + " for test " + mergedConfig.getTestClass()); @@ -242,7 +243,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr private boolean containsNonTestComponent(Class[] classes) { for (Class candidate : classes) { if (!MergedAnnotations.from(candidate, SearchStrategy.INHERITED_ANNOTATIONS) - .isPresent(TestConfiguration.class)) { + .isPresent(TestConfiguration.class)) { return true; } } @@ -328,8 +329,9 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr protected void verifyConfiguration(Class testClass) { SpringBootTest springBootTest = getAnnotation(testClass); - if (springBootTest != null && isListeningOnPort(springBootTest.webEnvironment()) && MergedAnnotations - .from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).isPresent(WebAppConfiguration.class)) { + if (springBootTest != null && isListeningOnPort(springBootTest.webEnvironment()) + && MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .isPresent(WebAppConfiguration.class)) { throw new IllegalStateException("@WebAppConfiguration should only be used " + "with @SpringBootTest when @SpringBootTest is configured with a " + "mock web environment. Please remove @WebAppConfiguration or reconfigure @SpringBootTest."); 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..d9a9f4a2eb 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -223,7 +223,7 @@ public class ApplicationContextAssert throwAssertionError(contextFailedToStartWhenExpecting("to get beans names with type:%n <%s>", type)); } return Assertions.assertThat(getApplicationContext().getBeanNamesForType(type)) - .as("Bean names of type <%s> from <%s>", type, getApplicationContext()); + .as("Bean names of type <%s> from <%s>", type, getApplicationContext()); } /** @@ -359,8 +359,8 @@ public class ApplicationContextAssert "%nExpecting:%n <%s>%nto contain a bean of name:%n <%s> (%s)%nbut found:%n <%s> of type <%s>", getApplicationContext(), name, type, bean, bean.getClass())); } - return Assertions.assertThat((T) bean).as("Bean of name <%s> and type <%s> from <%s>", name, type, - getApplicationContext()); + return Assertions.assertThat((T) bean) + .as("Bean of name <%s> and type <%s> from <%s>", name, type, getApplicationContext()); } private Object findBean(String name) { @@ -411,7 +411,7 @@ public class ApplicationContextAssert throwAssertionError(contextFailedToStartWhenExpecting("to get beans of type:%n <%s>", type)); } return Assertions.assertThat(scope.getBeansOfType(getApplicationContext(), type)) - .as("Beans of type <%s> from <%s>", type, getApplicationContext()); + .as("Beans of type <%s> from <%s>", type, getApplicationContext()); } /** 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..91f41839a8 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -96,9 +96,9 @@ class AssertProviderApplicationContextInvocationHandler implements InvocationHan + this.startupFailure.getClass().getName() + "]"; } ToStringCreator builder = new ToStringCreator(this.applicationContext) - .append("id", this.applicationContext.getId()) - .append("applicationName", this.applicationContext.getApplicationName()) - .append("beanDefinitionCount", this.applicationContext.getBeanDefinitionCount()); + .append("id", this.applicationContext.getId()) + .append("applicationName", this.applicationContext.getApplicationName()) + .append("beanDefinitionCount", this.applicationContext.getBeanDefinitionCount()); return "Started application " + builder; } 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 e03cd6652a..82077b5d2d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -441,10 +441,10 @@ public abstract class AbstractApplicationContextRunner extends AbstractJsonMarshalTester { @Override protected JsonContent getJsonContent(String json) { - Configuration configuration = Configuration.builder().jsonProvider(new JacksonJsonProvider(this.objectMapper)) - .mappingProvider(new JacksonMappingProvider(this.objectMapper)).build(); + Configuration configuration = Configuration.builder() + .jsonProvider(new JacksonJsonProvider(this.objectMapper)) + .mappingProvider(new JacksonMappingProvider(this.objectMapper)) + .build(); return new JsonContent<>(getResourceLoadClass(), getType(), json, configuration); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java index dd6591932a..95175109a7 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,10 +67,12 @@ class DefinitionsParser { private void parseElement(AnnotatedElement element, Class source) { MergedAnnotations annotations = MergedAnnotations.from(element, SearchStrategy.SUPERCLASS); - annotations.stream(MockBean.class).map(MergedAnnotation::synthesize) - .forEach((annotation) -> parseMockBeanAnnotation(annotation, element, source)); - annotations.stream(SpyBean.class).map(MergedAnnotation::synthesize) - .forEach((annotation) -> parseSpyBeanAnnotation(annotation, element, source)); + annotations.stream(MockBean.class) + .map(MergedAnnotation::synthesize) + .forEach((annotation) -> parseMockBeanAnnotation(annotation, element, source)); + annotations.stream(SpyBean.class) + .map(MergedAnnotation::synthesize) + .forEach((annotation) -> parseSpyBeanAnnotation(annotation, element, source)); } private void parseMockBeanAnnotation(MockBean annotation, AnnotatedElement element, Class source) { diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java index 8b874e0618..ff6cdff238 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -129,9 +129,13 @@ class MockDefinition extends Definition { @Override public String toString() { - return new ToStringCreator(this).append("name", getName()).append("typeToMock", this.typeToMock) - .append("extraInterfaces", this.extraInterfaces).append("answer", this.answer) - .append("serializable", this.serializable).append("reset", getReset()).toString(); + return new ToStringCreator(this).append("name", getName()) + .append("typeToMock", this.typeToMock) + .append("extraInterfaces", this.extraInterfaces) + .append("answer", this.answer) + .append("serializable", this.serializable) + .append("reset", getReset()) + .toString(); } T createMock() { 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..f5d0e0ee3e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -83,7 +83,7 @@ public class MockitoPostProcessor implements InstantiationAwareBeanPostProcessor private static final String BEAN_NAME = MockitoPostProcessor.class.getName(); private static final String CONFIGURATION_CLASS_ATTRIBUTE = Conventions - .getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "configurationClass"); + .getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "configurationClass"); private static final BeanNameGenerator beanNameGenerator = new DefaultBeanNameGenerator(); 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..1e316e6fb0 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -108,7 +108,7 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener parser.parse(testContext.getTestClass()); if (!parser.getDefinitions().isEmpty()) { MockitoPostProcessor postProcessor = testContext.getApplicationContext() - .getBean(MockitoPostProcessor.class); + .getBean(MockitoPostProcessor.class); for (Definition definition : parser.getDefinitions()) { Field field = parser.getField(definition); if (field != null) { diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java index dbfc28f636..947bdf1ada 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,8 +79,10 @@ class SpyDefinition extends Definition { @Override public String toString() { - return new ToStringCreator(this).append("name", getName()).append("typeToSpy", this.typeToSpy) - .append("reset", getReset()).toString(); + return new ToStringCreator(this).append("name", getName()) + .append("typeToSpy", this.typeToSpy) + .append("reset", getReset()) + .toString(); } T createSpy(Object instance) { 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..5c88f408ff 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ class SpringBootTestRandomPortEnvironmentPostProcessor implements EnvironmentPos @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { MapPropertySource source = (MapPropertySource) environment.getPropertySources() - .get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); + .get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); if (source == null || isTestServerPortFixed(source, environment) || isTestManagementPortConfigured(source)) { return; } @@ -70,10 +70,14 @@ class SpringBootTestRandomPortEnvironmentPostProcessor implements EnvironmentPos } private Integer getPropertyAsInteger(ConfigurableEnvironment environment, String property, Integer defaultValue) { - return environment.getPropertySources().stream().filter( - (source) -> !source.getName().equals(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME)) - .map((source) -> getPropertyAsInteger(source, property, environment)).filter(Objects::nonNull) - .findFirst().orElse(defaultValue); + return environment.getPropertySources() + .stream() + .filter((source) -> !source.getName() + .equals(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME)) + .map((source) -> getPropertyAsInteger(source, property, environment)) + .filter(Objects::nonNull) + .findFirst() + .orElse(defaultValue); } private Integer getPropertyAsInteger(PropertySource source, String property, 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 8c93661e1b..18a815cb77 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 @@ -135,7 +135,7 @@ public class TestRestTemplate { ClientHttpRequestFactory requestFactory = builder.buildRequestFactory(); if (requestFactory instanceof HttpComponentsClientHttpRequestFactory) { builder = builder - .requestFactory(() -> new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions)); + .requestFactory(() -> new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions)); } } if (username != null || password != null) { @@ -952,12 +952,12 @@ public class TestRestTemplate { if (entity instanceof UriTemplateRequestEntity) { UriTemplateRequestEntity templatedUriEntity = (UriTemplateRequestEntity) entity; if (templatedUriEntity.getVars() != null) { - return this.restTemplate.getUriTemplateHandler().expand(templatedUriEntity.getUriTemplate(), - templatedUriEntity.getVars()); + return this.restTemplate.getUriTemplateHandler() + .expand(templatedUriEntity.getUriTemplate(), templatedUriEntity.getVars()); } else if (templatedUriEntity.getVarsMap() != null) { - return this.restTemplate.getUriTemplateHandler().expand(templatedUriEntity.getUriTemplate(), - templatedUriEntity.getVarsMap()); + return this.restTemplate.getUriTemplateHandler() + .expand(templatedUriEntity.getUriTemplate(), templatedUriEntity.getVarsMap()); } throw new IllegalStateException( "No variables specified for URI template: " + templatedUriEntity.getUriTemplate()); @@ -1025,8 +1025,10 @@ public class TestRestTemplate { } protected RequestConfig getRequestConfig() { - Builder builder = RequestConfig.custom().setCookieSpec(this.cookieSpec).setAuthenticationEnabled(false) - .setRedirectsEnabled(this.enableRedirects); + Builder builder = RequestConfig.custom() + .setCookieSpec(this.cookieSpec) + .setAuthenticationEnabled(false) + .setRedirectsEnabled(this.enableRedirects); return builder.build(); } 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..7afb4b5e08 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer { public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedContextConfiguration) { SpringBootTest springBootTest = TestContextAnnotationUtils - .findMergedAnnotation(mergedContextConfiguration.getTestClass(), SpringBootTest.class); + .findMergedAnnotation(mergedContextConfiguration.getTestClass(), SpringBootTest.class); if (springBootTest.webEnvironment().isEmbedded()) { registerTestRestTemplate(context); } @@ -143,7 +143,7 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer { private boolean isSslEnabled(ApplicationContext context) { try { AbstractServletWebServerFactory webServerFactory = context - .getBean(AbstractServletWebServerFactory.class); + .getBean(AbstractServletWebServerFactory.class); return webServerFactory.getSsl() != null && webServerFactory.getSsl().isEnabled(); } catch (NoSuchBeanDefinitionException ex) { 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..3b9d6086d7 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -208,7 +208,7 @@ class WebTestClientContextCustomizer implements ContextCustomizer { private boolean isSslEnabled(ApplicationContext context) { try { AbstractReactiveWebServerFactory webServerFactory = context - .getBean(AbstractReactiveWebServerFactory.class); + .getBean(AbstractReactiveWebServerFactory.class); return webServerFactory.getSsl() != null && webServerFactory.getSsl().isEnabled(); } catch (NoSuchBeanDefinitionException ex) { @@ -218,7 +218,8 @@ class WebTestClientContextCustomizer implements ContextCustomizer { private void customizeWebTestClientBuilder(WebTestClient.Builder clientBuilder, ApplicationContext context) { for (WebTestClientBuilderCustomizer customizer : context - .getBeansOfType(WebTestClientBuilderCustomizer.class).values()) { + .getBeansOfType(WebTestClientBuilderCustomizer.class) + .values()) { customizer.customize(clientBuilder); } } @@ -226,9 +227,10 @@ class WebTestClientContextCustomizer implements ContextCustomizer { private void customizeWebTestClientCodecs(WebTestClient.Builder clientBuilder, ApplicationContext context) { Collection codecCustomizers = context.getBeansOfType(CodecCustomizer.class).values(); if (!CollectionUtils.isEmpty(codecCustomizers)) { - clientBuilder.exchangeStrategies(ExchangeStrategies.builder().codecs( - (codecs) -> codecCustomizers.forEach((codecCustomizer) -> codecCustomizer.customize(codecs))) - .build()); + clientBuilder.exchangeStrategies(ExchangeStrategies.builder() + .codecs((codecs) -> codecCustomizers + .forEach((codecCustomizer) -> codecCustomizer.customize(codecs))) + .build()); } } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerFactory.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerFactory.java index e41fab8608..d8547732e5 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerFactory.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ class WebTestClientContextCustomizerFactory implements ContextCustomizerFactory reactorClientPresent = ClassUtils.isPresent("reactor.netty.http.client.HttpClient", loader); jettyClientPresent = ClassUtils.isPresent("org.eclipse.jetty.client.HttpClient", loader); httpComponentsClientPresent = ClassUtils - .isPresent("org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient", loader) + .isPresent("org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient", loader) && ClassUtils.isPresent("org.apache.hc.core5.reactive.ReactiveDataConsumer", loader); webClientPresent = ClassUtils.isPresent("org.springframework.web.reactive.function.client.WebClient", loader); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests.java index 24fa63ae5e..288e7b2888 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,8 +69,15 @@ abstract class AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests { @Test void runAndTestHttpEndpoint() { assertThat(this.port).isNotEqualTo(8080).isNotEqualTo(0); - WebTestClient.bindToServer().baseUrl("http://localhost:" + this.port).responseTimeout(Duration.ofMinutes(5)) - .build().get().uri("/").exchange().expectBody(String.class).isEqualTo("Hello World"); + WebTestClient.bindToServer() + .baseUrl("http://localhost:" + this.port) + .responseTimeout(Duration.ofMinutes(5)) + .build() + .get() + .uri("/") + .exchange() + .expectBody(String.class) + .isEqualTo("Hello World"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java index 02836265b3..7b44dd881f 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,13 +37,13 @@ class AnnotatedClassFinderTests { @Test void findFromClassWhenSourceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.finder.findFromClass((Class) null)) - .withMessageContaining("Source must not be null"); + .withMessageContaining("Source must not be null"); } @Test void findFromPackageWhenSourceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.finder.findFromPackage((String) null)) - .withMessageContaining("Source must not be null"); + .withMessageContaining("Source must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java index a488d433e4..4f0eede1c7 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ class FilteredClassLoaderTests { try (FilteredClassLoader classLoader = new FilteredClassLoader( FilteredClassLoaderTests.class.getPackage().getName())) { assertThatExceptionOfType(ClassNotFoundException.class) - .isThrownBy(() -> Class.forName(getClass().getName(), false, classLoader)); + .isThrownBy(() -> Class.forName(getClass().getName(), false, classLoader)); } } @@ -52,7 +52,7 @@ class FilteredClassLoaderTests { void loadClassWhenFilteredOnClassShouldThrowClassNotFound() throws Exception { try (FilteredClassLoader classLoader = new FilteredClassLoader(FilteredClassLoaderTests.class)) { assertThatExceptionOfType(ClassNotFoundException.class) - .isThrownBy(() -> Class.forName(getClass().getName(), false, classLoader)); + .isThrownBy(() -> Class.forName(getClass().getName(), false, classLoader)); } } @@ -117,7 +117,7 @@ class FilteredClassLoaderTests { Class hiddenClass = FilteredClassLoaderTests.class; try (FilteredClassLoader classLoader = new FilteredClassLoader(hiddenClass)) { assertThatIllegalArgumentException() - .isThrownBy(() -> classLoader.publicDefineClass(hiddenClass.getName(), new byte[] {}, null)); + .isThrownBy(() -> classLoader.publicDefineClass(hiddenClass.getName(), new byte[] {}, null)); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryIntegrationTests.java index a1ce41e80d..16219c6060 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ class ImportsContextCustomizerFactoryIntegrationTests { @Test void testItselfIsNotABean() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(getClass())); + .isThrownBy(() -> this.context.getBean(getClass())); } @Component diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java index 125572fc5c..c6d2e53a83 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,8 +77,8 @@ class ImportsContextCustomizerFactoryTests { @Test void getContextCustomizerWhenClassHasBeanMethodsShouldThrowException() { assertThatIllegalStateException() - .isThrownBy(() -> this.factory.createContextCustomizer(TestWithImportAndBeanMethod.class, null)) - .withMessageContaining("Test classes cannot include @Bean methods"); + .isThrownBy(() -> this.factory.createContextCustomizer(TestWithImportAndBeanMethod.class, null)) + .withMessageContaining("Test classes cannot include @Bean methods"); } @Test @@ -93,7 +93,7 @@ class ImportsContextCustomizerFactoryTests { @Test void selfAnnotatingAnnotationDoesNotCauseStackOverflow() { assertThat(this.factory.createContextCustomizer(TestWithImportAndSelfAnnotatingAnnotation.class, null)) - .isNotNull(); + .isNotNull(); } static class TestWithNoImport { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java index 28673bb532..f047bf9840 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,37 +47,37 @@ class ImportsContextCustomizerTests { @Test void importSelectorsCouldUseAnyAnnotations() { assertThat(new ImportsContextCustomizer(FirstImportSelectorAnnotatedClass.class)) - .isNotEqualTo(new ImportsContextCustomizer(SecondImportSelectorAnnotatedClass.class)); + .isNotEqualTo(new ImportsContextCustomizer(SecondImportSelectorAnnotatedClass.class)); } @Test void determinableImportSelector() { assertThat(new ImportsContextCustomizer(FirstDeterminableImportSelectorAnnotatedClass.class)) - .isEqualTo(new ImportsContextCustomizer(SecondDeterminableImportSelectorAnnotatedClass.class)); + .isEqualTo(new ImportsContextCustomizer(SecondDeterminableImportSelectorAnnotatedClass.class)); } @Test void customizersForTestClassesWithDifferentKotlinMetadataAreEqual() { assertThat(new ImportsContextCustomizer(FirstKotlinAnnotatedTestClass.class)) - .isEqualTo(new ImportsContextCustomizer(SecondKotlinAnnotatedTestClass.class)); + .isEqualTo(new ImportsContextCustomizer(SecondKotlinAnnotatedTestClass.class)); } @Test void customizersForTestClassesWithDifferentSpockFrameworkAnnotationsAreEqual() { assertThat(new ImportsContextCustomizer(FirstSpockFrameworkAnnotatedTestClass.class)) - .isEqualTo(new ImportsContextCustomizer(SecondSpockFrameworkAnnotatedTestClass.class)); + .isEqualTo(new ImportsContextCustomizer(SecondSpockFrameworkAnnotatedTestClass.class)); } @Test void customizersForTestClassesWithDifferentSpockLangAnnotationsAreEqual() { assertThat(new ImportsContextCustomizer(FirstSpockLangAnnotatedTestClass.class)) - .isEqualTo(new ImportsContextCustomizer(SecondSpockLangAnnotatedTestClass.class)); + .isEqualTo(new ImportsContextCustomizer(SecondSpockLangAnnotatedTestClass.class)); } @Test void customizersForTestClassesWithDifferentJUnitAnnotationsAreEqual() { assertThat(new ImportsContextCustomizer(FirstJUnitAnnotatedTestClass.class)) - .isEqualTo(new ImportsContextCustomizer(SecondJUnitAnnotatedTestClass.class)); + .isEqualTo(new ImportsContextCustomizer(SecondJUnitAnnotatedTestClass.class)); } @Import(TestImportSelector.class) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java index 0ca328598c..9810879e79 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -127,7 +127,7 @@ class SpringBootContextLoaderTests { @Test void testPropertyValuesShouldTakePrecedenceWhenInlinedPropertiesPresentAndProfilesActive() { TestContext context = new ExposedTestContextManager(ActiveProfileWithInlinedProperties.class) - .getExposedTestContext(); + .getExposedTestContext(); StandardEnvironment environment = (StandardEnvironment) context.getApplicationContext().getEnvironment(); TestPropertyValues.of("key=thisValue").applyTo(environment); assertThat(environment.getProperty("key")).isEqualTo("thisValue"); @@ -138,9 +138,11 @@ class SpringBootContextLoaderTests { void propertySourceOrdering() { TestContext context = new ExposedTestContextManager(PropertySourceOrdering.class).getExposedTestContext(); ConfigurableEnvironment environment = (ConfigurableEnvironment) context.getApplicationContext() - .getEnvironment(); - List names = environment.getPropertySources().stream().map(PropertySource::getName) - .collect(Collectors.toList()); + .getEnvironment(); + List names = environment.getPropertySources() + .stream() + .map(PropertySource::getName) + .collect(Collectors.toList()); String last = names.remove(names.size() - 1); assertThat(names).containsExactly("configurationProperties", "Inlined Test Properties", "commandLineArgs", "servletConfigInitParams", "servletContextInitParams", "systemProperties", "systemEnvironment", @@ -151,14 +153,14 @@ class SpringBootContextLoaderTests { @Test void whenEnvironmentChangesWebApplicationTypeToNoneThenContextTypeChangesAccordingly() { TestContext context = new ExposedTestContextManager(ChangingWebApplicationTypeToNone.class) - .getExposedTestContext(); + .getExposedTestContext(); assertThat(context.getApplicationContext()).isNotInstanceOf(WebApplicationContext.class); } @Test void whenEnvironmentChangesWebApplicationTypeToReactiveThenContextTypeChangesAccordingly() { TestContext context = new ExposedTestContextManager(ChangingWebApplicationTypeToReactive.class) - .getExposedTestContext(); + .getExposedTestContext(); assertThat(context.getApplicationContext()).isInstanceOf(GenericReactiveWebApplicationContext.class); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java index 97d4481755..c5ec1f9a17 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,7 +63,7 @@ class SpringBootTestWebEnvironmentMockTests { @Test void validateWebApplicationContextIsSet() { WebApplicationContext fromServletContext = WebApplicationContextUtils - .getWebApplicationContext(this.servletContext); + .getWebApplicationContext(this.servletContext); assertThat(fromServletContext).isSameAs(this.context); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java index 2f85db9af4..00cd359c85 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ class SpringBootTestWebEnvironmentRandomPortTests extends AbstractSpringBootTest @Test void testRestTemplateShouldUseBuilder() { assertThat(getRestTemplate().getRestTemplate().getMessageConverters()) - .hasAtLeastOneElementOfType(MyConverter.class); + .hasAtLeastOneElementOfType(MyConverter.class); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithClassesIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithClassesIntegrationTests.java index c2a32af3fb..3ed88de6be 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithClassesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithClassesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ class SpringBootTestWithClassesIntegrationTests { void injectsOnlyConfig() { assertThat(this.context.getBean(Config.class)).isNotNull(); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(AdditionalConfig.class)); + .isThrownBy(() -> this.context.getBean(AdditionalConfig.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java index a52fd7b831..0983f849b1 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ class SpringBootTestWithContextConfigurationIntegrationTests { void injectsOnlyConfig() { assertThat(this.context.getBean(Config.class)).isNotNull(); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(AdditionalConfig.class)); + .isThrownBy(() -> this.context.getBean(AdditionalConfig.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java index 2a859b2b8a..9820b5a2ed 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,7 +65,7 @@ class SpringBootTestWithTestPropertySourceTests { @Test void propertyFromPropertySourcePropertiesOverridesPropertyFromPropertySourceLocations() { assertThat(this.config.propertySourceInlinedOverridesPropertySourceLocation) - .isEqualTo("property-source-inlined"); + .isEqualTo("property-source-inlined"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/TestConfigurationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/TestConfigurationTests.java index 1984d4e648..496b676988 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/TestConfigurationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/TestConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,14 +34,14 @@ class TestConfigurationTests { @Test void proxyBeanMethodsIsEnabledByDefault() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(DefaultTestConfiguration.class, Configuration.class); + .getMergedAnnotationAttributes(DefaultTestConfiguration.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(true); } @Test void proxyBeanMethodsCanBeDisabled() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(NoBeanMethodProxyingTestConfiguration.class, Configuration.class); + .getMergedAnnotationAttributes(NoBeanMethodProxyingTestConfiguration.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(false); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java index b77726ec5f..fb89acda2e 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,37 +64,38 @@ class ApplicationContextAssertProviderTests { void getWhenTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy( () -> ApplicationContextAssertProvider.get(null, ApplicationContext.class, this.mockContextSupplier)) - .withMessageContaining("Type must not be null"); + .withMessageContaining("Type must not be null"); } @Test void getWhenTypeIsClassShouldThrowException() { assertThatIllegalArgumentException().isThrownBy( () -> ApplicationContextAssertProvider.get(null, ApplicationContext.class, this.mockContextSupplier)) - .withMessageContaining("Type must not be null"); + .withMessageContaining("Type must not be null"); } @Test void getWhenContextTypeIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContextClass.class, - ApplicationContext.class, this.mockContextSupplier)) - .withMessageContaining("Type must be an interface"); + .isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContextClass.class, + ApplicationContext.class, this.mockContextSupplier)) + .withMessageContaining("Type must be an interface"); } @Test void getWhenContextTypeIsClassShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy(() -> ApplicationContextAssertProvider - .get(TestAssertProviderApplicationContext.class, null, this.mockContextSupplier)) - .withMessageContaining("ContextType must not be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, null, + this.mockContextSupplier)) + .withMessageContaining("ContextType must not be null"); } @Test void getWhenSupplierIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, - StaticApplicationContext.class, this.mockContextSupplier)) - .withMessageContaining("ContextType must be an interface"); + .isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, + StaticApplicationContext.class, this.mockContextSupplier)) + .withMessageContaining("ContextType must be an interface"); } @Test @@ -109,8 +110,9 @@ class ApplicationContextAssertProviderTests { void getWhenContextFailsShouldReturnProxyThatThrowsExceptions() { ApplicationContextAssertProvider context = get(this.startupFailureSupplier); assertThat((Object) context).isNotNull(); - assertThatIllegalStateException().isThrownBy(() -> context.getBean("foo")).withCause(this.startupFailure) - .withMessageContaining("failed to start"); + assertThatIllegalStateException().isThrownBy(() -> context.getBean("foo")) + .withCause(this.startupFailure) + .withMessageContaining("failed to start"); } @Test @@ -123,7 +125,8 @@ class ApplicationContextAssertProviderTests { void getSourceContextWhenContextFailsShouldThrowException() { ApplicationContextAssertProvider context = get(this.startupFailureSupplier); assertThatIllegalStateException().isThrownBy(context::getSourceApplicationContext) - .withCause(this.startupFailure).withMessageContaining("failed to start"); + .withCause(this.startupFailure) + .withMessageContaining("failed to start"); } @Test @@ -136,8 +139,9 @@ class ApplicationContextAssertProviderTests { void getSourceContextOfTypeWhenContextFailsToStartShouldThrowException() { ApplicationContextAssertProvider context = get(this.startupFailureSupplier); assertThatIllegalStateException() - .isThrownBy(() -> context.getSourceApplicationContext(ApplicationContext.class)) - .withCause(this.startupFailure).withMessageContaining("failed to start"); + .isThrownBy(() -> context.getSourceApplicationContext(ApplicationContext.class)) + .withCause(this.startupFailure) + .withMessageContaining("failed to start"); } @Test @@ -172,7 +176,7 @@ class ApplicationContextAssertProviderTests { void toStringWhenContextStartsShouldReturnSimpleString() { ApplicationContextAssertProvider context = get(this.mockContextSupplier); assertThat(context.toString()).startsWith("Started application [ConfigurableApplicationContext.MockitoMock") - .endsWith("id = [null], applicationName = [null], beanDefinitionCount = 0]"); + .endsWith("id = [null], applicationName = [null], beanDefinitionCount = 0]"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java index c3961558be..da83cadffa 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,7 +62,7 @@ class ApplicationContextAssertTests { @Test void createWhenApplicationContextIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ApplicationContextAssert<>(null, null)) - .withMessageContaining("ApplicationContext must not be null"); + .withMessageContaining("ApplicationContext must not be null"); } @Test @@ -84,15 +84,15 @@ class ApplicationContextAssertTests { @Test void hasBeanWhenHasNoBeanShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).hasBean("foo")) - .withMessageContaining("no such bean"); + .isThrownBy(() -> assertThat(getAssert(this.context)).hasBean("foo")) + .withMessageContaining("no such bean"); } @Test void hasBeanWhenNotStartedShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).hasBean("foo")) - .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); + .isThrownBy(() -> assertThat(getAssert(this.failure)).hasBean("foo")) + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -104,8 +104,8 @@ class ApplicationContextAssertTests { @Test void hasSingleBeanWhenHasNoBeansShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) - .withMessageContaining("to have a single bean of type"); + .isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) + .withMessageContaining("to have a single bean of type"); } @Test @@ -113,16 +113,16 @@ class ApplicationContextAssertTests { this.context.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) - .withMessageContaining("but found:"); + .isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) + .withMessageContaining("but found:"); } @Test void hasSingleBeanWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).hasSingleBean(Foo.class)) - .withMessageContaining("to have a single bean of type") - .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); + .isThrownBy(() -> assertThat(getAssert(this.failure)).hasSingleBean(Foo.class)) + .withMessageContaining("to have a single bean of type") + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -130,8 +130,8 @@ class ApplicationContextAssertTests { this.parent.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) - .withMessageContaining("but found:"); + .isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) + .withMessageContaining("but found:"); } @Test @@ -150,24 +150,24 @@ class ApplicationContextAssertTests { void doesNotHaveBeanOfTypeWhenHasBeanOfTypeShouldFail() { this.context.registerSingleton("foo", Foo.class); assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class)) - .withMessageContaining("but found"); + .isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class)) + .withMessageContaining("but found"); } @Test void doesNotHaveBeanOfTypeWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean(Foo.class)) - .withMessageContaining("not to have any beans of type") - .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); + .isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean(Foo.class)) + .withMessageContaining("not to have any beans of type") + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test void doesNotHaveBeanOfTypeWhenInParentShouldFail() { this.parent.registerSingleton("foo", Foo.class); assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class)) - .withMessageContaining("but found"); + .isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class)) + .withMessageContaining("but found"); } @Test @@ -185,15 +185,16 @@ class ApplicationContextAssertTests { void doesNotHaveBeanOfNameWhenHasBeanOfTypeShouldFail() { this.context.registerSingleton("foo", Foo.class); assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean("foo")) - .withMessageContaining("but found"); + .isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean("foo")) + .withMessageContaining("but found"); } @Test void doesNotHaveBeanOfNameWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo")) - .withMessageContaining("not to have any beans of name").withMessageContaining("failed to start"); + .isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo")) + .withMessageContaining("not to have any beans of name") + .withMessageContaining("failed to start"); } @Test @@ -211,9 +212,9 @@ class ApplicationContextAssertTests { @Test void getBeanNamesWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo")) - .withMessageContaining("not to have any beans of name") - .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); + .isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo")) + .withMessageContaining("not to have any beans of name") + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -232,8 +233,8 @@ class ApplicationContextAssertTests { this.context.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).getBean(Foo.class)) - .withMessageContaining("but found"); + .isThrownBy(() -> assertThat(getAssert(this.context)).getBean(Foo.class)) + .withMessageContaining("but found"); } @Test @@ -246,9 +247,9 @@ class ApplicationContextAssertTests { @Test void getBeanOfTypeWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean(Foo.class)) - .withMessageContaining("to contain bean of type") - .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); + .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean(Foo.class)) + .withMessageContaining("to contain bean of type") + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -268,8 +269,8 @@ class ApplicationContextAssertTests { this.parent.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).getBean(Foo.class)) - .withMessageContaining("but found"); + .isThrownBy(() -> assertThat(getAssert(this.context)).getBean(Foo.class)) + .withMessageContaining("but found"); } @Test @@ -293,9 +294,9 @@ class ApplicationContextAssertTests { @Test void getBeanOfNameWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo")) - .withMessageContaining("to contain a bean of name") - .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); + .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo")) + .withMessageContaining("to contain a bean of name") + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -313,16 +314,16 @@ class ApplicationContextAssertTests { void getBeanOfNameAndTypeWhenHasNoBeanOfNameButDifferentTypeShouldFail() { this.context.registerSingleton("foo", Foo.class); assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).getBean("foo", String.class)) - .withMessageContaining("of type"); + .isThrownBy(() -> assertThat(getAssert(this.context)).getBean("foo", String.class)) + .withMessageContaining("of type"); } @Test void getBeanOfNameAndTypeWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo", Foo.class)) - .withMessageContaining("to contain a bean of name") - .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); + .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo", Foo.class)) + .withMessageContaining("to contain a bean of name") + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -340,9 +341,9 @@ class ApplicationContextAssertTests { @Test void getBeansWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).getBeans(Foo.class)) - .withMessageContaining("to get beans of type") - .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); + .isThrownBy(() -> assertThat(getAssert(this.failure)).getBeans(Foo.class)) + .withMessageContaining("to get beans of type") + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -367,8 +368,8 @@ class ApplicationContextAssertTests { @Test void getFailureWhenDidNotFailShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).getFailure()) - .withMessageContaining("context started"); + .isThrownBy(() -> assertThat(getAssert(this.context)).getFailure()) + .withMessageContaining("context started"); } @Test @@ -379,16 +380,16 @@ class ApplicationContextAssertTests { @Test void hasFailedWhenNotFailedShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).hasFailed()) - .withMessageContaining("to have failed"); + .isThrownBy(() -> assertThat(getAssert(this.context)).hasFailed()) + .withMessageContaining("to have failed"); } @Test void hasNotFailedWhenFailedShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).hasNotFailed()) - .withMessageContaining("to have not failed") - .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); + .isThrownBy(() -> assertThat(getAssert(this.failure)).hasNotFailed()) + .withMessageContaining("to have not failed") + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableApplicationContextTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableApplicationContextTests.java index 7ab204f96f..91189ce2a9 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableApplicationContextTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ class AssertableApplicationContextTests { @Test void getShouldReturnProxy() { AssertableApplicationContext context = AssertableApplicationContext - .get(() -> mock(ConfigurableApplicationContext.class)); + .get(() -> mock(ConfigurableApplicationContext.class)); assertThat(context).isInstanceOf(ConfigurableApplicationContext.class); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableReactiveWebApplicationContextTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableReactiveWebApplicationContextTests.java index 8e84cbf9b0..b84b776bbd 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableReactiveWebApplicationContextTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableReactiveWebApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ class AssertableReactiveWebApplicationContextTests { @Test void getShouldReturnProxy() { AssertableReactiveWebApplicationContext context = AssertableReactiveWebApplicationContext - .get(() -> mock(ConfigurableReactiveWebApplicationContext.class)); + .get(() -> mock(ConfigurableReactiveWebApplicationContext.class)); assertThat(context).isInstanceOf(ConfigurableReactiveWebApplicationContext.class); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableWebApplicationContextTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableWebApplicationContextTests.java index 2387d7f419..53873f9c47 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableWebApplicationContextTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableWebApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ class AssertableWebApplicationContextTests { @Test void getShouldReturnProxy() { AssertableWebApplicationContext context = AssertableWebApplicationContext - .get(() -> mock(ConfigurableWebApplicationContext.class)); + .get(() -> mock(ConfigurableWebApplicationContext.class)); assertThat(context).isInstanceOf(ConfigurableWebApplicationContext.class); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java index dc20356094..db724a374a 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,10 +43,10 @@ class SpringBootTestContextBootstrapperTests { @Test void springBootTestWithANonMockWebEnvironmentAndWebAppConfigurationFailsFast() { assertThatIllegalStateException() - .isThrownBy(() -> buildTestContext(SpringBootTestNonMockWebEnvironmentAndWebAppConfiguration.class)) - .withMessageContaining("@WebAppConfiguration should only be used with " - + "@SpringBootTest when @SpringBootTest is configured with a mock web " - + "environment. Please remove @WebAppConfiguration or reconfigure @SpringBootTest."); + .isThrownBy(() -> buildTestContext(SpringBootTestNonMockWebEnvironmentAndWebAppConfiguration.class)) + .withMessageContaining("@WebAppConfiguration should only be used with " + + "@SpringBootTest when @SpringBootTest is configured with a mock web " + + "environment. Please remove @WebAppConfiguration or reconfigure @SpringBootTest."); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java index 759ea2de78..868f3fdd7f 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class TestTypeExcludeFilterTests { @Test void matchesJUnit4TestClass() throws Exception { assertThat(this.filter.match(getMetadataReader(TestTypeExcludeFilterTests.class), this.metadataReaderFactory)) - .isTrue(); + .isTrue(); } @Test @@ -53,13 +53,13 @@ class TestTypeExcludeFilterTests { @Test void matchesJUnitJupiterRepeatedTestClass() throws Exception { assertThat(this.filter.match(getMetadataReader(JupiterRepeatedTestExample.class), this.metadataReaderFactory)) - .isTrue(); + .isTrue(); } @Test void matchesJUnitJupiterTestFactoryClass() throws Exception { assertThat(this.filter.match(getMetadataReader(JupiterTestFactoryExample.class), this.metadataReaderFactory)) - .isTrue(); + .isTrue(); } @Test @@ -70,19 +70,22 @@ class TestTypeExcludeFilterTests { @Test void matchesNestedConfigurationClassWithoutTestMethodsIfItHasRunWith() throws Exception { assertThat(this.filter.match(getMetadataReader(AbstractTestWithConfigAndRunWith.Config.class), - this.metadataReaderFactory)).isTrue(); + this.metadataReaderFactory)) + .isTrue(); } @Test void matchesNestedConfigurationClassWithoutTestMethodsIfItHasExtendWith() throws Exception { assertThat(this.filter.match(getMetadataReader(AbstractJupiterTestWithConfigAndExtendWith.Config.class), - this.metadataReaderFactory)).isTrue(); + this.metadataReaderFactory)) + .isTrue(); } @Test void matchesNestedConfigurationClassWithoutTestMethodsIfItHasTestable() throws Exception { assertThat(this.filter.match(getMetadataReader(AbstractJupiterTestWithConfigAndTestable.Config.class), - this.metadataReaderFactory)).isTrue(); + this.metadataReaderFactory)) + .isTrue(); } @Test @@ -98,7 +101,8 @@ class TestTypeExcludeFilterTests { @Test void matchesNestedConfigurationClassWithoutTestNgAnnotation() throws Exception { assertThat(this.filter.match(getMetadataReader(AbstractTestNgTestWithConfig.Config.class), - this.metadataReaderFactory)).isTrue(); + this.metadataReaderFactory)) + .isTrue(); } private MetadataReader getMetadataReader(Class source) throws IOException { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java index 2fcf93ff6c..8e9033e805 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,7 +71,7 @@ abstract class AbstractApplicationContextRunnerTests assertThat(System.getProperties()).containsEntry(key, "value")); + .run((context) -> assertThat(System.getProperties()).containsEntry(key, "value")); assertThat(System.getProperties().containsKey(key)).isFalse(); } @@ -79,8 +79,9 @@ abstract class AbstractApplicationContextRunnerTests assertThat(context).hasFailed()); + get().withSystemProperties(key + "=value") + .withUserConfiguration(FailingConfig.class) + .run((context) -> assertThat(context).hasFailed()); assertThat(System.getProperties().containsKey(key)).isFalse(); } @@ -91,7 +92,7 @@ abstract class AbstractApplicationContextRunnerTests assertThat(System.getProperties()).containsEntry(key, "newValue")); + .run((context) -> assertThat(System.getProperties()).containsEntry(key, "newValue")); assertThat(System.getProperties().getProperty(key)).isEqualTo("value"); } finally { @@ -106,7 +107,7 @@ abstract class AbstractApplicationContextRunnerTests assertThat(context).hasBean("foo").hasBean("bar")); + get().withUserConfiguration(FooConfig.class) + .withConfiguration(UserConfigurations.of(BarConfig.class)) + .run((context) -> assertThat(context).hasBean("foo").hasBean("bar")); } @Test @@ -160,30 +162,32 @@ abstract class AbstractApplicationContextRunnerTests assertThatExceptionOfType(ClassNotFoundException.class) - .isThrownBy(() -> ClassUtils.forName(Gson.class.getName(), context.getClassLoader()))); + .run((context) -> assertThatExceptionOfType(ClassNotFoundException.class) + .isThrownBy(() -> ClassUtils.forName(Gson.class.getName(), context.getClassLoader()))); } @Test void runWithClassLoaderShouldSetClassLoaderOnConditionContext() { get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName())) - .withUserConfiguration(ConditionalConfig.class) - .run((context) -> assertThat(context).hasSingleBean(ConditionalConfig.class)); + .withUserConfiguration(ConditionalConfig.class) + .run((context) -> assertThat(context).hasSingleBean(ConditionalConfig.class)); } @Test void consecutiveRunWithFilteredClassLoaderShouldHaveBeanWithLazyProperties() { - get().withClassLoader(new FilteredClassLoader(Gson.class)).withUserConfiguration(LazyConfig.class) - .run((context) -> assertThat(context).hasSingleBean(ExampleBeanWithLazyProperties.class)); + get().withClassLoader(new FilteredClassLoader(Gson.class)) + .withUserConfiguration(LazyConfig.class) + .run((context) -> assertThat(context).hasSingleBean(ExampleBeanWithLazyProperties.class)); - get().withClassLoader(new FilteredClassLoader(Gson.class)).withUserConfiguration(LazyConfig.class) - .run((context) -> assertThat(context).hasSingleBean(ExampleBeanWithLazyProperties.class)); + get().withClassLoader(new FilteredClassLoader(Gson.class)) + .withUserConfiguration(LazyConfig.class) + .run((context) -> assertThat(context).hasSingleBean(ExampleBeanWithLazyProperties.class)); } @Test void thrownRuleWorksWithCheckedException() { get().run((context) -> assertThatIOException().isThrownBy(() -> throwCheckedException("Expected message")) - .withMessageContaining("Expected message")); + .withMessageContaining("Expected message")); } @Test @@ -191,43 +195,48 @@ abstract class AbstractApplicationContextRunnerTests 42).run((context) -> { assertThat(context).hasFailed(); assertThat(context.getStartupFailure()).isInstanceOf(BeanDefinitionStoreException.class) - .hasMessageContaining("Invalid bean definition with name 'foo'") - .hasMessageContaining("@Bean definition illegally overridden by existing bean definition"); + .hasMessageContaining("Invalid bean definition with name 'foo'") + .hasMessageContaining("@Bean definition illegally overridden by existing bean definition"); }); } @Test void runDisablesCircularReferencesByDefault() { get().withUserConfiguration(ExampleConsumerConfiguration.class, ExampleProducerConfiguration.class) - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasRootCauseInstanceOf(BeanCurrentlyInCreationException.class); - }); + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().hasRootCauseInstanceOf(BeanCurrentlyInCreationException.class); + }); } @Test void circularReferencesCanBeAllowed() { get().withAllowCircularReferences(true) - .withUserConfiguration(ExampleConsumerConfiguration.class, ExampleProducerConfiguration.class) - .run((context) -> assertThat(context).hasNotFailed()); + .withUserConfiguration(ExampleConsumerConfiguration.class, ExampleProducerConfiguration.class) + .run((context) -> assertThat(context).hasNotFailed()); } @Test void runWithUserBeanShouldBeRegisteredInOrder() { - get().withAllowBeanDefinitionOverriding(true).withBean(String.class, () -> "one") - .withBean(String.class, () -> "two").withBean(String.class, () -> "three").run((context) -> { - assertThat(context).hasBean("string"); - assertThat(context.getBean("string")).isEqualTo("three"); - }); + get().withAllowBeanDefinitionOverriding(true) + .withBean(String.class, () -> "one") + .withBean(String.class, () -> "two") + .withBean(String.class, () -> "three") + .run((context) -> { + assertThat(context).hasBean("string"); + assertThat(context.getBean("string")).isEqualTo("three"); + }); } @Test void runWithConfigurationsAndUserBeanShouldRegisterUserBeanLast() { - get().withAllowBeanDefinitionOverriding(true).withUserConfiguration(FooConfig.class) - .withBean("foo", String.class, () -> "overridden").run((context) -> { - assertThat(context).hasBean("foo"); - assertThat(context.getBean("foo")).isEqualTo("overridden"); - }); + get().withAllowBeanDefinitionOverriding(true) + .withUserConfiguration(FooConfig.class) + .withBean("foo", String.class, () -> "overridden") + .run((context) -> { + assertThat(context).hasBean("foo"); + assertThat(context.getBean("foo")).isEqualTo("overridden"); + }); } protected abstract T get(); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/ContextConsumerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/ContextConsumerTests.java index 5c19d70a6f..dc3bdb1138 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/ContextConsumerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/ContextConsumerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,7 +60,7 @@ class ContextConsumerTests { ContextConsumer firstConsumer = (context) -> assertThat(predicate.test(42)).isFalse(); ContextConsumer secondConsumer = (context) -> assertThat(predicate.test(24)).isFalse(); assertThatThrownBy(() -> firstConsumer.andThen(secondConsumer).accept(mock(ApplicationContext.class))) - .isInstanceOf(AssertionError.class); + .isInstanceOf(AssertionError.class); then(predicate).should().test(42); then(predicate).shouldHaveNoMoreInteractions(); } @@ -70,7 +70,7 @@ class ContextConsumerTests { ContextConsumer consumer = (context) -> { }; assertThatIllegalArgumentException().isThrownBy(() -> consumer.andThen(null)) - .withMessage("After must not be null"); + .withMessage("After must not be null"); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java index 8f27bf9ebd..87f6d33ffa 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -91,14 +91,14 @@ abstract class AbstractJsonMarshalTesterTests { @Test void createWhenResourceLoadClassIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> createTester(null, ResolvableType.forClass(ExampleObject.class))) - .withMessageContaining("ResourceLoadClass must not be null"); + .isThrownBy(() -> createTester(null, ResolvableType.forClass(ExampleObject.class))) + .withMessageContaining("ResourceLoadClass must not be null"); } @Test void createWhenTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> createTester(getClass(), null)) - .withMessageContaining("Type must not be null"); + .withMessageContaining("Type must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/BasicJsonTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/BasicJsonTesterTests.java index 463d90c142..4e06a8ec05 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/BasicJsonTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/BasicJsonTesterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,7 @@ class BasicJsonTesterTests { @Test void createWhenResourceLoadClassIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new BasicJsonTester(null)) - .withMessageContaining("ResourceLoadClass must not be null"); + .withMessageContaining("ResourceLoadClass must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java index 049e9e0fc4..eebd6569bb 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,8 +44,8 @@ class DuplicateJsonObjectContextCustomizerFactoryTests { @Test void warningForMultipleVersions() { - new DuplicateJsonObjectContextCustomizerFactory().createContextCustomizer(null, null).customizeContext(null, - null); + new DuplicateJsonObjectContextCustomizerFactory().createContextCustomizer(null, null) + .customizeContext(null, null); assertThat(this.output).contains("Found multiple occurrences of org.json.JSONObject on the class path:"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterIntegrationTests.java index d007b5ff1e..ed1aca17d8 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,7 +77,7 @@ class GsonTesterIntegrationTests { void stringLiteral() throws Exception { String stringWithSpecialCharacters = "myString"; assertThat(this.stringJson.write(stringWithSpecialCharacters)).extractingJsonPathStringValue("@") - .isEqualTo(stringWithSpecialCharacters); + .isEqualTo(stringWithSpecialCharacters); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java index 7ca858e7f0..62fe8f3df9 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,14 +37,14 @@ class GsonTesterTests extends AbstractJsonMarshalTesterTests { @Test void initFieldsWhenTestIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> GsonTester.initFields(null, new GsonBuilder().create())) - .withMessageContaining("TestInstance must not be null"); + .withMessageContaining("TestInstance must not be null"); } @Test void initFieldsWhenMarshallerIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> GsonTester.initFields(new InitFieldsTestClass(), (Gson) null)) - .withMessageContaining("Marshaller must not be null"); + .isThrownBy(() -> GsonTester.initFields(new InitFieldsTestClass(), (Gson) null)) + .withMessageContaining("Marshaller must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java index dadf742af0..8aae1238e9 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java @@ -81,7 +81,7 @@ class JacksonTesterIntegrationTests { JacksonTester.initFields(this, new ObjectMapper()); String stringWithSpecialCharacters = "myString"; assertThat(this.stringJson.write(stringWithSpecialCharacters)).extractingJsonPathStringValue("@") - .isEqualTo(stringWithSpecialCharacters); + .isEqualTo(stringWithSpecialCharacters); } @Test @@ -95,7 +95,7 @@ class JacksonTesterIntegrationTests { // restores the symmetry. See gh-15727 String stringWithSpecialCharacters = "\u0006\u007F"; assertThat(this.stringJson.write(stringWithSpecialCharacters)).extractingJsonPathStringValue("@") - .isEqualTo(stringWithSpecialCharacters); + .isEqualTo(stringWithSpecialCharacters); } @Test @@ -105,7 +105,7 @@ class JacksonTesterIntegrationTests { object.setName("Spring"); object.setAge(123); JsonContent content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class) - .write(object); + .write(object); assertThat(content).extractingJsonPathStringValue("@.name").isEqualTo("Spring"); assertThat(content).doesNotHaveJsonPathValue("age"); } @@ -115,7 +115,7 @@ class JacksonTesterIntegrationTests { JacksonTester.initFields(this, JsonMapper.builder().disable(MapperFeature.DEFAULT_VIEW_INCLUSION).build()); ByteArrayResource resource = new ByteArrayResource(JSON.getBytes()); ObjectContent content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class) - .read(resource); + .read(resource); assertThat(content.getObject().getName()).isEqualTo("Spring"); assertThat(content.getObject().getAge()).isEqualTo(0); } @@ -125,7 +125,7 @@ class JacksonTesterIntegrationTests { JacksonTester.initFields(this, JsonMapper.builder().disable(MapperFeature.DEFAULT_VIEW_INCLUSION).build()); Reader reader = new StringReader(JSON); ObjectContent content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class) - .read(reader); + .read(reader); assertThat(content.getObject().getName()).isEqualTo("Spring"); assertThat(content.getObject().getAge()).isEqualTo(0); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java index 67f240ba43..366ba5ae7b 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,14 +36,14 @@ class JacksonTesterTests extends AbstractJsonMarshalTesterTests { @Test void initFieldsWhenTestIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> JacksonTester.initFields(null, new ObjectMapper())) - .withMessageContaining("TestInstance must not be null"); + .withMessageContaining("TestInstance must not be null"); } @Test void initFieldsWhenMarshallerIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> JacksonTester.initFields(new InitFieldsTestClass(), (ObjectMapper) null)) - .withMessageContaining("Marshaller must not be null"); + .isThrownBy(() -> JacksonTester.initFields(new InitFieldsTestClass(), (ObjectMapper) null)) + .withMessageContaining("Marshaller must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java index 5d729cde6e..6448dec304 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,7 +85,7 @@ class JsonContentAssertTests { @Test void isEqualToWhenStringIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(DIFFERENT)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(DIFFERENT)); } @Test @@ -96,7 +96,7 @@ class JsonContentAssertTests { @Test void isEqualToWhenResourcePathIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo("different.json")); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo("different.json")); } @Test @@ -107,7 +107,7 @@ class JsonContentAssertTests { @Test void isEqualToWhenBytesAreNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(DIFFERENT.getBytes())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(DIFFERENT.getBytes())); } @Test @@ -118,7 +118,7 @@ class JsonContentAssertTests { @Test void isEqualToWhenFileIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(createFile(DIFFERENT))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(createFile(DIFFERENT))); } @Test @@ -129,7 +129,7 @@ class JsonContentAssertTests { @Test void isEqualToWhenInputStreamIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(createInputStream(DIFFERENT))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(createInputStream(DIFFERENT))); } @Test @@ -140,7 +140,7 @@ class JsonContentAssertTests { @Test void isEqualToWhenResourceIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(createResource(DIFFERENT))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(createResource(DIFFERENT))); } @Test @@ -151,13 +151,13 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenNullActualShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(null)).isEqualToJson(SOURCE)); + .isThrownBy(() -> assertThat(forJson(null)).isEqualToJson(SOURCE)); } @Test void isEqualToJsonWhenStringIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT)); } @Test @@ -168,7 +168,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenResourcePathIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json")); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json")); } @Test @@ -179,7 +179,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass())); } @Test @@ -190,7 +190,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenBytesAreNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes())); } @Test @@ -201,7 +201,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenFileIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT))); } @Test @@ -212,7 +212,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenInputStreamIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT))); } @Test @@ -223,7 +223,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenResourceIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT))); } @Test @@ -234,7 +234,7 @@ class JsonContentAssertTests { @Test void isStrictlyEqualToJsonWhenStringIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(LENIENT_SAME)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(LENIENT_SAME)); } @Test @@ -245,7 +245,7 @@ class JsonContentAssertTests { @Test void isStrictlyEqualToJsonWhenResourcePathIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json")); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json")); } @Test @@ -256,7 +256,7 @@ class JsonContentAssertTests { @Test void isStrictlyEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json", getClass())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json", getClass())); } @Test @@ -267,7 +267,7 @@ class JsonContentAssertTests { @Test void isStrictlyEqualToJsonWhenBytesAreNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(LENIENT_SAME.getBytes())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(LENIENT_SAME.getBytes())); } @Test @@ -278,7 +278,7 @@ class JsonContentAssertTests { @Test void isStrictlyEqualToJsonWhenFileIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createFile(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createFile(LENIENT_SAME))); } @Test @@ -289,7 +289,7 @@ class JsonContentAssertTests { @Test void isStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createInputStream(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createInputStream(LENIENT_SAME))); } @Test @@ -300,7 +300,7 @@ class JsonContentAssertTests { @Test void isStrictlyEqualToJsonWhenResourceIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createResource(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createResource(LENIENT_SAME))); } @Test @@ -311,7 +311,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenStringIsNotMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT, JSONCompareMode.LENIENT)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT, JSONCompareMode.LENIENT)); } @Test @@ -322,7 +322,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", JSONCompareMode.LENIENT)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", JSONCompareMode.LENIENT)); } @Test @@ -343,8 +343,8 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenBytesAreNotMatchingAndLenientShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), JSONCompareMode.LENIENT)); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), JSONCompareMode.LENIENT)); } @Test @@ -388,7 +388,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenStringIsNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT, COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT, COMPARATOR)); } @Test @@ -399,7 +399,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenResourcePathIsNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", COMPARATOR)); } @Test @@ -410,7 +410,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), COMPARATOR)); } @Test @@ -421,7 +421,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenBytesAreNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), COMPARATOR)); } @Test @@ -432,7 +432,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenFileIsNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT), COMPARATOR)); } @Test @@ -443,7 +443,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), COMPARATOR)); } @Test @@ -454,13 +454,13 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenResourceIsNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT), COMPARATOR)); } @Test void isNotEqualToWhenStringIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(LENIENT_SAME)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(LENIENT_SAME)); } @Test @@ -476,7 +476,7 @@ class JsonContentAssertTests { @Test void isNotEqualToWhenResourcePathIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo("lenient-same.json")); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo("lenient-same.json")); } @Test @@ -487,7 +487,7 @@ class JsonContentAssertTests { @Test void isNotEqualToWhenBytesAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(LENIENT_SAME.getBytes())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(LENIENT_SAME.getBytes())); } @Test @@ -498,7 +498,7 @@ class JsonContentAssertTests { @Test void isNotEqualToWhenFileIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(createFile(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(createFile(LENIENT_SAME))); } @Test @@ -509,7 +509,7 @@ class JsonContentAssertTests { @Test void isNotEqualToWhenInputStreamIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(createInputStream(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(createInputStream(LENIENT_SAME))); } @Test @@ -520,7 +520,7 @@ class JsonContentAssertTests { @Test void isNotEqualToWhenResourceIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(createResource(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(createResource(LENIENT_SAME))); } @Test @@ -531,7 +531,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenStringIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME)); } @Test @@ -547,7 +547,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenResourcePathIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json")); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json")); } @Test @@ -558,7 +558,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenResourcePathAndClassAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass())); } @Test @@ -569,7 +569,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenBytesAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes())); } @Test @@ -580,7 +580,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenFileIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME))); } @Test @@ -591,7 +591,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenInputStreamIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME))); } @Test @@ -602,7 +602,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenResourceIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME))); } @Test @@ -613,7 +613,7 @@ class JsonContentAssertTests { @Test void isNotStrictlyEqualToJsonWhenStringIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(SOURCE)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(SOURCE)); } @Test @@ -624,7 +624,7 @@ class JsonContentAssertTests { @Test void isNotStrictlyEqualToJsonWhenResourcePathIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("source.json")); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("source.json")); } @Test @@ -635,7 +635,7 @@ class JsonContentAssertTests { @Test void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("source.json", getClass())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("source.json", getClass())); } @Test @@ -646,7 +646,7 @@ class JsonContentAssertTests { @Test void isNotStrictlyEqualToJsonWhenBytesAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(SOURCE.getBytes())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(SOURCE.getBytes())); } @Test @@ -657,7 +657,7 @@ class JsonContentAssertTests { @Test void isNotStrictlyEqualToJsonWhenFileIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createFile(SOURCE))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createFile(SOURCE))); } @Test @@ -668,7 +668,7 @@ class JsonContentAssertTests { @Test void isNotStrictlyEqualToJsonWhenInputStreamIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createInputStream(SOURCE))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createInputStream(SOURCE))); } @Test @@ -679,7 +679,7 @@ class JsonContentAssertTests { @Test void isNotStrictlyEqualToJsonWhenResourceIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createResource(SOURCE))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createResource(SOURCE))); } @Test @@ -690,7 +690,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenStringIsMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, JSONCompareMode.LENIENT)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, JSONCompareMode.LENIENT)); } @Test @@ -712,7 +712,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson("lenient-same.json", getClass(), JSONCompareMode.LENIENT)); + .isNotEqualToJson("lenient-same.json", getClass(), JSONCompareMode.LENIENT)); } @Test @@ -745,7 +745,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenInputStreamIsMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson(createInputStream(LENIENT_SAME), JSONCompareMode.LENIENT)); + .isNotEqualToJson(createInputStream(LENIENT_SAME), JSONCompareMode.LENIENT)); } @Test @@ -756,7 +756,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenResourceIsMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson(createResource(LENIENT_SAME), JSONCompareMode.LENIENT)); + .isNotEqualToJson(createResource(LENIENT_SAME), JSONCompareMode.LENIENT)); } @Test @@ -767,7 +767,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenStringIsMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, COMPARATOR)); } @Test @@ -778,7 +778,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenResourcePathIsMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", COMPARATOR)); } @Test @@ -800,7 +800,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenBytesAreMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(), COMPARATOR)); } @Test @@ -811,7 +811,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenFileIsMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME), COMPARATOR)); } @Test @@ -832,8 +832,8 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenResourceIsMatchingAndComparatorShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME), COMPARATOR)); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME), COMPARATOR)); } @Test @@ -855,8 +855,8 @@ class JsonContentAssertTests { void hasJsonPathForNotPresent() { String expression = "missing"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(NULLS)).hasJsonPath(expression)) - .withMessageContaining("No JSON path \"" + expression + "\" found"); + .isThrownBy(() -> assertThat(forJson(NULLS)).hasJsonPath(expression)) + .withMessageContaining("No JSON path \"" + expression + "\" found"); } @Test @@ -878,16 +878,16 @@ class JsonContentAssertTests { void hasJsonPathValueForANullValue() { String expression = "nullname"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(NULLS)).hasJsonPathValue(expression)) - .withMessageContaining("No value at JSON path \"" + expression + "\""); + .isThrownBy(() -> assertThat(forJson(NULLS)).hasJsonPathValue(expression)) + .withMessageContaining("No value at JSON path \"" + expression + "\""); } @Test void hasJsonPathValueForMissingValue() { String expression = "missing"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(NULLS)).hasJsonPathValue(expression)) - .withMessageContaining("No value at JSON path \"" + expression + "\""); + .isThrownBy(() -> assertThat(forJson(NULLS)).hasJsonPathValue(expression)) + .withMessageContaining("No value at JSON path \"" + expression + "\""); } @Test @@ -899,8 +899,8 @@ class JsonContentAssertTests { void hasJsonPathValueForIndefinitePathWithEmptyResults() { String expression = "$.familyMembers[?(@.name == 'Dilbert')]"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SIMPSONS)).hasJsonPathValue(expression)) - .withMessageContaining("No value at JSON path \"" + expression + "\""); + .isThrownBy(() -> assertThat(forJson(SIMPSONS)).hasJsonPathValue(expression)) + .withMessageContaining("No value at JSON path \"" + expression + "\""); } @Test @@ -912,16 +912,16 @@ class JsonContentAssertTests { void doesNotHaveJsonPathForNull() { String expression = "nullname"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(NULLS)).doesNotHaveJsonPath(expression)) - .withMessageContaining("Expecting no JSON path \"" + expression + "\""); + .isThrownBy(() -> assertThat(forJson(NULLS)).doesNotHaveJsonPath(expression)) + .withMessageContaining("Expecting no JSON path \"" + expression + "\""); } @Test void doesNotHaveJsonPathForPresent() { String expression = "valuename"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(NULLS)).doesNotHaveJsonPath(expression)) - .withMessageContaining("Expecting no JSON path \"" + expression + "\""); + .isThrownBy(() -> assertThat(forJson(NULLS)).doesNotHaveJsonPath(expression)) + .withMessageContaining("Expecting no JSON path \"" + expression + "\""); } @Test @@ -933,25 +933,25 @@ class JsonContentAssertTests { void doesNotHaveJsonPathValueForAnEmptyArray() { String expression = "$.emptyArray"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression)) - .withMessageContaining("Expected no value at JSON path \"" + expression + "\" but found: []"); + .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression)) + .withMessageContaining("Expected no value at JSON path \"" + expression + "\" but found: []"); } @Test void doesNotHaveJsonPathValueForAnEmptyMap() { String expression = "$.emptyMap"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression)) - .withMessageContaining("Expected no value at JSON path \"" + expression + "\" but found: {}"); + .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression)) + .withMessageContaining("Expected no value at JSON path \"" + expression + "\" but found: {}"); } @Test void doesNotHaveJsonPathValueForIndefinitePathWithResults() { String expression = "$.familyMembers[?(@.name == 'Bart')]"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue(expression)) - .withMessageContaining( - "Expected no value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]"); + .isThrownBy(() -> assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue(expression)) + .withMessageContaining( + "Expected no value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]"); } @Test @@ -988,17 +988,17 @@ class JsonContentAssertTests { void hasEmptyJsonPathValueForIndefinitePathWithResults() { String expression = "$.familyMembers[?(@.name == 'Bart')]"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue(expression)) - .withMessageContaining( - "Expected an empty value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]"); + .isThrownBy(() -> assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue(expression)) + .withMessageContaining( + "Expected an empty value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]"); } @Test void hasEmptyJsonPathValueForWhitespace() { String expression = "$.whitespace"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).hasEmptyJsonPathValue(expression)) - .withMessageContaining("Expected an empty value at JSON path \"" + expression + "\" but found: ' '"); + .isThrownBy(() -> assertThat(forJson(TYPES)).hasEmptyJsonPathValue(expression)) + .withMessageContaining("Expected an empty value at JSON path \"" + expression + "\" but found: ' '"); } @Test @@ -1035,32 +1035,32 @@ class JsonContentAssertTests { void doesNotHaveEmptyJsonPathValueForIndefinitePathWithEmptyResults() { String expression = "$.familyMembers[?(@.name == 'Dilbert')]"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SIMPSONS)).doesNotHaveEmptyJsonPathValue(expression)) - .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: []"); + .isThrownBy(() -> assertThat(forJson(SIMPSONS)).doesNotHaveEmptyJsonPathValue(expression)) + .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: []"); } @Test void doesNotHaveEmptyJsonPathValueForAnEmptyString() { String expression = "$.emptyString"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression)) - .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: ''"); + .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression)) + .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: ''"); } @Test void doesNotHaveEmptyJsonPathValueForForAnEmptyArray() { String expression = "$.emptyArray"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression)) - .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: []"); + .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression)) + .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: []"); } @Test void doesNotHaveEmptyJsonPathValueForAnEmptyMap() { String expression = "$.emptyMap"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression)) - .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: {}"); + .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression)) + .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: {}"); } @Test @@ -1077,8 +1077,8 @@ class JsonContentAssertTests { void hasJsonPathStringValueForNonString() { String expression = "$.bool"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathStringValue(expression)) - .withMessageContaining("Expected a string at JSON path \"" + expression + "\" but found: true"); + .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathStringValue(expression)) + .withMessageContaining("Expected a string at JSON path \"" + expression + "\" but found: true"); } @Test @@ -1090,8 +1090,8 @@ class JsonContentAssertTests { void hasJsonPathNumberValueForNonNumber() { String expression = "$.bool"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathNumberValue(expression)) - .withMessageContaining("Expected a number at JSON path \"" + expression + "\" but found: true"); + .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathNumberValue(expression)) + .withMessageContaining("Expected a number at JSON path \"" + expression + "\" but found: true"); } @Test @@ -1103,8 +1103,8 @@ class JsonContentAssertTests { void hasJsonPathBooleanValueForNonBoolean() { String expression = "$.num"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathBooleanValue(expression)) - .withMessageContaining("Expected a boolean at JSON path \"" + expression + "\" but found: 5"); + .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathBooleanValue(expression)) + .withMessageContaining("Expected a boolean at JSON path \"" + expression + "\" but found: 5"); } @Test @@ -1121,8 +1121,8 @@ class JsonContentAssertTests { void hasJsonPathArrayValueForNonArray() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathArrayValue(expression)) - .withMessageContaining("Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); + .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathArrayValue(expression)) + .withMessageContaining("Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); } @Test @@ -1139,8 +1139,8 @@ class JsonContentAssertTests { void hasJsonPathMapValueForNonMap() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathMapValue(expression)) - .withMessageContaining("Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); + .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathMapValue(expression)) + .withMessageContaining("Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); } @Test @@ -1172,8 +1172,8 @@ class JsonContentAssertTests { void extractingJsonPathStringValueForWrongType() { String expression = "$.num"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathStringValue(expression)) - .withMessageContaining("Expected a string at JSON path \"" + expression + "\" but found: 5"); + .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathStringValue(expression)) + .withMessageContaining("Expected a string at JSON path \"" + expression + "\" but found: 5"); } @Test @@ -1190,8 +1190,8 @@ class JsonContentAssertTests { void extractingJsonPathNumberValueForWrongType() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathNumberValue(expression)) - .withMessageContaining("Expected a number at JSON path \"" + expression + "\" but found: 'foo'"); + .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathNumberValue(expression)) + .withMessageContaining("Expected a number at JSON path \"" + expression + "\" but found: 'foo'"); } @Test @@ -1208,8 +1208,8 @@ class JsonContentAssertTests { void extractingJsonPathBooleanValueForWrongType() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathBooleanValue(expression)) - .withMessageContaining("Expected a boolean at JSON path \"" + expression + "\" but found: 'foo'"); + .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathBooleanValue(expression)) + .withMessageContaining("Expected a boolean at JSON path \"" + expression + "\" but found: 'foo'"); } @Test @@ -1231,8 +1231,8 @@ class JsonContentAssertTests { void extractingJsonPathArrayValueForWrongType() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathArrayValue(expression)) - .withMessageContaining("Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); + .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathArrayValue(expression)) + .withMessageContaining("Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); } @Test @@ -1254,8 +1254,8 @@ class JsonContentAssertTests { void extractingJsonPathMapValueForWrongType() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathMapValue(expression)) - .withMessageContaining("Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); + .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathMapValue(expression)) + .withMessageContaining("Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java index e6338feba3..1c3b27265e 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,23 +38,23 @@ class JsonContentTests { @Test void createWhenResourceLoadClassIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> new JsonContent(null, TYPE, JSON, Configuration.defaultConfiguration())) - .withMessageContaining("ResourceLoadClass must not be null"); + .isThrownBy(() -> new JsonContent(null, TYPE, JSON, Configuration.defaultConfiguration())) + .withMessageContaining("ResourceLoadClass must not be null"); } @Test void createWhenJsonIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new JsonContent(getClass(), TYPE, null, Configuration.defaultConfiguration())) - .withMessageContaining("JSON must not be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new JsonContent(getClass(), TYPE, null, Configuration.defaultConfiguration())) + .withMessageContaining("JSON must not be null"); } @Test void createWhenConfigurationIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new JsonContent(getClass(), TYPE, JSON, null)) - .withMessageContaining("Configuration must not be null"); + .isThrownBy(() -> new JsonContent(getClass(), TYPE, JSON, null)) + .withMessageContaining("Configuration must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java index 92237238c2..cf1c3e2a6e 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,14 +38,14 @@ class JsonbTesterTests extends AbstractJsonMarshalTesterTests { @Test void initFieldsWhenTestIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> JsonbTester.initFields(null, JsonbBuilder.create())) - .withMessageContaining("TestInstance must not be null"); + .withMessageContaining("TestInstance must not be null"); } @Test void initFieldsWhenMarshallerIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> JsonbTester.initFields(new InitFieldsTestClass(), (Jsonb) null)) - .withMessageContaining("Marshaller must not be null"); + .isThrownBy(() -> JsonbTester.initFields(new InitFieldsTestClass(), (Jsonb) null)) + .withMessageContaining("Marshaller must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java index 6fe815d3b4..9c059f1083 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,7 @@ class ObjectContentAssertTests { @Test void isEqualToWhenObjectsAreDifferentShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forObject(SOURCE)).isEqualTo(DIFFERENT)); + .isThrownBy(() -> assertThat(forObject(SOURCE)).isEqualTo(DIFFERENT)); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java index 9d183335f8..8d83219da6 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ class ObjectContentTests { @Test void createWhenObjectIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ObjectContent(TYPE, null)) - .withMessageContaining("Object must not be null"); + .withMessageContaining("Object must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java index 0b8cb7ea2b..04409f2f16 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -80,7 +80,7 @@ class DefinitionsParserTests { MockDefinition fieldDefinition = getMockDefinition(1); assertThat(fieldDefinition.getTypeToMock().resolve()).isEqualTo(ExampleServiceCaller.class); QualifierDefinition qualifier = QualifierDefinition - .forElement(ReflectionUtils.findField(MockBeanOnClassAndField.class, "caller")); + .forElement(ReflectionUtils.findField(MockBeanOnClassAndField.class, "caller")); assertThat(fieldDefinition.getQualifier()).isNotNull().isEqualTo(qualifier); } @@ -94,7 +94,7 @@ class DefinitionsParserTests { @Test void parseMockBeanMissingClassToMock() { assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(MockBeanMissingClassToMock.class)) - .withMessageContaining("Unable to deduce type to mock"); + .withMessageContaining("Unable to deduce type to mock"); } @Test @@ -108,7 +108,7 @@ class DefinitionsParserTests { @Test void parseMockBeanMultipleClassesWithName() { assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(MockBeanMultipleClassesWithName.class)) - .withMessageContaining("The name attribute can only be used when mocking a single class"); + .withMessageContaining("The name attribute can only be used when mocking a single class"); } @Test @@ -146,7 +146,7 @@ class DefinitionsParserTests { assertThat(classDefinition.getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); SpyDefinition fieldDefinition = getSpyDefinition(1); QualifierDefinition qualifier = QualifierDefinition - .forElement(ReflectionUtils.findField(SpyBeanOnClassAndField.class, "caller")); + .forElement(ReflectionUtils.findField(SpyBeanOnClassAndField.class, "caller")); assertThat(fieldDefinition.getQualifier()).isNotNull().isEqualTo(qualifier); assertThat(fieldDefinition.getTypeToSpy().resolve()).isEqualTo(ExampleServiceCaller.class); } @@ -161,7 +161,7 @@ class DefinitionsParserTests { @Test void parseSpyBeanMissingClassToMock() { assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(SpyBeanMissingClassToMock.class)) - .withMessageContaining("Unable to deduce type to spy"); + .withMessageContaining("Unable to deduce type to spy"); } @Test @@ -175,7 +175,7 @@ class DefinitionsParserTests { @Test void parseSpyBeanMultipleClassesWithName() { assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(SpyBeanMultipleClassesWithName.class)) - .withMessageContaining("The name attribute can only be used when spying a single class"); + .withMessageContaining("The name attribute can only be used when spying a single class"); } private MockDefinition getMockDefinition(int index) { 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..50b1db3382 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ class MockBeanContextCachingTests { @SuppressWarnings("unchecked") void clearCache() { Map contexts = (Map) ReflectionTestUtils - .getField(this.contextCache, "contextMap"); + .getField(this.contextCache, "contextMap"); for (ApplicationContext context : contexts.values()) { if (context instanceof ConfigurableApplicationContext) { ((ConfigurableApplicationContext) context).close(); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java index 53a6f51a5d..e79ab69235 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,8 @@ class MockDefinitionTests { @Test void classToMockMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new MockDefinition(null, null, null, null, false, null, null)) - .withMessageContaining("TypeToMock must not be null"); + .isThrownBy(() -> new MockDefinition(null, null, null, null, false, null, null)) + .withMessageContaining("TypeToMock must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java index 36873c22b6..4e6a066063 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,8 +58,8 @@ class MockitoPostProcessorTests { MockitoPostProcessor.register(context); context.register(MultipleBeans.class); assertThatIllegalStateException().isThrownBy(context::refresh) - .withMessageContaining("Unable to register mock bean " + ExampleService.class.getName() - + " expected a single matching bean to replace but found [example1, example2]"); + .withMessageContaining("Unable to register mock bean " + ExampleService.class.getName() + + " expected a single matching bean to replace but found [example1, example2]"); } @Test @@ -68,8 +68,8 @@ class MockitoPostProcessorTests { MockitoPostProcessor.register(context); context.register(MultipleQualifiedBeans.class); assertThatIllegalStateException().isThrownBy(context::refresh) - .withMessageContaining("Unable to register mock bean " + ExampleService.class.getName() - + " expected a single matching bean to replace but found [example1, example3]"); + .withMessageContaining("Unable to register mock bean " + ExampleService.class.getName() + + " expected a single matching bean to replace but found [example1, example3]"); } @Test @@ -94,7 +94,7 @@ class MockitoPostProcessorTests { assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isMock()).isTrue(); assertThat(Mockito.mockingDetails(context.getBean("examplePrimary", ExampleService.class)).isMock()).isTrue(); assertThat(Mockito.mockingDetails(context.getBean("exampleQualified", ExampleService.class)).isMock()) - .isFalse(); + .isFalse(); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java index 05d8ed51fa..bda83de5d3 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -88,7 +88,7 @@ class MockitoTestExecutionListenerTests { TestContext mockTestContext = mockTestContext(instance); given(mockTestContext.getApplicationContext()).willReturn(this.applicationContext); given(mockTestContext.getAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE)) - .willReturn(Boolean.TRUE); + .willReturn(Boolean.TRUE); this.listener.beforeTestMethod(mockTestContext); then(this.postProcessor).should().inject(this.fieldCaptor.capture(), eq(instance), any(MockDefinition.class)); assertThat(this.fieldCaptor.getValue().getName()).isEqualTo("mockBean"); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java index 53272bd00b..dd88219916 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,14 +65,14 @@ class QualifierDefinitionTests { @Test void forElementWhenElementIsFieldWithNoQualifiersShouldReturnNull() { QualifierDefinition definition = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigA.class, "noQualifier")); + .forElement(ReflectionUtils.findField(ConfigA.class, "noQualifier")); assertThat(definition).isNull(); } @Test void forElementWhenElementIsFieldWithQualifierShouldReturnDefinition() { QualifierDefinition definition = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier")); + .forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier")); assertThat(definition).isNotNull(); } @@ -97,26 +97,29 @@ class QualifierDefinitionTests { @Test void hashCodeAndEqualsShouldWorkOnDifferentClasses() { QualifierDefinition directQualifier1 = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier")); + .forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier")); QualifierDefinition directQualifier2 = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigB.class, "directQualifier")); + .forElement(ReflectionUtils.findField(ConfigB.class, "directQualifier")); QualifierDefinition differentDirectQualifier1 = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigA.class, "differentDirectQualifier")); + .forElement(ReflectionUtils.findField(ConfigA.class, "differentDirectQualifier")); QualifierDefinition differentDirectQualifier2 = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigB.class, "differentDirectQualifier")); + .forElement(ReflectionUtils.findField(ConfigB.class, "differentDirectQualifier")); QualifierDefinition customQualifier1 = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigA.class, "customQualifier")); + .forElement(ReflectionUtils.findField(ConfigA.class, "customQualifier")); QualifierDefinition customQualifier2 = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigB.class, "customQualifier")); + .forElement(ReflectionUtils.findField(ConfigB.class, "customQualifier")); assertThat(directQualifier1.hashCode()).isEqualTo(directQualifier2.hashCode()); assertThat(differentDirectQualifier1.hashCode()).isEqualTo(differentDirectQualifier2.hashCode()); assertThat(customQualifier1.hashCode()).isEqualTo(customQualifier2.hashCode()); - assertThat(differentDirectQualifier1).isEqualTo(differentDirectQualifier1).isEqualTo(differentDirectQualifier2) - .isNotEqualTo(directQualifier2); - assertThat(directQualifier1).isEqualTo(directQualifier1).isEqualTo(directQualifier2) - .isNotEqualTo(differentDirectQualifier1); - assertThat(customQualifier1).isEqualTo(customQualifier1).isEqualTo(customQualifier2) - .isNotEqualTo(differentDirectQualifier1); + assertThat(differentDirectQualifier1).isEqualTo(differentDirectQualifier1) + .isEqualTo(differentDirectQualifier2) + .isNotEqualTo(directQualifier2); + assertThat(directQualifier1).isEqualTo(directQualifier1) + .isEqualTo(directQualifier2) + .isNotEqualTo(differentDirectQualifier1); + assertThat(customQualifier1).isEqualTo(customQualifier1) + .isEqualTo(customQualifier2) + .isNotEqualTo(differentDirectQualifier1); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests.java index 6751f49f0c..5d0cf611cf 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,7 @@ class SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests { void testSpying() { assertThat(this.caller.sayGreeting()).isEqualTo("I say two"); assertThat(Mockito.mockingDetails(this.spy).getMockCreationSettings().getMockName().toString()) - .isEqualTo("two"); + .isEqualTo("two"); then(this.spy).should().greeting(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java index 06883177c8..f3fd74d204 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class SpyDefinitionTests { @Test void classToSpyMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new SpyDefinition(null, null, null, true, null)) - .withMessageContaining("TypeToSpy must not be null"); + .withMessageContaining("TypeToSpy must not be null"); } @Test @@ -81,14 +81,14 @@ class SpyDefinitionTests { void createSpyWhenNullInstanceShouldThrowException() { SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); assertThatIllegalArgumentException().isThrownBy(() -> definition.createSpy(null)) - .withMessageContaining("Instance must not be null"); + .withMessageContaining("Instance must not be null"); } @Test void createSpyWhenWrongInstanceShouldThrowException() { SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); assertThatIllegalArgumentException().isThrownBy(() -> definition.createSpy(new ExampleServiceCaller(null))) - .withMessageContaining("must be an instance of"); + .withMessageContaining("must be an instance of"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/TestPropertyValuesTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/TestPropertyValuesTests.java index e007aa2f69..d6bd7bca57 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/TestPropertyValuesTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/TestPropertyValuesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -103,7 +103,7 @@ class TestPropertyValuesTests { TestPropertyValues.of("FOO_BAR=BAZ").applyTo(this.environment, Type.SYSTEM_ENVIRONMENT); assertThat(this.environment.getProperty("foo.bar")).isEqualTo("BAZ"); assertThat(this.environment.getPropertySources() - .contains("test-" + StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)).isTrue(); + .contains("test-" + StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)).isTrue(); } @Test @@ -118,7 +118,7 @@ class TestPropertyValuesTests { TestPropertyValues.of("foo.bar=baz", "hello.world=hi").applyTo(this.environment, Type.MAP, "other"); TestPropertyValues.of("FOO_BAR=BAZ").applyTo(this.environment, Type.SYSTEM_ENVIRONMENT, "other"); assertThat(this.environment.getPropertySources().get("other")) - .isInstanceOf(SystemEnvironmentPropertySource.class); + .isInstanceOf(SystemEnvironmentPropertySource.class); assertThat(this.environment.getProperty("foo.bar")).isEqualTo("BAZ"); assertThat(this.environment.getProperty("hello.world")).isNull(); } @@ -133,8 +133,10 @@ class TestPropertyValuesTests { @Test void andShouldChainAndAddSingleKeyValue() { - TestPropertyValues.of("foo.bar=baz").and("hello.world=hi").and("bling.blah=bing").applyTo(this.environment, - Type.MAP); + TestPropertyValues.of("foo.bar=baz") + .and("hello.world=hi") + .and("bling.blah=bing") + .applyTo(this.environment, Type.MAP); assertThat(this.environment.getProperty("foo.bar")).isEqualTo("baz"); assertThat(this.environment.getProperty("hello.world")).isEqualTo("hi"); assertThat(this.environment.getProperty("bling.blah")).isEqualTo("bing"); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessorTests.java index 578f50b655..4102a0e3cf 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -115,7 +115,7 @@ class SpringBootTestRandomPortEnvironmentPostProcessorTests { // is null in app properties addTestPropertySource("0", null); this.propertySources - .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "8080"))); + .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "8080"))); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); assertThat(this.environment.getProperty("management.server.port")).isEqualTo(""); @@ -125,7 +125,7 @@ class SpringBootTestRandomPortEnvironmentPostProcessorTests { void postProcessWhenTestServerPortIsZeroAndManagementPortIsNotNullAndDifferentInProduction() { addTestPropertySource("0", null); this.propertySources - .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "8081"))); + .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "8081"))); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); assertThat(this.environment.getProperty("management.server.port")).isEqualTo("0"); @@ -135,7 +135,7 @@ class SpringBootTestRandomPortEnvironmentPostProcessorTests { void postProcessWhenTestServerPortIsZeroAndManagementPortMinusOne() { addTestPropertySource("0", null); this.propertySources - .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "-1"))); + .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "-1"))); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); assertThat(this.environment.getProperty("management.server.port")).isEqualTo("-1"); @@ -145,7 +145,7 @@ class SpringBootTestRandomPortEnvironmentPostProcessorTests { void postProcessWhenTestServerPortIsZeroAndManagementPortIsAnInteger() { addTestPropertySource("0", null); this.propertySources - .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", 8081))); + .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", 8081))); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); assertThat(this.environment.getProperty("management.server.port")).isEqualTo("0"); @@ -155,10 +155,10 @@ class SpringBootTestRandomPortEnvironmentPostProcessorTests { void postProcessWhenManagementServerPortPlaceholderPresentShouldResolvePlaceholder() { addTestPropertySource("0", null); MapPropertySource testPropertySource = (MapPropertySource) this.propertySources - .get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); + .get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); testPropertySource.getSource().put("port", "9090"); this.propertySources - .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "${port}"))); + .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "${port}"))); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); assertThat(this.environment.getProperty("management.server.port")).isEqualTo("0"); @@ -168,17 +168,17 @@ class SpringBootTestRandomPortEnvironmentPostProcessorTests { void postProcessWhenManagementServerPortPlaceholderAbsentShouldFail() { addTestPropertySource("0", null); this.propertySources - .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "${port}"))); + .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "${port}"))); assertThatIllegalArgumentException() - .isThrownBy(() -> this.postProcessor.postProcessEnvironment(this.environment, null)) - .withMessage("Could not resolve placeholder 'port' in value \"${port}\""); + .isThrownBy(() -> this.postProcessor.postProcessEnvironment(this.environment, null)) + .withMessage("Could not resolve placeholder 'port' in value \"${port}\""); } @Test void postProcessWhenServerPortPlaceholderPresentShouldResolvePlaceholder() { addTestPropertySource("0", null); MapPropertySource testPropertySource = (MapPropertySource) this.propertySources - .get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); + .get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); testPropertySource.getSource().put("port", "8080"); Map source = new HashMap<>(); source.put("server.port", "${port}"); @@ -197,8 +197,8 @@ class SpringBootTestRandomPortEnvironmentPostProcessorTests { source.put("management.server.port", "9090"); this.propertySources.addLast(new MapPropertySource("other", source)); assertThatIllegalArgumentException() - .isThrownBy(() -> this.postProcessor.postProcessEnvironment(this.environment, null)) - .withMessage("Could not resolve placeholder 'port' in value \"${port}\""); + .isThrownBy(() -> this.postProcessor.postProcessEnvironment(this.environment, null)) + .withMessage("Could not resolve placeholder 'port' in value \"${port}\""); } private void addTestPropertySource(String serverPort, String managementPort) { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java index 85d0e57b84..48b6313837 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,21 +43,21 @@ class LocalHostUriTemplateHandlerTests { @Test void createWhenEnvironmentIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostUriTemplateHandler(null)) - .withMessageContaining("Environment must not be null"); + .withMessageContaining("Environment must not be null"); } @Test void createWhenSchemeIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new LocalHostUriTemplateHandler(new MockEnvironment(), null)) - .withMessageContaining("Scheme must not be null"); + .isThrownBy(() -> new LocalHostUriTemplateHandler(new MockEnvironment(), null)) + .withMessageContaining("Scheme must not be null"); } @Test void createWhenHandlerIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new LocalHostUriTemplateHandler(new MockEnvironment(), "http", null)) - .withMessageContaining("Handler must not be null"); + .isThrownBy(() -> new LocalHostUriTemplateHandler(new MockEnvironment(), "http", null)) + .withMessageContaining("Handler must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java index d0ebd4c27e..2740b4d28f 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,13 +50,13 @@ class MockServerRestTemplateCustomizerTests { MockServerRestTemplateCustomizer customizer = new MockServerRestTemplateCustomizer(); customizer.customize(new RestTemplate()); assertThat(customizer.getServer()).extracting("expectationManager") - .isInstanceOf(SimpleRequestExpectationManager.class); + .isInstanceOf(SimpleRequestExpectationManager.class); } @Test void createWhenExpectationManagerClassIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new MockServerRestTemplateCustomizer(null)) - .withMessageContaining("ExpectationManager must not be null"); + .withMessageContaining("ExpectationManager must not be null"); } @Test @@ -65,7 +65,7 @@ class MockServerRestTemplateCustomizerTests { UnorderedRequestExpectationManager.class); customizer.customize(new RestTemplate()); assertThat(customizer.getServer()).extracting("expectationManager") - .isInstanceOf(UnorderedRequestExpectationManager.class); + .isInstanceOf(UnorderedRequestExpectationManager.class); } @Test @@ -74,7 +74,7 @@ class MockServerRestTemplateCustomizerTests { UnorderedRequestExpectationManager.class); customizer.customize(new RestTemplateBuilder().rootUri("https://example.com").build()); assertThat(customizer.getServer()).extracting("expectationManager") - .isInstanceOf(RootUriRequestExpectationManager.class); + .isInstanceOf(RootUriRequestExpectationManager.class); } @Test @@ -82,7 +82,7 @@ class MockServerRestTemplateCustomizerTests { this.customizer.setDetectRootUri(false); this.customizer.customize(new RestTemplateBuilder().rootUri("https://example.com").build()); assertThat(this.customizer.getServer()).extracting("expectationManager") - .isInstanceOf(SimpleRequestExpectationManager.class); + .isInstanceOf(SimpleRequestExpectationManager.class); } @@ -97,8 +97,8 @@ class MockServerRestTemplateCustomizerTests { @Test void getServerWhenNoServersAreBoundShouldThrowException() { assertThatIllegalStateException().isThrownBy(this.customizer::getServer) - .withMessageContaining("Unable to return a single MockRestServiceServer since " - + "MockServerRestTemplateCustomizer has not been bound to a RestTemplate"); + .withMessageContaining("Unable to return a single MockRestServiceServer since " + + "MockServerRestTemplateCustomizer has not been bound to a RestTemplate"); } @Test @@ -106,8 +106,8 @@ class MockServerRestTemplateCustomizerTests { this.customizer.customize(new RestTemplate()); this.customizer.customize(new RestTemplate()); assertThatIllegalStateException().isThrownBy(this.customizer::getServer) - .withMessageContaining("Unable to return a single MockRestServiceServer since " - + "MockServerRestTemplateCustomizer has been bound to more than one RestTemplate"); + .withMessageContaining("Unable to return a single MockRestServiceServer since " + + "MockServerRestTemplateCustomizer has been bound to more than one RestTemplate"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/NoTestRestTemplateBeanChecker.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/NoTestRestTemplateBeanChecker.java index 2fb9be5158..94d4519940 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/NoTestRestTemplateBeanChecker.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/NoTestRestTemplateBeanChecker.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,8 @@ class NoTestRestTemplateBeanChecker implements ImportSelector, BeanFactoryAware @Override public void setBeanFactory(BeanFactory beanFactory) { assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) beanFactory, - TestRestTemplate.class)).isEmpty(); + TestRestTemplate.class)) + .isEmpty(); } @Override diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java index 2fd99419ca..d7ea5b5119 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,13 +71,13 @@ class RootUriRequestExpectationManagerTests { @Test void createWhenRootUriIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new RootUriRequestExpectationManager(null, this.delegate)) - .withMessageContaining("RootUri must not be null"); + .withMessageContaining("RootUri must not be null"); } @Test void createWhenExpectationManagerIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new RootUriRequestExpectationManager(this.uri, null)) - .withMessageContaining("ExpectationManager must not be null"); + .withMessageContaining("ExpectationManager must not be null"); } @Test @@ -112,9 +112,9 @@ class RootUriRequestExpectationManagerTests { ClientHttpRequest request = mock(ClientHttpRequest.class); given(request.getURI()).willReturn(new URI(this.uri + "/hello")); given(this.delegate.validateRequest(any(ClientHttpRequest.class))) - .willThrow(new AssertionError("Request URI expected: was:")); + .willThrow(new AssertionError("Request URI expected: was:")); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.manager.validateRequest(request)) - .withMessageContaining("Request URI expected:"); + .withMessageContaining("Request URI expected:"); } @Test @@ -168,8 +168,8 @@ class RootUriRequestExpectationManagerTests { MockRestServiceServer server = RootUriRequestExpectationManager.bindTo(restTemplate); server.expect(requestTo("/hello")).andRespond(withSuccess()); assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> restTemplate.getForEntity("https://spring.io/hello", String.class)) - .withMessageContaining("expected: but was:"); + .isThrownBy(() -> restTemplate.getForEntity("https://spring.io/hello", String.class)) + .withMessageContaining("expected: but was:"); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java index 4215136214..35854b484d 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -82,7 +82,7 @@ class TestRestTemplateTests { void simple() { // The Apache client is on the classpath so we get the fully-fledged factory assertThat(new TestRestTemplate().getRestTemplate().getRequestFactory()) - .isInstanceOf(HttpComponentsClientHttpRequestFactory.class); + .isInstanceOf(HttpComponentsClientHttpRequestFactory.class); } @Test @@ -90,7 +90,7 @@ class TestRestTemplateTests { RestTemplateBuilder builder = new RestTemplateBuilder().requestFactory(OkHttp3ClientHttpRequestFactory.class); TestRestTemplate testRestTemplate = new TestRestTemplate(builder); assertThat(testRestTemplate.getRestTemplate().getRequestFactory()) - .isInstanceOf(OkHttp3ClientHttpRequestFactory.class); + .isInstanceOf(OkHttp3ClientHttpRequestFactory.class); } @Test @@ -134,7 +134,8 @@ class TestRestTemplateTests { void options() { TestRestTemplate template = new TestRestTemplate(HttpClientOption.ENABLE_REDIRECTS); CustomHttpComponentsClientHttpRequestFactory factory = (CustomHttpComponentsClientHttpRequestFactory) template - .getRestTemplate().getRequestFactory(); + .getRestTemplate() + .getRequestFactory(); RequestConfig config = factory.getRequestConfig(); assertThat(config.isRedirectsEnabled()).isTrue(); } @@ -155,7 +156,8 @@ class TestRestTemplateTests { method.getParameterTypes()); assertThat(equivalent).as("Method %s not found", method).isNotNull(); assertThat(Modifier.isPublic(equivalent.getModifiers())) - .as("Method %s should have been public", equivalent).isTrue(); + .as("Method %s should have been public", equivalent) + .isTrue(); try { equivalent.invoke(restTemplate, mockArguments(method.getParameterTypes())); } @@ -219,8 +221,11 @@ class TestRestTemplateTests { } private List> getConverterClasses(TestRestTemplate testRestTemplate) { - return testRestTemplate.getRestTemplate().getMessageConverters().stream().map(Object::getClass) - .collect(Collectors.toList()); + return testRestTemplate.getRestTemplate() + .getMessageConverters() + .stream() + .map(Object::getClass) + .collect(Collectors.toList()); } @Test @@ -271,14 +276,14 @@ class TestRestTemplateTests { @Test void exchangeWithRequestEntityAndClassHandlesRelativeUris() throws IOException { verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate - .exchange(new RequestEntity(HttpMethod.GET, relativeUri), String.class)); + .exchange(new RequestEntity(HttpMethod.GET, relativeUri), String.class)); } @Test void exchangeWithRequestEntityAndParameterizedTypeReferenceHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate.exchange( - new RequestEntity(HttpMethod.GET, relativeUri), new ParameterizedTypeReference() { - })); + verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate + .exchange(new RequestEntity(HttpMethod.GET, relativeUri), new ParameterizedTypeReference() { + })); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java index 46c461341a..74ba020c6d 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ class LocalHostWebClientTests { @Test void createWhenEnvironmentIsNullWillThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostWebClient(null)) - .withMessageContaining("Environment must not be null"); + .withMessageContaining("Environment must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java index d6d300913b..167ad21176 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,20 +63,20 @@ class LocalHostWebConnectionHtmlUnitDriverTests { @Test void createWhenEnvironmentIsNullWillThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null)) - .withMessageContaining("Environment must not be null"); + .withMessageContaining("Environment must not be null"); } @Test void createWithJavascriptFlagWhenEnvironmentIsNullWillThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, true)) - .withMessageContaining("Environment must not be null"); + .withMessageContaining("Environment must not be null"); } @Test void createWithBrowserVersionWhenEnvironmentIsNullWillThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, BrowserVersion.CHROME)) - .withMessageContaining("Environment must not be null"); + .isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, BrowserVersion.CHROME)) + .withMessageContaining("Environment must not be null"); } @Test @@ -85,8 +85,8 @@ class LocalHostWebConnectionHtmlUnitDriverTests { given(capabilities.getBrowserName()).willReturn("htmlunit"); given(capabilities.getBrowserVersion()).willReturn("chrome"); assertThatIllegalArgumentException() - .isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, capabilities)) - .withMessageContaining("Environment must not be null"); + .isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, capabilities)) + .withMessageContaining("Environment must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/NoWebTestClientBeanChecker.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/NoWebTestClientBeanChecker.java index 2c8a28db62..6caa9d7431 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/NoWebTestClientBeanChecker.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/NoWebTestClientBeanChecker.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,8 @@ class NoWebTestClientBeanChecker implements ImportSelector, BeanFactoryAware { @Override public void setBeanFactory(BeanFactory beanFactory) { assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) beanFactory, - WebTestClient.class)).isEmpty(); + WebTestClient.class)) + .isEmpty(); } @Override 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..3b58a64ebc 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -84,25 +84,25 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { private void addConditionPropertyGenerators(List generators) { String annotationPackage = "org.springframework.boot.autoconfigure.condition"; generators.add(PropertyGenerator.of(annotationPackage, "ConditionalOnClass") - .withAnnotation(new OnClassConditionValueExtractor())); + .withAnnotation(new OnClassConditionValueExtractor())); generators.add(PropertyGenerator.of(annotationPackage, "ConditionalOnBean") - .withAnnotation(new OnBeanConditionValueExtractor())); + .withAnnotation(new OnBeanConditionValueExtractor())); generators.add(PropertyGenerator.of(annotationPackage, "ConditionalOnSingleCandidate") - .withAnnotation(new OnBeanConditionValueExtractor())); + .withAnnotation(new OnBeanConditionValueExtractor())); generators.add(PropertyGenerator.of(annotationPackage, "ConditionalOnWebApplication") - .withAnnotation(ValueExtractor.allFrom("type"))); + .withAnnotation(ValueExtractor.allFrom("type"))); } private void addAutoConfigurePropertyGenerators(List generators) { String annotationPackage = "org.springframework.boot.autoconfigure"; generators.add(PropertyGenerator.of(annotationPackage, "AutoConfigureBefore", true) - .withAnnotation(ValueExtractor.allFrom("value", "name")) - .withAnnotation("AutoConfiguration", ValueExtractor.allFrom("before", "beforeName"))); + .withAnnotation(ValueExtractor.allFrom("value", "name")) + .withAnnotation("AutoConfiguration", ValueExtractor.allFrom("before", "beforeName"))); generators.add(PropertyGenerator.of(annotationPackage, "AutoConfigureAfter", true) - .withAnnotation(ValueExtractor.allFrom("value", "name")) - .withAnnotation("AutoConfiguration", ValueExtractor.allFrom("after", "afterName"))); + .withAnnotation(ValueExtractor.allFrom("value", "name")) + .withAnnotation("AutoConfiguration", ValueExtractor.allFrom("after", "afterName"))); generators.add(PropertyGenerator.of(annotationPackage, "AutoConfigureOrder") - .withAnnotation(ValueExtractor.allFrom("value"))); + .withAnnotation(ValueExtractor.allFrom("value"))); } @Override @@ -207,7 +207,7 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { Object value = annotationValue.getValue(); if (value instanceof List) { return ((List) value).stream() - .map((annotation) -> extractValue(annotation.getValue())); + .map((annotation) -> extractValue(annotation.getValue())); } return Stream.of(extractValue(value)); } @@ -248,7 +248,7 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { public List getValues(AnnotationMirror annotation) { Map attributes = new LinkedHashMap<>(); annotation.getElementValues() - .forEach((key, value) -> attributes.put(key.getSimpleName().toString(), value)); + .forEach((key, value) -> attributes.put(key.getSimpleName().toString(), value)); if (attributes.containsKey("name")) { return Collections.emptyList(); } @@ -274,8 +274,9 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { } private int compare(Object o1, Object o2) { - return Comparator.comparing(this::isSpringClass).thenComparing(String.CASE_INSENSITIVE_ORDER) - .compare(o1.toString(), o2.toString()); + return Comparator.comparing(this::isSpringClass) + .thenComparing(String.CASE_INSENSITIVE_ORDER) + .compare(o1.toString(), o2.toString()); } private boolean isSpringClass(String type) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java index 593bf2bbb1..cca091a8a6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +57,7 @@ class AutoConfigureAnnotationProcessorTests { + "TestClassConfiguration$Nested,org.springframework.foo"); assertThat(properties).containsKey("org.springframework.boot.autoconfigureprocessor.TestClassConfiguration"); assertThat(properties) - .containsKey("org.springframework.boot.autoconfigureprocessor.TestClassConfiguration$Nested"); + .containsKey("org.springframework.boot.autoconfigureprocessor.TestClassConfiguration$Nested"); assertThat(properties).containsEntry( "org.springframework.boot.autoconfigureprocessor.TestClassConfiguration.ConditionalOnBean", "java.io.OutputStream"); @@ -114,8 +114,8 @@ class AutoConfigureAnnotationProcessorTests { @Test void annotatedClassWithAutoConfiguration() throws Exception { Properties properties = compile(TestAutoConfigurationConfiguration.class); - assertThat(properties).containsEntry( - "org.springframework.boot.autoconfigureprocessor.TestAutoConfigurationConfiguration", ""); + assertThat(properties) + .containsEntry("org.springframework.boot.autoconfigureprocessor.TestAutoConfigurationConfiguration", ""); assertThat(properties).containsEntry( "org.springframework.boot.autoconfigureprocessor.TestAutoConfigurationConfiguration.AutoConfigureBefore", "java.io.InputStream,test.before1,test.before2"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestAutoConfigureAnnotationProcessor.java b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestAutoConfigureAnnotationProcessor.java index 36cfba8ab9..0d9393787f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestAutoConfigureAnnotationProcessor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestAutoConfigureAnnotationProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,21 +51,21 @@ public class TestAutoConfigureAnnotationProcessor extends AutoConfigureAnnotatio List generators = new ArrayList<>(); String annotationPackage = "org.springframework.boot.autoconfigureprocessor"; generators.add(PropertyGenerator.of(annotationPackage, "ConditionalOnClass") - .withAnnotation("TestConditionalOnClass", new OnClassConditionValueExtractor())); + .withAnnotation("TestConditionalOnClass", new OnClassConditionValueExtractor())); generators.add(PropertyGenerator.of(annotationPackage, "ConditionalOnBean") - .withAnnotation("TestConditionalOnBean", new OnBeanConditionValueExtractor())); + .withAnnotation("TestConditionalOnBean", new OnBeanConditionValueExtractor())); generators.add(PropertyGenerator.of(annotationPackage, "ConditionalOnSingleCandidate") - .withAnnotation("TestConditionalOnSingleCandidate", new OnBeanConditionValueExtractor())); + .withAnnotation("TestConditionalOnSingleCandidate", new OnBeanConditionValueExtractor())); generators.add(PropertyGenerator.of(annotationPackage, "ConditionalOnWebApplication") - .withAnnotation("TestConditionalOnWebApplication", ValueExtractor.allFrom("type"))); + .withAnnotation("TestConditionalOnWebApplication", ValueExtractor.allFrom("type"))); generators.add(PropertyGenerator.of(annotationPackage, "AutoConfigureBefore", true) - .withAnnotation("TestAutoConfigureBefore", ValueExtractor.allFrom("value", "name")) - .withAnnotation("TestAutoConfiguration", ValueExtractor.allFrom("before", "beforeName"))); + .withAnnotation("TestAutoConfigureBefore", ValueExtractor.allFrom("value", "name")) + .withAnnotation("TestAutoConfiguration", ValueExtractor.allFrom("before", "beforeName"))); generators.add(PropertyGenerator.of(annotationPackage, "AutoConfigureAfter", true) - .withAnnotation("TestAutoConfigureAfter", ValueExtractor.allFrom("value", "name")) - .withAnnotation("TestAutoConfiguration", ValueExtractor.allFrom("after", "afterName"))); + .withAnnotation("TestAutoConfigureAfter", ValueExtractor.allFrom("value", "name")) + .withAnnotation("TestAutoConfiguration", ValueExtractor.allFrom("after", "afterName"))); generators.add(PropertyGenerator.of(annotationPackage, "AutoConfigureOrder") - .withAnnotation("TestAutoConfigureOrder", ValueExtractor.allFrom("value"))); + .withAnnotation("TestAutoConfigureOrder", ValueExtractor.allFrom("value"))); return generators; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuilderBuildpack.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuilderBuildpack.java index d67b0000da..e649586e18 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuilderBuildpack.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuilderBuildpack.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,7 +62,7 @@ class BuilderBuildpack implements Buildpack { static Buildpack resolve(BuildpackResolverContext context, BuildpackReference reference) { boolean unambiguous = reference.hasPrefix(PREFIX); BuilderReference builderReference = BuilderReference - .of(unambiguous ? reference.getSubReference(PREFIX) : reference.toString()); + .of(unambiguous ? reference.getSubReference(PREFIX) : reference.toString()); BuildpackMetadata buildpackMetadata = findBuildpackMetadata(context, builderReference); if (unambiguous) { Assert.isTrue(buildpackMetadata != null, () -> "Buildpack '" + reference + "' not found in builder"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuildpackLayersMetadata.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuildpackLayersMetadata.java index 1816b0d987..3b269c0421 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuildpackLayersMetadata.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuildpackLayersMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -118,8 +118,9 @@ final class BuildpackLayersMetadata extends MappedObject { private static Buildpacks fromJson(JsonNode node) { Buildpacks buildpacks = new Buildpacks(); - node.fields().forEachRemaining((field) -> buildpacks.addBuildpackVersions(field.getKey(), - BuildpackVersions.fromJson(field.getValue()))); + node.fields() + .forEachRemaining((field) -> buildpacks.addBuildpackVersions(field.getKey(), + BuildpackVersions.fromJson(field.getValue()))); return buildpacks; } @@ -139,8 +140,9 @@ final class BuildpackLayersMetadata extends MappedObject { private static BuildpackVersions fromJson(JsonNode node) { BuildpackVersions versions = new BuildpackVersions(); - node.fields().forEachRemaining((field) -> versions.addBuildpackVersion(field.getKey(), - BuildpackLayerDetails.fromJson(field.getValue()))); + node.fields() + .forEachRemaining((field) -> versions.addBuildpackVersion(field.getKey(), + BuildpackLayerDetails.fromJson(field.getValue()))); return versions; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/ImageBuildpack.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/ImageBuildpack.java index 8220e2294f..a798b226e6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/ImageBuildpack.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/ImageBuildpack.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,7 +71,7 @@ final class ImageBuildpack implements Buildpack { private boolean buildpackExistsInBuilder(BuildpackResolverContext context, List imageLayers) { BuildpackLayerDetails buildpackLayerDetails = context.getBuildpackLayersMetadata() - .getBuildpack(this.coordinates.getId(), this.coordinates.getVersion()); + .getBuildpack(this.coordinates.getId(), this.coordinates.getVersion()); String layerDiffId = (buildpackLayerDetails != null) ? buildpackLayerDetails.getLayerDiffId() : null; return (layerDiffId != null) && imageLayers.stream().map(LayerId::toString).anyMatch(layerDiffId::equals); } @@ -98,7 +98,7 @@ final class ImageBuildpack implements Buildpack { boolean unambiguous = reference.hasPrefix(PREFIX); try { ImageReference imageReference = ImageReference - .of((unambiguous) ? reference.getSubReference(PREFIX) : reference.toString()); + .of((unambiguous) ? reference.getSubReference(PREFIX) : reference.toString()); return new ImageBuildpack(context, imageReference); } catch (IllegalArgumentException ex) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/Lifecycle.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/Lifecycle.java index b787880b4a..b31cacf0e3 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/Lifecycle.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/Lifecycle.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -239,8 +239,8 @@ class Lifecycle implements Closeable { } try { TarArchive applicationContent = this.request.getApplicationContent(this.builder.getBuildOwner()); - return this.docker.container().create(config, - ContainerContent.of(applicationContent, Directory.APPLICATION)); + return this.docker.container() + .create(config, ContainerContent.of(applicationContent, Directory.APPLICATION)); } finally { this.applicationVolumePopulated = true; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/LifecycleVersion.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/LifecycleVersion.java index 375879263f..3db3f48f66 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/LifecycleVersion.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/LifecycleVersion.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,8 @@ import org.springframework.util.Assert; class LifecycleVersion implements Comparable { private static final Comparator COMPARATOR = Comparator.comparingInt(LifecycleVersion::getMajor) - .thenComparingInt(LifecycleVersion::getMinor).thenComparing(LifecycleVersion::getPatch); + .thenComparingInt(LifecycleVersion::getMinor) + .thenComparing(LifecycleVersion::getPatch); private final int major; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/DockerApi.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/DockerApi.java index 6ebdfb8fa7..6a27db1059 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/DockerApi.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/DockerApi.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -339,7 +339,7 @@ public class DockerApi { URI createUri = buildUrl("/containers/create"); try (Response response = http().post(createUri, "application/json", config::writeTo)) { return ContainerReference - .of(SharedObjectMapper.get().readTree(response.getContent()).at("/Id").asText()); + .of(SharedObjectMapper.get().readTree(response.getContent()).at("/Id").asText()); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/ImageArchive.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/ImageArchive.java index dce9126235..ee1ab5cae7 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/ImageArchive.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/ImageArchive.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,10 +56,10 @@ import org.springframework.util.Assert; public class ImageArchive implements TarArchive { private static final Instant WINDOWS_EPOCH_PLUS_SECOND = OffsetDateTime.of(1980, 1, 1, 0, 0, 1, 0, ZoneOffset.UTC) - .toInstant(); + .toInstant(); private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_ZONED_DATE_TIME - .withZone(ZoneOffset.UTC); + .withZone(ZoneOffset.UTC); private static final String EMPTY_LAYER_NAME_PREFIX = "blank_"; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/Regex.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/Regex.java index c4ebb66520..c843097d10 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/Regex.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/Regex.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,7 +66,7 @@ final class Regex implements CharSequence { static final Pattern TAG = Regex.of("^[\\w][\\w.-]{0,127}").compile(); static final Pattern DIGEST = Regex.of("^[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][[A-Fa-f0-9]]{32,}") - .compile(); + .compile(); private final String value; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ApiVersionTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ApiVersionTests.java index 26b9c2e4db..74acc2a6cc 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ApiVersionTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ApiVersionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,19 +35,19 @@ class ApiVersionTests { @Test void parseWhenVersionIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ApiVersion.parse(null)) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test void parseWhenVersionIsEmptyThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ApiVersion.parse("")) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test void parseWhenVersionDoesNotMatchPatternThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ApiVersion.parse("bad")) - .withMessage("Malformed version number 'bad'"); + .withMessage("Malformed version number 'bad'"); } @Test @@ -65,8 +65,8 @@ class ApiVersionTests { @Test void assertSupportsWhenDoesNotSupportThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> ApiVersion.parse("1.2").assertSupports(ApiVersion.parse("1.3"))) - .withMessage("Detected platform API version '1.3' does not match supported version '1.2'"); + .isThrownBy(() -> ApiVersion.parse("1.2").assertSupports(ApiVersion.parse("1.3"))) + .withMessage("Detected platform API version '1.3' does not match supported version '1.2'"); } @Test @@ -129,7 +129,7 @@ class ApiVersionTests { private boolean supportsAny(String v1, String... others) { return ApiVersion.parse(v1) - .supportsAny(Arrays.stream(others).map(ApiVersion::parse).toArray(ApiVersion[]::new)); + .supportsAny(Arrays.stream(others).map(ApiVersion::parse).toArray(ApiVersion[]::new)); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ApiVersionsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ApiVersionsTests.java index d760520b00..f193b04dde 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ApiVersionsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ApiVersionsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,8 +63,8 @@ class ApiVersionsTests { @Test void findLatestWhenNoneSupportedThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> ApiVersions.parse("1.1", "1.2").findLatestSupported("1.3", "1.4")).withMessage( - "Detected platform API versions '1.3,1.4' are not included in supported versions '1.1,1.2'"); + .isThrownBy(() -> ApiVersions.parse("1.1", "1.2").findLatestSupported("1.3", "1.4")) + .withMessage("Detected platform API versions '1.3,1.4' are not included in supported versions '1.1,1.2'"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildOwnerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildOwnerTests.java index 44697e9c4f..c897a0af1e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildOwnerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildOwnerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ class BuildOwnerTests { @Test void fromEnvWhenEnvIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> BuildOwner.fromEnv(null)) - .withMessage("Env must not be null"); + .withMessage("Env must not be null"); } @Test @@ -55,7 +55,7 @@ class BuildOwnerTests { Map env = new LinkedHashMap<>(); env.put("CNB_GROUP_ID", "456"); assertThatIllegalStateException().isThrownBy(() -> BuildOwner.fromEnv(env)) - .withMessage("Missing 'CNB_USER_ID' value from the builder environment '" + env + "'"); + .withMessage("Missing 'CNB_USER_ID' value from the builder environment '" + env + "'"); } @Test @@ -63,7 +63,7 @@ class BuildOwnerTests { Map env = new LinkedHashMap<>(); env.put("CNB_USER_ID", "123"); assertThatIllegalStateException().isThrownBy(() -> BuildOwner.fromEnv(env)) - .withMessage("Missing 'CNB_GROUP_ID' value from the builder environment '" + env + "'"); + .withMessage("Missing 'CNB_GROUP_ID' value from the builder environment '" + env + "'"); } @Test @@ -72,7 +72,7 @@ class BuildOwnerTests { env.put("CNB_USER_ID", "nope"); env.put("CNB_GROUP_ID", "456"); assertThatIllegalStateException().isThrownBy(() -> BuildOwner.fromEnv(env)) - .withMessage("Malformed 'CNB_USER_ID' value 'nope' in the builder environment '" + env + "'"); + .withMessage("Malformed 'CNB_USER_ID' value 'nope' in the builder environment '" + env + "'"); } @Test @@ -81,7 +81,7 @@ class BuildOwnerTests { env.put("CNB_USER_ID", "123"); env.put("CNB_GROUP_ID", "nope"); assertThatIllegalStateException().isThrownBy(() -> BuildOwner.fromEnv(env)) - .withMessage("Malformed 'CNB_GROUP_ID' value 'nope' in the builder environment '" + env + "'"); + .withMessage("Malformed 'CNB_GROUP_ID' value 'nope' in the builder environment '" + env + "'"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildRequestTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildRequestTests.java index 0667e77084..ba69cde719 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildRequestTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildRequestTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -78,32 +78,33 @@ class BuildRequestTests { @Test void forJarFileWhenJarFileIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> BuildRequest.forJarFile(null)) - .withMessage("JarFile must not be null"); + .withMessage("JarFile must not be null"); } @Test void forJarFileWhenJarFileIsMissingThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> BuildRequest.forJarFile(new File(this.tempDir, "missing.jar"))) - .withMessage("JarFile must exist"); + .isThrownBy(() -> BuildRequest.forJarFile(new File(this.tempDir, "missing.jar"))) + .withMessage("JarFile must exist"); } @Test void forJarFileWhenJarFileIsDirectoryThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> BuildRequest.forJarFile(this.tempDir)) - .withMessage("JarFile must be a file"); + .withMessage("JarFile must be a file"); } @Test void withBuilderUpdatesBuilder() throws IOException { BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")) - .withBuilder(ImageReference.of("spring/builder")); + .withBuilder(ImageReference.of("spring/builder")); assertThat(request.getBuilder().toString()).isEqualTo("docker.io/spring/builder:latest"); } @Test void withBuilderWhenHasDigestUpdatesBuilder() throws IOException { - BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")).withBuilder(ImageReference + BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")) + .withBuilder(ImageReference .of("spring/builder@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d")); assertThat(request.getBuilder().toString()).isEqualTo( "docker.io/spring/builder@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); @@ -112,13 +113,14 @@ class BuildRequestTests { @Test void withRunImageUpdatesRunImage() throws IOException { BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")) - .withRunImage(ImageReference.of("example.com/custom/run-image:latest")); + .withRunImage(ImageReference.of("example.com/custom/run-image:latest")); assertThat(request.getRunImage().toString()).isEqualTo("example.com/custom/run-image:latest"); } @Test void withRunImageWhenHasDigestUpdatesRunImage() throws IOException { - BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")).withRunImage(ImageReference + BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")) + .withRunImage(ImageReference .of("example.com/custom/run-image@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d")); assertThat(request.getRunImage().toString()).isEqualTo( "example.com/custom/run-image@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); @@ -157,14 +159,14 @@ class BuildRequestTests { void withEnvWhenKeyIsNullThrowsException() throws IOException { BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")); assertThatIllegalArgumentException().isThrownBy(() -> request.withEnv(null, "test")) - .withMessage("Name must not be empty"); + .withMessage("Name must not be empty"); } @Test void withEnvWhenValueIsNullThrowsException() throws IOException { BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")); assertThatIllegalArgumentException().isThrownBy(() -> request.withEnv("test", null)) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test @@ -181,7 +183,7 @@ class BuildRequestTests { void withBuildpacksWhenBuildpacksIsNullThrowsException() throws IOException { BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")); assertThatIllegalArgumentException().isThrownBy(() -> request.withBuildpacks((List) null)) - .withMessage("Buildpacks must not be null"); + .withMessage("Buildpacks must not be null"); } @Test @@ -198,7 +200,7 @@ class BuildRequestTests { void withBindingsWhenBindingsIsNullThrowsException() throws IOException { BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")); assertThatIllegalArgumentException().isThrownBy(() -> request.withBindings((List) null)) - .withMessage("Bindings must not be null"); + .withMessage("Bindings must not be null"); } @Test @@ -223,7 +225,7 @@ class BuildRequestTests { void withTagsWhenTagsIsNullThrowsException() throws IOException { BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")); assertThatIllegalArgumentException().isThrownBy(() -> request.withTags((List) null)) - .withMessage("Tags must not be null"); + .withMessage("Tags must not be null"); } @Test @@ -238,7 +240,7 @@ class BuildRequestTests { void withBuildVolumeCacheWhenCacheIsNullThrowsException() throws IOException { BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")); assertThatIllegalArgumentException().isThrownBy(() -> request.withBuildCache(null)) - .withMessage("BuildCache must not be null"); + .withMessage("BuildCache must not be null"); } @Test @@ -253,7 +255,7 @@ class BuildRequestTests { void withLaunchVolumeCacheWhenCacheIsNullThrowsException() throws IOException { BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")); assertThatIllegalArgumentException().isThrownBy(() -> request.withLaunchCache(null)) - .withMessage("LaunchCache must not be null"); + .withMessage("LaunchCache must not be null"); } private void hasExpectedJarContent(TarArchive archive) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderBuildpackTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderBuildpackTests.java index 0907c1a2c2..d19666afdb 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderBuildpackTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderBuildpackTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ class BuilderBuildpackTests extends AbstractJsonTests { BuildpackReference reference = BuildpackReference.of("urn:cnb:builder:paketo-buildpacks/spring-boot@3.5.0"); Buildpack buildpack = BuilderBuildpack.resolve(this.resolverContext, reference); assertThat(buildpack.getCoordinates()) - .isEqualTo(BuildpackCoordinates.of("paketo-buildpacks/spring-boot", "3.5.0")); + .isEqualTo(BuildpackCoordinates.of("paketo-buildpacks/spring-boot", "3.5.0")); assertThatNoLayersAreAdded(buildpack); } @@ -61,7 +61,7 @@ class BuilderBuildpackTests extends AbstractJsonTests { BuildpackReference reference = BuildpackReference.of("urn:cnb:builder:paketo-buildpacks/spring-boot"); Buildpack buildpack = BuilderBuildpack.resolve(this.resolverContext, reference); assertThat(buildpack.getCoordinates()) - .isEqualTo(BuildpackCoordinates.of("paketo-buildpacks/spring-boot", "3.5.0")); + .isEqualTo(BuildpackCoordinates.of("paketo-buildpacks/spring-boot", "3.5.0")); assertThatNoLayersAreAdded(buildpack); } @@ -70,7 +70,7 @@ class BuilderBuildpackTests extends AbstractJsonTests { BuildpackReference reference = BuildpackReference.of("paketo-buildpacks/spring-boot@3.5.0"); Buildpack buildpack = BuilderBuildpack.resolve(this.resolverContext, reference); assertThat(buildpack.getCoordinates()) - .isEqualTo(BuildpackCoordinates.of("paketo-buildpacks/spring-boot", "3.5.0")); + .isEqualTo(BuildpackCoordinates.of("paketo-buildpacks/spring-boot", "3.5.0")); assertThatNoLayersAreAdded(buildpack); } @@ -79,7 +79,7 @@ class BuilderBuildpackTests extends AbstractJsonTests { BuildpackReference reference = BuildpackReference.of("paketo-buildpacks/spring-boot"); Buildpack buildpack = BuilderBuildpack.resolve(this.resolverContext, reference); assertThat(buildpack.getCoordinates()) - .isEqualTo(BuildpackCoordinates.of("paketo-buildpacks/spring-boot", "3.5.0")); + .isEqualTo(BuildpackCoordinates.of("paketo-buildpacks/spring-boot", "3.5.0")); assertThatNoLayersAreAdded(buildpack); } @@ -87,16 +87,16 @@ class BuilderBuildpackTests extends AbstractJsonTests { void resolveWhenFullyQualifiedBuildpackWithVersionNotInBuilderThrowsException() { BuildpackReference reference = BuildpackReference.of("urn:cnb:builder:example/buildpack1@1.2.3"); assertThatIllegalArgumentException().isThrownBy(() -> BuilderBuildpack.resolve(this.resolverContext, reference)) - .withMessageContaining("'urn:cnb:builder:example/buildpack1@1.2.3'") - .withMessageContaining("not found in builder"); + .withMessageContaining("'urn:cnb:builder:example/buildpack1@1.2.3'") + .withMessageContaining("not found in builder"); } @Test void resolveWhenFullyQualifiedBuildpackWithoutVersionNotInBuilderThrowsException() { BuildpackReference reference = BuildpackReference.of("urn:cnb:builder:example/buildpack1"); assertThatIllegalArgumentException().isThrownBy(() -> BuilderBuildpack.resolve(this.resolverContext, reference)) - .withMessageContaining("'urn:cnb:builder:example/buildpack1'") - .withMessageContaining("not found in builder"); + .withMessageContaining("'urn:cnb:builder:example/buildpack1'") + .withMessageContaining("not found in builder"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderMetadataTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderMetadataTests.java index b7dd6bf767..f5c0c0c7b5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderMetadataTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,28 +51,28 @@ class BuilderMetadataTests extends AbstractJsonTests { assertThat(metadata.getLifecycle().getApi().getPlatform()).isEqualTo("0.3"); assertThat(metadata.getCreatedBy().getName()).isEqualTo("Pack CLI"); assertThat(metadata.getCreatedBy().getVersion()) - .isEqualTo("v0.9.0 (git sha: d42c384a39f367588f2653f2a99702db910e5ad7)"); + .isEqualTo("v0.9.0 (git sha: d42c384a39f367588f2653f2a99702db910e5ad7)"); assertThat(metadata.getBuildpacks()).extracting(BuildpackMetadata::getId, BuildpackMetadata::getVersion) - .contains(tuple("paketo-buildpacks/java", "4.10.0")) - .contains(tuple("paketo-buildpacks/spring-boot", "3.5.0")) - .contains(tuple("paketo-buildpacks/executable-jar", "3.1.3")) - .contains(tuple("paketo-buildpacks/graalvm", "4.1.0")) - .contains(tuple("paketo-buildpacks/java-native-image", "4.7.0")) - .contains(tuple("paketo-buildpacks/spring-boot-native-image", "2.0.1")) - .contains(tuple("paketo-buildpacks/bellsoft-liberica", "6.2.0")); + .contains(tuple("paketo-buildpacks/java", "4.10.0")) + .contains(tuple("paketo-buildpacks/spring-boot", "3.5.0")) + .contains(tuple("paketo-buildpacks/executable-jar", "3.1.3")) + .contains(tuple("paketo-buildpacks/graalvm", "4.1.0")) + .contains(tuple("paketo-buildpacks/java-native-image", "4.7.0")) + .contains(tuple("paketo-buildpacks/spring-boot-native-image", "2.0.1")) + .contains(tuple("paketo-buildpacks/bellsoft-liberica", "6.2.0")); } @Test void fromImageWhenImageIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> BuilderMetadata.fromImage(null)) - .withMessage("Image must not be null"); + .withMessage("Image must not be null"); } @Test void fromImageWhenImageConfigIsNullThrowsException() { Image image = mock(Image.class); assertThatIllegalArgumentException().isThrownBy(() -> BuilderMetadata.fromImage(image)) - .withMessage("ImageConfig must not be null"); + .withMessage("ImageConfig must not be null"); } @Test @@ -82,7 +82,7 @@ class BuilderMetadataTests extends AbstractJsonTests { given(image.getConfig()).willReturn(imageConfig); given(imageConfig.getLabels()).willReturn(Collections.singletonMap("alpha", "a")); assertThatIllegalArgumentException().isThrownBy(() -> BuilderMetadata.fromImage(image)) - .withMessage("No 'io.buildpacks.builder.metadata' label found in image config labels 'alpha'"); + .withMessage("No 'io.buildpacks.builder.metadata' label found in image config labels 'alpha'"); } @Test @@ -127,7 +127,7 @@ class BuilderMetadataTests extends AbstractJsonTests { String label = imageConfigCopy.getLabels().get("io.buildpacks.builder.metadata"); BuilderMetadata metadataCopy = BuilderMetadata.fromJson(label); assertThat(metadataCopy.getStack().getRunImage().getImage()) - .isEqualTo(metadata.getStack().getRunImage().getImage()); + .isEqualTo(metadata.getStack().getRunImage().getImage()); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderTests.java index 32ad37e113..c9c522a2dd 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,7 +64,7 @@ class BuilderTests { @Test void createWhenLogIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new Builder((BuildLog) null)) - .withMessage("Log must not be null"); + .withMessage("Log must not be null"); } @Test @@ -77,7 +77,7 @@ class BuilderTests { void buildWhenRequestIsNullThrowsException() { Builder builder = new Builder(); assertThatIllegalArgumentException().isThrownBy(() -> builder.build(null)) - .withMessage("Request must not be null"); + .withMessage("Request must not be null"); } @Test @@ -87,19 +87,19 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest(); builder.build(request); assertThat(out.toString()).contains("Running creator"); assertThat(out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'"); ArgumentCaptor archive = ArgumentCaptor.forClass(ImageArchive.class); - then(docker.image()).should().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), - isNull()); - then(docker.image()).should().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), - isNull()); + then(docker.image()).should() + .pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull()); + then(docker.image()).should() + .pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), isNull()); then(docker.image()).should().load(archive.capture(), any()); then(docker.image()).should().remove(archive.getValue().getTag(), true); then(docker.image()).shouldHaveNoMoreInteractions(); @@ -112,26 +112,31 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); DockerConfiguration dockerConfiguration = new DockerConfiguration() - .withBuilderRegistryTokenAuthentication("builder token") - .withPublishRegistryTokenAuthentication("publish token"); - given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) - .willAnswer(withPulledImage(builderImage)); - given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) - .willAnswer(withPulledImage(runImage)); + .withBuilderRegistryTokenAuthentication("builder token") + .withPublishRegistryTokenAuthentication("publish token"); + given(docker.image() + .pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) + .willAnswer(withPulledImage(builderImage)); + given(docker.image() + .pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, dockerConfiguration); BuildRequest request = getTestRequest().withPublish(true); builder.build(request); assertThat(out.toString()).contains("Running creator"); assertThat(out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'"); ArgumentCaptor archive = ArgumentCaptor.forClass(ImageArchive.class); - then(docker.image()).should().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())); - then(docker.image()).should().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())); - then(docker.image()).should().push(eq(request.getName()), any(), - eq(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())); + then(docker.image()).should() + .pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())); + then(docker.image()).should() + .pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())); + then(docker.image()).should() + .push(eq(request.getName()), any(), + eq(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())); then(docker.image()).should().load(archive.capture(), any()); then(docker.image()).should().remove(archive.getValue().getTag(), true); then(docker.image()).shouldHaveNoMoreInteractions(); @@ -144,9 +149,9 @@ class BuilderTests { Image builderImage = loadImage("image-with-no-run-image-tag.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of("gcr.io/paketo-buildpacks/builder:latest")), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:latest")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest().withBuilder(ImageReference.of("gcr.io/paketo-buildpacks/builder")); builder.build(request); @@ -164,10 +169,12 @@ class BuilderTests { Image builderImage = loadImage("image-with-run-image-digest.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); - given(docker.image().pull(eq(ImageReference.of( - "docker.io/cloudfoundry/run@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d")), - any(), isNull())).willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(builderImage)); + given(docker.image() + .pull(eq(ImageReference + .of("docker.io/cloudfoundry/run@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d")), + any(), isNull())) + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest(); builder.build(request); @@ -185,9 +192,9 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("example.com/custom/run:latest")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest().withRunImage(ImageReference.of("example.com/custom/run:latest")); builder.build(request); @@ -205,13 +212,13 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(runImage)); given(docker.image().inspect(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)))) - .willReturn(builderImage); + .willReturn(builderImage); given(docker.image().inspect(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")))) - .willReturn(runImage); + .willReturn(runImage); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest().withPullPolicy(PullPolicy.NEVER); builder.build(request); @@ -231,13 +238,13 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(runImage)); given(docker.image().inspect(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)))) - .willReturn(builderImage); + .willReturn(builderImage); given(docker.image().inspect(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")))) - .willReturn(runImage); + .willReturn(runImage); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest().withPullPolicy(PullPolicy.ALWAYS); builder.build(request); @@ -257,15 +264,17 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); - given(docker.image().inspect(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)))).willThrow( - new DockerEngineException("docker://localhost/", new URI("example"), 404, "NOT FOUND", null, null)) - .willReturn(builderImage); - given(docker.image().inspect(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")))).willThrow( - new DockerEngineException("docker://localhost/", new URI("example"), 404, "NOT FOUND", null, null)) - .willReturn(runImage); + .willAnswer(withPulledImage(runImage)); + given(docker.image().inspect(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)))) + .willThrow( + new DockerEngineException("docker://localhost/", new URI("example"), 404, "NOT FOUND", null, null)) + .willReturn(builderImage); + given(docker.image().inspect(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")))) + .willThrow( + new DockerEngineException("docker://localhost/", new URI("example"), 404, "NOT FOUND", null, null)) + .willReturn(runImage); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest().withPullPolicy(PullPolicy.IF_NOT_PRESENT); builder.build(request); @@ -285,9 +294,9 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest().withTags(ImageReference.of("my-application:1.2.3")); builder.build(request); @@ -307,14 +316,16 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); DockerConfiguration dockerConfiguration = new DockerConfiguration() - .withBuilderRegistryTokenAuthentication("builder token") - .withPublishRegistryTokenAuthentication("publish token"); - given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) - .willAnswer(withPulledImage(builderImage)); - given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) - .willAnswer(withPulledImage(runImage)); + .withBuilderRegistryTokenAuthentication("builder token") + .withPublishRegistryTokenAuthentication("publish token"); + given(docker.image() + .pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) + .willAnswer(withPulledImage(builderImage)); + given(docker.image() + .pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, dockerConfiguration); BuildRequest request = getTestRequest().withPublish(true).withTags(ImageReference.of("my-application:1.2.3")); builder.build(request); @@ -322,15 +333,19 @@ class BuilderTests { assertThat(out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'"); assertThat(out.toString()).contains("Successfully created image tag 'docker.io/library/my-application:1.2.3'"); - then(docker.image()).should().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())); - then(docker.image()).should().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())); - then(docker.image()).should().push(eq(request.getName()), any(), - eq(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())); + then(docker.image()).should() + .pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())); + then(docker.image()).should() + .pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())); + then(docker.image()).should() + .push(eq(request.getName()), any(), + eq(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())); then(docker.image()).should().tag(eq(request.getName()), eq(ImageReference.of("my-application:1.2.3"))); - then(docker.image()).should().push(eq(ImageReference.of("my-application:1.2.3")), any(), - eq(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())); + then(docker.image()).should() + .push(eq(ImageReference.of("my-application:1.2.3")), any(), + eq(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())); ArgumentCaptor archive = ArgumentCaptor.forClass(ImageArchive.class); then(docker.image()).should().load(archive.capture(), any()); then(docker.image()).should().remove(archive.getValue().getTag(), true); @@ -344,13 +359,14 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image-with-bad-stack.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest(); - assertThatIllegalStateException().isThrownBy(() -> builder.build(request)).withMessage( - "Run image stack 'org.cloudfoundry.stacks.cfwindowsfs3' does not match builder stack 'io.buildpacks.stacks.bionic'"); + assertThatIllegalStateException().isThrownBy(() -> builder.build(request)) + .withMessage( + "Run image stack 'org.cloudfoundry.stacks.cfwindowsfs3' does not match builder stack 'io.buildpacks.stacks.bionic'"); } @Test @@ -360,13 +376,13 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest(); assertThatExceptionOfType(BuilderException.class).isThrownBy(() -> builder.build(request)) - .withMessage("Builder lifecycle 'creator' failed with status code 9"); + .withMessage("Builder lifecycle 'creator' failed with status code 9"); } @Test @@ -375,14 +391,16 @@ class BuilderTests { DockerApi docker = mockDockerApi(); Image builderImage = loadImage("image-with-run-image-different-registry.json"); DockerConfiguration dockerConfiguration = new DockerConfiguration() - .withBuilderRegistryTokenAuthentication("builder token"); - given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) - .willAnswer(withPulledImage(builderImage)); + .withBuilderRegistryTokenAuthentication("builder token"); + given(docker.image() + .pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) + .willAnswer(withPulledImage(builderImage)); Builder builder = new Builder(BuildLog.to(out), docker, dockerConfiguration); BuildRequest request = getTestRequest(); - assertThatIllegalStateException().isThrownBy(() -> builder.build(request)).withMessage( - "Run image 'example.com/custom/run:latest' must be pulled from the 'docker.io' authenticated registry"); + assertThatIllegalStateException().isThrownBy(() -> builder.build(request)) + .withMessage( + "Run image 'example.com/custom/run:latest' must be pulled from the 'docker.io' authenticated registry"); } @Test @@ -391,14 +409,16 @@ class BuilderTests { DockerApi docker = mockDockerApi(); Image builderImage = loadImage("image.json"); DockerConfiguration dockerConfiguration = new DockerConfiguration() - .withBuilderRegistryTokenAuthentication("builder token"); - given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) - .willAnswer(withPulledImage(builderImage)); + .withBuilderRegistryTokenAuthentication("builder token"); + given(docker.image() + .pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) + .willAnswer(withPulledImage(builderImage)); Builder builder = new Builder(BuildLog.to(out), docker, dockerConfiguration); BuildRequest request = getTestRequest().withRunImage(ImageReference.of("example.com/custom/run:latest")); - assertThatIllegalStateException().isThrownBy(() -> builder.build(request)).withMessage( - "Run image 'example.com/custom/run:latest' must be pulled from the 'docker.io' authenticated registry"); + assertThatIllegalStateException().isThrownBy(() -> builder.build(request)) + .withMessage( + "Run image 'example.com/custom/run:latest' must be pulled from the 'docker.io' authenticated registry"); } @Test @@ -408,15 +428,15 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildpackReference reference = BuildpackReference.of("urn:cnb:builder:example/buildpack@1.2.3"); BuildRequest request = getTestRequest().withBuildpacks(reference); assertThatIllegalArgumentException().isThrownBy(() -> builder.build(request)) - .withMessageContaining("'urn:cnb:builder:example/buildpack@1.2.3'") - .withMessageContaining("not found in builder"); + .withMessageContaining("'urn:cnb:builder:example/buildpack@1.2.3'") + .withMessageContaining("not found in builder"); } private DockerApi mockDockerApi() throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackCoordinatesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackCoordinatesTests.java index 568ee4f1e5..3a420e06f6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackCoordinatesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackCoordinatesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ class BuildpackCoordinatesTests extends AbstractJsonTests { @Test void fromToml() throws IOException { BuildpackCoordinates coordinates = BuildpackCoordinates - .fromToml(createTomlStream("example/buildpack1", "0.0.1", true, false), this.archive); + .fromToml(createTomlStream("example/buildpack1", "0.0.1", true, false), this.archive); assertThat(coordinates.getId()).isEqualTo("example/buildpack1"); assertThat(coordinates.getVersion()).isEqualTo("0.0.1"); } @@ -52,46 +52,46 @@ class BuildpackCoordinatesTests extends AbstractJsonTests { void fromTomlWhenMissingDescriptorThrowsException() { ByteArrayInputStream coordinates = new ByteArrayInputStream("".getBytes()); assertThatIllegalArgumentException().isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive)) - .withMessageContaining("Buildpack descriptor 'buildpack.toml' is required") - .withMessageContaining(this.archive.toString()); + .withMessageContaining("Buildpack descriptor 'buildpack.toml' is required") + .withMessageContaining(this.archive.toString()); } @Test void fromTomlWhenMissingIDThrowsException() { InputStream coordinates = createTomlStream(null, null, true, false); assertThatIllegalArgumentException().isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive)) - .withMessageContaining("Buildpack descriptor must contain ID") - .withMessageContaining(this.archive.toString()); + .withMessageContaining("Buildpack descriptor must contain ID") + .withMessageContaining(this.archive.toString()); } @Test void fromTomlWhenMissingVersionThrowsException() { InputStream coordinates = createTomlStream("example/buildpack1", null, true, false); assertThatIllegalArgumentException().isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive)) - .withMessageContaining("Buildpack descriptor must contain version") - .withMessageContaining(this.archive.toString()); + .withMessageContaining("Buildpack descriptor must contain version") + .withMessageContaining(this.archive.toString()); } @Test void fromTomlWhenMissingStacksAndOrderThrowsException() { InputStream coordinates = createTomlStream("example/buildpack1", "0.0.1", false, false); assertThatIllegalArgumentException().isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive)) - .withMessageContaining("Buildpack descriptor must contain either 'stacks' or 'order'") - .withMessageContaining(this.archive.toString()); + .withMessageContaining("Buildpack descriptor must contain either 'stacks' or 'order'") + .withMessageContaining(this.archive.toString()); } @Test void fromTomlWhenContainsBothStacksAndOrderThrowsException() { InputStream coordinates = createTomlStream("example/buildpack1", "0.0.1", true, true); assertThatIllegalArgumentException().isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive)) - .withMessageContaining("Buildpack descriptor must not contain both 'stacks' and 'order'") - .withMessageContaining(this.archive.toString()); + .withMessageContaining("Buildpack descriptor must not contain both 'stacks' and 'order'") + .withMessageContaining(this.archive.toString()); } @Test void fromBuildpackMetadataWhenMetadataIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> BuildpackCoordinates.fromBuildpackMetadata(null)) - .withMessage("BuildpackMetadata must not be null"); + .withMessage("BuildpackMetadata must not be null"); } @Test @@ -105,7 +105,7 @@ class BuildpackCoordinatesTests extends AbstractJsonTests { @Test void ofWhenIdIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> BuildpackCoordinates.of(null, null)) - .withMessage("ID must not be empty"); + .withMessage("ID must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackLayersMetadataTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackLayersMetadataTests.java index 779c1607d3..31d692f849 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackLayersMetadataTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackLayersMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,11 +42,11 @@ class BuildpackLayersMetadataTests extends AbstractJsonTests { Image image = Image.of(getContent("buildpack-image.json")); BuildpackLayersMetadata metadata = BuildpackLayersMetadata.fromImage(image); assertThat(metadata.getBuildpack("example/hello-moon", "0.0.3")).extracting("homepage", "layerDiffId") - .containsExactly("https://github.com/example/tree/main/buildpacks/hello-moon", - "sha256:4bfdc8714aee68da6662c43bc28d3b41202c88e915641c356523dabe729814c2"); + .containsExactly("https://github.com/example/tree/main/buildpacks/hello-moon", + "sha256:4bfdc8714aee68da6662c43bc28d3b41202c88e915641c356523dabe729814c2"); assertThat(metadata.getBuildpack("example/hello-world", "0.0.2")).extracting("homepage", "layerDiffId") - .containsExactly("https://github.com/example/tree/main/buildpacks/hello-world", - "sha256:f752fe099c846e501bdc991d1a22f98c055ddc62f01cfc0495fff2c69f8eb940"); + .containsExactly("https://github.com/example/tree/main/buildpacks/hello-world", + "sha256:f752fe099c846e501bdc991d1a22f98c055ddc62f01cfc0495fff2c69f8eb940"); assertThat(metadata.getBuildpack("example/hello-world", "version-does-not-exist")).isNull(); assertThat(metadata.getBuildpack("id-does-not-exist", "9.9.9")).isNull(); } @@ -54,14 +54,14 @@ class BuildpackLayersMetadataTests extends AbstractJsonTests { @Test void fromImageWhenImageIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> BuildpackLayersMetadata.fromImage(null)) - .withMessage("Image must not be null"); + .withMessage("Image must not be null"); } @Test void fromImageWhenImageConfigIsNullThrowsException() { Image image = mock(Image.class); assertThatIllegalArgumentException().isThrownBy(() -> BuildpackLayersMetadata.fromImage(image)) - .withMessage("ImageConfig must not be null"); + .withMessage("ImageConfig must not be null"); } @Test @@ -71,25 +71,25 @@ class BuildpackLayersMetadataTests extends AbstractJsonTests { given(image.getConfig()).willReturn(imageConfig); given(imageConfig.getLabels()).willReturn(Collections.singletonMap("alpha", "a")); assertThatIllegalArgumentException().isThrownBy(() -> BuildpackLayersMetadata.fromImage(image)) - .withMessage("No 'io.buildpacks.buildpack.layers' label found in image config labels 'alpha'"); + .withMessage("No 'io.buildpacks.buildpack.layers' label found in image config labels 'alpha'"); } @Test void fromJsonLoadsMetadata() throws IOException { BuildpackLayersMetadata metadata = BuildpackLayersMetadata - .fromJson(getContentAsString("buildpack-layers-metadata.json")); + .fromJson(getContentAsString("buildpack-layers-metadata.json")); assertThat(metadata.getBuildpack("example/hello-moon", "0.0.3")).extracting("name", "homepage", "layerDiffId") - .containsExactly("Example hello-moon buildpack", - "https://github.com/example/tree/main/buildpacks/hello-moon", - "sha256:4bfdc8714aee68da6662c43bc28d3b41202c88e915641c356523dabe729814c2"); + .containsExactly("Example hello-moon buildpack", + "https://github.com/example/tree/main/buildpacks/hello-moon", + "sha256:4bfdc8714aee68da6662c43bc28d3b41202c88e915641c356523dabe729814c2"); assertThat(metadata.getBuildpack("example/hello-world", "0.0.1")).extracting("name", "homepage", "layerDiffId") - .containsExactly("Example hello-world buildpack", - "https://github.com/example/tree/main/buildpacks/hello-world", - "sha256:1c90e0b80d92555a0523c9ee6500845328fc39ba9dca9d30a877ff759ffbff28"); + .containsExactly("Example hello-world buildpack", + "https://github.com/example/tree/main/buildpacks/hello-world", + "sha256:1c90e0b80d92555a0523c9ee6500845328fc39ba9dca9d30a877ff759ffbff28"); assertThat(metadata.getBuildpack("example/hello-world", "0.0.2")).extracting("name", "homepage", "layerDiffId") - .containsExactly("Example hello-world buildpack", - "https://github.com/example/tree/main/buildpacks/hello-world", - "sha256:f752fe099c846e501bdc991d1a22f98c055ddc62f01cfc0495fff2c69f8eb940"); + .containsExactly("Example hello-world buildpack", + "https://github.com/example/tree/main/buildpacks/hello-world", + "sha256:f752fe099c846e501bdc991d1a22f98c055ddc62f01cfc0495fff2c69f8eb940"); assertThat(metadata.getBuildpack("example/hello-world", "version-does-not-exist")).isNull(); assertThat(metadata.getBuildpack("id-does-not-exist", "9.9.9")).isNull(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackMetadataTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackMetadataTests.java index 413fd2100e..dd9fac9d1a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackMetadataTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,14 +48,14 @@ class BuildpackMetadataTests extends AbstractJsonTests { @Test void fromImageWhenImageIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> BuildpackMetadata.fromImage(null)) - .withMessage("Image must not be null"); + .withMessage("Image must not be null"); } @Test void fromImageWhenImageConfigIsNullThrowsException() { Image image = mock(Image.class); assertThatIllegalArgumentException().isThrownBy(() -> BuildpackMetadata.fromImage(image)) - .withMessage("ImageConfig must not be null"); + .withMessage("ImageConfig must not be null"); } @Test @@ -65,7 +65,7 @@ class BuildpackMetadataTests extends AbstractJsonTests { given(image.getConfig()).willReturn(imageConfig); given(imageConfig.getLabels()).willReturn(Collections.singletonMap("alpha", "a")); assertThatIllegalArgumentException().isThrownBy(() -> BuildpackMetadata.fromImage(image)) - .withMessage("No 'io.buildpacks.buildpackage.metadata' label found in image config labels 'alpha'"); + .withMessage("No 'io.buildpacks.buildpackage.metadata' label found in image config labels 'alpha'"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackReferenceTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackReferenceTests.java index a661aab72b..3b4778d0a0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackReferenceTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackReferenceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ class BuildpackReferenceTests { @Test void ofWhenValueIsEmptyThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> BuildpackReference.of("")) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackResolversTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackResolversTests.java index 12c2038a7d..47daf7ee2b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackResolversTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackResolversTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -96,9 +96,9 @@ class BuildpackResolversTests extends AbstractJsonTests { void resolveAllWithInvalidLocatorThrowsException() { BuildpackReference reference = BuildpackReference.of("unknown-buildpack@0.0.1"); assertThatIllegalArgumentException() - .isThrownBy(() -> BuildpackResolvers.resolveAll(this.resolverContext, Collections.singleton(reference))) - .withMessageContaining("Invalid buildpack reference") - .withMessageContaining("'unknown-buildpack@0.0.1'"); + .isThrownBy(() -> BuildpackResolvers.resolveAll(this.resolverContext, Collections.singleton(reference))) + .withMessageContaining("Invalid buildpack reference") + .withMessageContaining("'unknown-buildpack@0.0.1'"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/DirectoryBuildpackTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/DirectoryBuildpackTests.java index 65a0fed9ff..bb9c95b61b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/DirectoryBuildpackTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/DirectoryBuildpackTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -90,9 +90,9 @@ class DirectoryBuildpackTests { Files.createDirectories(this.buildpackDir.toPath()); BuildpackReference reference = BuildpackReference.of(this.buildpackDir.toString()); assertThatIllegalArgumentException() - .isThrownBy(() -> DirectoryBuildpack.resolve(this.resolverContext, reference)) - .withMessageContaining("Buildpack descriptor 'buildpack.toml' is required") - .withMessageContaining(this.buildpackDir.getAbsolutePath()); + .isThrownBy(() -> DirectoryBuildpack.resolve(this.resolverContext, reference)) + .withMessageContaining("Buildpack descriptor 'buildpack.toml' is required") + .withMessageContaining(this.buildpackDir.getAbsolutePath()); } @Test @@ -133,13 +133,14 @@ class DirectoryBuildpackTests { entries.add(entry); entry = tar.getNextTarEntry(); } - assertThat(entries).extracting("name", "mode").containsExactlyInAnyOrder(tuple("/cnb/", 0755), - tuple("/cnb/buildpacks/", 0755), tuple("/cnb/buildpacks/example_buildpack1/", 0755), - tuple("/cnb/buildpacks/example_buildpack1/0.0.1/", 0755), - tuple("/cnb/buildpacks/example_buildpack1/0.0.1/buildpack.toml", 0644), - tuple("/cnb/buildpacks/example_buildpack1/0.0.1/bin/", 0755), - tuple("/cnb/buildpacks/example_buildpack1/0.0.1/bin/detect", 0744), - tuple("/cnb/buildpacks/example_buildpack1/0.0.1/bin/build", 0744)); + assertThat(entries).extracting("name", "mode") + .containsExactlyInAnyOrder(tuple("/cnb/", 0755), tuple("/cnb/buildpacks/", 0755), + tuple("/cnb/buildpacks/example_buildpack1/", 0755), + tuple("/cnb/buildpacks/example_buildpack1/0.0.1/", 0755), + tuple("/cnb/buildpacks/example_buildpack1/0.0.1/buildpack.toml", 0644), + tuple("/cnb/buildpacks/example_buildpack1/0.0.1/bin/", 0755), + tuple("/cnb/buildpacks/example_buildpack1/0.0.1/bin/detect", 0744), + tuple("/cnb/buildpacks/example_buildpack1/0.0.1/bin/build", 0744)); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/EphemeralBuilderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/EphemeralBuilderTests.java index 53909aa0ff..5a556f62c8 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/EphemeralBuilderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/EphemeralBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -144,7 +144,7 @@ class EphemeralBuilderTests extends AbstractJsonTests { this.creator, this.env, this.buildpacks); ImageConfig config = builder.getArchive().getImageConfig(); assertThat(config.getLabels()) - .contains(entry(EphemeralBuilder.BUILDER_FOR_LABEL_NAME, this.targetImage.toString())); + .contains(entry(EphemeralBuilder.BUILDER_FOR_LABEL_NAME, this.targetImage.toString())); } @Test @@ -164,7 +164,7 @@ class EphemeralBuilderTests extends AbstractJsonTests { "/cnb/buildpacks/example_buildpack3/0.0.3/buildpack.toml"); File orderDirectory = unpack(getLayer(builder.getArchive(), EXISTING_IMAGE_LAYER_COUNT + 3), "order"); assertThat(new File(orderDirectory, "cnb/order.toml")).usingCharset(StandardCharsets.UTF_8) - .hasContent(content("order.toml")); + .hasContent(content("order.toml")); } private void assertBuildpackLayerContent(EphemeralBuilder builder, int index, String s) throws Exception { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ImageBuildpackTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ImageBuildpackTests.java index 7a349006cf..20a483a514 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ImageBuildpackTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ImageBuildpackTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -126,7 +126,7 @@ class ImageBuildpackTests extends AbstractJsonTests { ImageReference imageReference = ImageReference.of("example/buildpack1:1.0.0"); BuildpackResolverContext resolverContext = mock(BuildpackResolverContext.class); given(resolverContext.getBuildpackLayersMetadata()) - .willReturn(BuildpackLayersMetadata.fromJson(getContentAsString("buildpack-layers-metadata.json"))); + .willReturn(BuildpackLayersMetadata.fromJson(getContentAsString("buildpack-layers-metadata.json"))); given(resolverContext.fetchImage(eq(imageReference), eq(ImageType.BUILDPACK))).willReturn(image); willAnswer(this::withMockLayers).given(resolverContext).exportImageLayers(eq(imageReference), any()); BuildpackReference reference = BuildpackReference.of("docker://example/buildpack1:1.0.0"); @@ -141,8 +141,8 @@ class ImageBuildpackTests extends AbstractJsonTests { given(resolverContext.fetchImage(any(), any())).willThrow(IOException.class); BuildpackReference reference = BuildpackReference.of("docker://example/buildpack1"); assertThatIllegalArgumentException().isThrownBy(() -> ImageBuildpack.resolve(resolverContext, reference)) - .withMessageContaining("Error pulling buildpack image") - .withMessageContaining("example/buildpack1:latest"); + .withMessageContaining("Error pulling buildpack image") + .withMessageContaining("example/buildpack1:latest"); } @Test @@ -152,7 +152,7 @@ class ImageBuildpackTests extends AbstractJsonTests { given(resolverContext.fetchImage(any(), any())).willReturn(image); BuildpackReference reference = BuildpackReference.of("docker://example/buildpack1:latest"); assertThatIllegalArgumentException().isThrownBy(() -> ImageBuildpack.resolve(resolverContext, reference)) - .withMessageContaining("No 'io.buildpacks.buildpackage.metadata' label found"); + .withMessageContaining("No 'io.buildpacks.buildpackage.metadata' label found"); } @Test @@ -160,7 +160,7 @@ class ImageBuildpackTests extends AbstractJsonTests { BuildpackReference reference = BuildpackReference.of("docker://buildpack@0.0.1"); BuildpackResolverContext resolverContext = mock(BuildpackResolverContext.class); assertThatIllegalArgumentException().isThrownBy(() -> ImageBuildpack.resolve(resolverContext, reference)) - .withMessageContaining("Unable to parse image reference \"buildpack@0.0.1\""); + .withMessageContaining("Unable to parse image reference \"buildpack@0.0.1\""); } @Test @@ -217,14 +217,14 @@ class ImageBuildpackTests extends AbstractJsonTests { entry = tar.getNextTarEntry(); } } - assertThat(entries).extracting("name", "mode").containsExactlyInAnyOrder( - tuple("cnb/", TarArchiveEntry.DEFAULT_DIR_MODE), - tuple("cnb/buildpacks/", TarArchiveEntry.DEFAULT_DIR_MODE), - tuple("cnb/buildpacks/example_buildpack/", TarArchiveEntry.DEFAULT_DIR_MODE), - tuple("cnb/buildpacks/example_buildpack/0.0.1/", TarArchiveEntry.DEFAULT_DIR_MODE), - tuple("cnb/buildpacks/example_buildpack/0.0.1/buildpack.toml", TarArchiveEntry.DEFAULT_FILE_MODE), - tuple("cnb/buildpacks/example_buildpack/0.0.1/" + this.longFilePath, - TarArchiveEntry.DEFAULT_FILE_MODE)); + assertThat(entries).extracting("name", "mode") + .containsExactlyInAnyOrder(tuple("cnb/", TarArchiveEntry.DEFAULT_DIR_MODE), + tuple("cnb/buildpacks/", TarArchiveEntry.DEFAULT_DIR_MODE), + tuple("cnb/buildpacks/example_buildpack/", TarArchiveEntry.DEFAULT_DIR_MODE), + tuple("cnb/buildpacks/example_buildpack/0.0.1/", TarArchiveEntry.DEFAULT_DIR_MODE), + tuple("cnb/buildpacks/example_buildpack/0.0.1/buildpack.toml", TarArchiveEntry.DEFAULT_FILE_MODE), + tuple("cnb/buildpacks/example_buildpack/0.0.1/" + this.longFilePath, + TarArchiveEntry.DEFAULT_FILE_MODE)); } private void assertAppliesNoLayers(Buildpack buildpack) throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/LifecycleTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/LifecycleTests.java index ed188ba520..e333cf9b45 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/LifecycleTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/LifecycleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -135,7 +135,7 @@ class LifecycleTests { Lifecycle lifecycle = createLifecycle(); lifecycle.execute(); assertThatIllegalStateException().isThrownBy(lifecycle::execute) - .withMessage("Lifecycle has already been executed"); + .withMessage("Lifecycle has already been executed"); } @Test @@ -144,7 +144,7 @@ class LifecycleTests { given(this.docker.container().create(any(), any())).willAnswer(answerWithGeneratedContainerId()); given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(9, null)); assertThatExceptionOfType(BuilderException.class).isThrownBy(() -> createLifecycle().execute()) - .withMessage("Builder lifecycle 'creator' failed with status code 9"); + .withMessage("Builder lifecycle 'creator' failed with status code 9"); } @Test @@ -165,8 +165,8 @@ class LifecycleTests { given(this.docker.container().create(any(), any())).willAnswer(answerWithGeneratedContainerId()); given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null)); assertThatIllegalStateException() - .isThrownBy(() -> createLifecycle("builder-metadata-unsupported-api.json").execute()) - .withMessageContaining("Detected platform API versions '0.2' are not included in supported versions"); + .isThrownBy(() -> createLifecycle("builder-metadata-unsupported-api.json").execute()) + .withMessageContaining("Detected platform API versions '0.2' are not included in supported versions"); } @Test @@ -175,9 +175,8 @@ class LifecycleTests { given(this.docker.container().create(any(), any())).willAnswer(answerWithGeneratedContainerId()); given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null)); assertThatIllegalStateException() - .isThrownBy(() -> createLifecycle("builder-metadata-unsupported-apis.json").execute()) - .withMessageContaining( - "Detected platform API versions '0.1,0.2' are not included in supported versions"); + .isThrownBy(() -> createLifecycle("builder-metadata-unsupported-apis.json").execute()) + .withMessageContaining("Detected platform API versions '0.1,0.2' are not included in supported versions"); } @Test @@ -213,7 +212,7 @@ class LifecycleTests { given(this.docker.container().create(any(), any())).willAnswer(answerWithGeneratedContainerId()); given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null)); BuildRequest request = getTestRequest().withBuildCache(Cache.volume("build-volume")) - .withLaunchCache(Cache.volume("launch-volume")); + .withLaunchCache(Cache.volume("launch-volume")); createLifecycle(request).execute(); assertPhaseWasRun("creator", withExpectedConfig("lifecycle-creator-cache-volumes.json")); assertThat(this.out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/LifecycleVersionTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/LifecycleVersionTests.java index 2f645c5b8b..d6a01d6b7a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/LifecycleVersionTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/LifecycleVersionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,19 +31,19 @@ class LifecycleVersionTests { @Test void parseWhenValueIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> LifecycleVersion.parse(null)) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test void parseWhenTooLongThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> LifecycleVersion.parse("v1.2.3.4")) - .withMessage("Malformed version number '1.2.3.4'"); + .withMessage("Malformed version number '1.2.3.4'"); } @Test void parseWhenNonNumericThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> LifecycleVersion.parse("v1.2.3a")) - .withMessage("Malformed version number '1.2.3a'"); + .withMessage("Malformed version number '1.2.3a'"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/StackIdTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/StackIdTests.java index 3204772eab..c69ce60fb3 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/StackIdTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/StackIdTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ class StackIdTests { @Test void fromImageWhenImageIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> StackId.fromImage(null)) - .withMessage("Image must not be null"); + .withMessage("Image must not be null"); } @Test @@ -48,7 +48,7 @@ class StackIdTests { ImageConfig imageConfig = mock(ImageConfig.class); given(image.getConfig()).willReturn(imageConfig); assertThatIllegalStateException().isThrownBy(() -> StackId.fromImage(image)) - .withMessage("Missing 'io.buildpacks.stack.id' stack label"); + .withMessage("Missing 'io.buildpacks.stack.id' stack label"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/TarGzipBuildpackTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/TarGzipBuildpackTests.java index 9bc68cb8bb..561d370719 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/TarGzipBuildpackTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/TarGzipBuildpackTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,8 +73,8 @@ class TarGzipBuildpackTests { Path compressedArchive = this.testTarGzip.createEmptyArchive(); BuildpackReference reference = BuildpackReference.of(compressedArchive.toString()); assertThatIllegalArgumentException().isThrownBy(() -> TarGzipBuildpack.resolve(this.resolverContext, reference)) - .withMessageContaining("Buildpack descriptor 'buildpack.toml' is required") - .withMessageContaining(compressedArchive.toString()); + .withMessageContaining("Buildpack descriptor 'buildpack.toml' is required") + .withMessageContaining(compressedArchive.toString()); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/TestTarGzip.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/TestTarGzip.java index 4c50d71c4d..90e879b26c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/TestTarGzip.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/TestTarGzip.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -123,7 +123,7 @@ class TestTarGzip { assertThat(tar.getNextEntry().getName()).isEqualTo("cnb/buildpacks/example_buildpack1/"); assertThat(tar.getNextEntry().getName()).isEqualTo("cnb/buildpacks/example_buildpack1/0.0.1/"); assertThat(tar.getNextEntry().getName()) - .isEqualTo("cnb/buildpacks/example_buildpack1/0.0.1/buildpack.toml"); + .isEqualTo("cnb/buildpacks/example_buildpack1/0.0.1/buildpack.toml"); assertThat(tar.getNextEntry().getName()).isEqualTo("cnb/buildpacks/example_buildpack1/0.0.1/bin/"); assertThat(tar.getNextEntry().getName()).isEqualTo("cnb/buildpacks/example_buildpack1/0.0.1/bin/detect"); assertThat(tar.getNextEntry().getName()).isEqualTo("cnb/buildpacks/example_buildpack1/0.0.1/bin/build"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiIntegrationTests.java index b5242e2be6..cff7b111eb 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,9 @@ class DockerApiIntegrationTests { @Test void pullImage() throws IOException { - this.docker.image().pull(ImageReference.of("gcr.io/paketo-buildpacks/builder:base"), - new TotalProgressPullListener(new TotalProgressBar("Pulling: "))); + this.docker.image() + .pull(ImageReference.of("gcr.io/paketo-buildpacks/builder:base"), + new TotalProgressPullListener(new TotalProgressBar("Pulling: "))); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiTests.java index e6a76b6f41..a4e4d54362 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -151,13 +151,13 @@ class DockerApiTests { @Test void pullWhenReferenceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.pull(null, this.pullListener)) - .withMessage("Reference must not be null"); + .withMessage("Reference must not be null"); } @Test void pullWhenListenerIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.pull(ImageReference.of("ubuntu"), null)) - .withMessage("Listener must not be null"); + .withMessage("Listener must not be null"); } @Test @@ -193,14 +193,14 @@ class DockerApiTests { @Test void pushWhenReferenceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.push(null, this.pushListener, null)) - .withMessage("Reference must not be null"); + .withMessage("Reference must not be null"); } @Test void pushWhenListenerIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.api.push(ImageReference.of("ubuntu"), null, null)) - .withMessage("Listener must not be null"); + .isThrownBy(() -> this.api.push(ImageReference.of("ubuntu"), null, null)) + .withMessage("Listener must not be null"); } @Test @@ -221,21 +221,21 @@ class DockerApiTests { URI pushUri = new URI(IMAGES_URL + "/localhost:5000/ubuntu/push"); given(http().post(pushUri, "auth token")).willReturn(responseOf("push-stream-with-error.json")); assertThatIllegalStateException() - .isThrownBy(() -> this.api.push(reference, this.pushListener, "auth token")) - .withMessageContaining("test message"); + .isThrownBy(() -> this.api.push(reference, this.pushListener, "auth token")) + .withMessageContaining("test message"); } @Test void loadWhenArchiveIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.load(null, UpdateListener.none())) - .withMessage("Archive must not be null"); + .withMessage("Archive must not be null"); } @Test void loadWhenListenerIsNullThrowsException() { ImageArchive archive = mock(ImageArchive.class); assertThatIllegalArgumentException().isThrownBy(() -> this.api.load(archive, null)) - .withMessage("Listener must not be null"); + .withMessage("Listener must not be null"); } @Test // gh-23130 @@ -245,7 +245,7 @@ class DockerApiTests { URI loadUri = new URI(IMAGES_URL + "/load"); given(http().post(eq(loadUri), eq("application/x-tar"), any())).willReturn(emptyResponse()); assertThatIllegalStateException().isThrownBy(() -> this.api.load(archive, this.loadListener)) - .withMessageContaining("Invalid response received"); + .withMessageContaining("Invalid response received"); } @Test @@ -268,13 +268,13 @@ class DockerApiTests { @Test void removeWhenReferenceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.remove(null, true)) - .withMessage("Reference must not be null"); + .withMessage("Reference must not be null"); } @Test void removeRemovesContainer() throws Exception { ImageReference reference = ImageReference - .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); URI removeUri = new URI(IMAGES_URL + "/docker.io/library/ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); given(http().delete(removeUri)).willReturn(emptyResponse()); @@ -285,7 +285,7 @@ class DockerApiTests { @Test void removeWhenForceIsTrueRemovesContainer() throws Exception { ImageReference reference = ImageReference - .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); URI removeUri = new URI(IMAGES_URL + "/docker.io/library/ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d?force=1"); given(http().delete(removeUri)).willReturn(emptyResponse()); @@ -296,7 +296,7 @@ class DockerApiTests { @Test void inspectWhenReferenceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.inspect(null)) - .withMessage("Reference must not be null"); + .withMessage("Reference must not be null"); } @Test @@ -318,7 +318,7 @@ class DockerApiTests { void exportLayersWhenExportsIsNullThrowsException() { ImageReference reference = ImageReference.of("gcr.io/paketo-buildpacks/builder:base"); assertThatIllegalArgumentException().isThrownBy(() -> this.api.exportLayers(reference, null)) - .withMessage("Exports must not be null"); + .withMessage("Exports must not be null"); } @Test @@ -339,26 +339,26 @@ class DockerApiTests { } } }); - assertThat(contents).hasSize(3).containsKeys( - "1bf6c63a1e9ed1dd7cb961273bf60b8e0f440361faf273baf866f408e4910601/layer.tar", - "8fdfb915302159a842cbfae6faec5311b00c071ebf14e12da7116ae7532e9319/layer.tar", - "93cd584bb189bfca4f51744bd19d836fd36da70710395af5a1523ee88f208c6a/layer.tar"); + assertThat(contents).hasSize(3) + .containsKeys("1bf6c63a1e9ed1dd7cb961273bf60b8e0f440361faf273baf866f408e4910601/layer.tar", + "8fdfb915302159a842cbfae6faec5311b00c071ebf14e12da7116ae7532e9319/layer.tar", + "93cd584bb189bfca4f51744bd19d836fd36da70710395af5a1523ee88f208c6a/layer.tar"); assertThat(contents.get("1bf6c63a1e9ed1dd7cb961273bf60b8e0f440361faf273baf866f408e4910601/layer.tar")) - .containsExactly("etc/", "etc/apt/", "etc/apt/sources.list"); + .containsExactly("etc/", "etc/apt/", "etc/apt/sources.list"); } @Test void tagWhenReferenceIsNullThrowsException() { ImageReference tag = ImageReference.of("localhost:5000/ubuntu"); assertThatIllegalArgumentException().isThrownBy(() -> this.api.tag(null, tag)) - .withMessage("SourceReference must not be null"); + .withMessage("SourceReference must not be null"); } @Test void tagWhenTargetIsNullThrowsException() { ImageReference reference = ImageReference.of("localhost:5000/ubuntu"); assertThatIllegalArgumentException().isThrownBy(() -> this.api.tag(reference, null)) - .withMessage("TargetReference must not be null"); + .withMessage("TargetReference must not be null"); } @Test @@ -392,7 +392,7 @@ class DockerApiTests { @Test void createWhenConfigIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.create(null)) - .withMessage("Config must not be null"); + .withMessage("Config must not be null"); } @Test @@ -401,7 +401,7 @@ class DockerApiTests { ContainerConfig config = ContainerConfig.of(imageReference, (update) -> update.withCommand("/bin/bash")); URI createUri = new URI(CONTAINERS_URL + "/create"); given(http().post(eq(createUri), eq("application/json"), any())) - .willReturn(responseOf("create-container-response.json")); + .willReturn(responseOf("create-container-response.json")); ContainerReference containerReference = this.api.create(config); assertThat(containerReference.toString()).isEqualTo("e90e34656806"); then(http()).should().post(any(), any(), this.writer.capture()); @@ -421,7 +421,7 @@ class DockerApiTests { ContainerContent content = ContainerContent.of(archive); URI createUri = new URI(CONTAINERS_URL + "/create"); given(http().post(eq(createUri), eq("application/json"), any())) - .willReturn(responseOf("create-container-response.json")); + .willReturn(responseOf("create-container-response.json")); URI uploadUri = new URI(CONTAINERS_URL + "/e90e34656806/archive?path=%2F"); given(http().put(eq(uploadUri), eq("application/x-tar"), any())).willReturn(emptyResponse()); ContainerReference containerReference = this.api.create(config, content); @@ -438,7 +438,7 @@ class DockerApiTests { @Test void startWhenReferenceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.start(null)) - .withMessage("Reference must not be null"); + .withMessage("Reference must not be null"); } @Test @@ -453,14 +453,14 @@ class DockerApiTests { @Test void logsWhenReferenceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.logs(null, UpdateListener.none())) - .withMessage("Reference must not be null"); + .withMessage("Reference must not be null"); } @Test void logsWhenListenerIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.api.logs(ContainerReference.of("e90e34656806"), null)) - .withMessage("Listener must not be null"); + .isThrownBy(() -> this.api.logs(ContainerReference.of("e90e34656806"), null)) + .withMessage("Listener must not be null"); } @Test @@ -478,7 +478,7 @@ class DockerApiTests { @Test void waitWhenReferenceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.wait(null)) - .withMessage("Reference must not be null"); + .withMessage("Reference must not be null"); } @Test @@ -493,7 +493,7 @@ class DockerApiTests { @Test void removeWhenReferenceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.remove(null, true)) - .withMessage("Reference must not be null"); + .withMessage("Reference must not be null"); } @Test @@ -529,7 +529,7 @@ class DockerApiTests { @Test void deleteWhenNameIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.delete(null, false)) - .withMessage("Name must not be null"); + .withMessage("Name must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/LogUpdateEventTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/LogUpdateEventTests.java index e8a6fc4297..98645c19a7 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/LogUpdateEventTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/LogUpdateEventTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,11 +37,11 @@ class LogUpdateEventTests { List events = readAll("log-update-event.stream"); assertThat(events).hasSize(7); assertThat(events.get(0).toString()) - .isEqualTo("Analyzing image '307c032c4ceaa6330b6c02af945a1fe56a8c3c27c28268574b217c1d38b093cf'"); + .isEqualTo("Analyzing image '307c032c4ceaa6330b6c02af945a1fe56a8c3c27c28268574b217c1d38b093cf'"); assertThat(events.get(1).toString()) - .isEqualTo("Writing metadata for uncached layer 'org.cloudfoundry.openjdk:openjdk-jre'"); + .isEqualTo("Writing metadata for uncached layer 'org.cloudfoundry.openjdk:openjdk-jre'"); assertThat(events.get(2).toString()) - .isEqualTo("Using cached launch layer 'org.cloudfoundry.jvmapplication:executable-jar'"); + .isEqualTo("Using cached launch layer 'org.cloudfoundry.jvmapplication:executable-jar'"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/TotalProgressBarTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/TotalProgressBarTests.java index 345e0d4544..d7b20f503c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/TotalProgressBarTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/TotalProgressBarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ class TotalProgressBarTests { assertThat(out.toString()).isEqualTo("prefix: [ #########################"); bar.accept(new TotalProgressEvent(100)); assertThat(out.toString()) - .isEqualTo(String.format("prefix: [ ################################################## ]%n")); + .isEqualTo(String.format("prefix: [ ################################################## ]%n")); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/TotalProgressEventTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/TotalProgressEventTests.java index e018c34116..1cafbd8830 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/TotalProgressEventTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/TotalProgressEventTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,13 +38,13 @@ class TotalProgressEventTests { @Test void createWhenPercentLessThanZeroThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new TotalProgressEvent(-1)) - .withMessage("Percent must be in the range 0 to 100"); + .withMessage("Percent must be in the range 0 to 100"); } @Test void createWhenEventMoreThanOneHundredThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new TotalProgressEvent(101)) - .withMessage("Percent must be in the range 0 to 100"); + .withMessage("Percent must be in the range 0 to 100"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/CertificateParserTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/CertificateParserTests.java index 479817196c..381e475b59 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/CertificateParserTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/CertificateParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,7 +74,7 @@ class CertificateParserTests { void parseWithInvalidPathWillThrowException() throws URISyntaxException { Path path = Paths.get(new URI("file:///bad/path/cert.pem")); assertThatIllegalStateException().isThrownBy(() -> CertificateParser.parse(path)) - .withMessageContaining(path.toString()); + .withMessageContaining(path.toString()); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/PrivateKeyParserTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/PrivateKeyParserTests.java index f55f79aaf3..8ba45fa513 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/PrivateKeyParserTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/PrivateKeyParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,7 +87,7 @@ class PrivateKeyParserTests { void parseWithNonKeyFileWillThrowException() throws IOException { Path path = this.fileWriter.writeFile("text.pem", "plain text"); assertThatIllegalStateException().isThrownBy(() -> PrivateKeyParser.parse(path)) - .withMessageContaining(path.toString()); + .withMessageContaining(path.toString()); Files.delete(path); } @@ -95,7 +95,7 @@ class PrivateKeyParserTests { void parseWithInvalidPathWillThrowException() throws URISyntaxException { Path path = Paths.get(new URI("file:///bad/path/key.pem")); assertThatIllegalStateException().isThrownBy(() -> PrivateKeyParser.parse(path)) - .withMessageContaining(path.toString()); + .withMessageContaining(path.toString()); } @Nested diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/DockerConnectionExceptionTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/DockerConnectionExceptionTests.java index 0501c5364c..68c5546e1a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/DockerConnectionExceptionTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/DockerConnectionExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,20 +35,20 @@ class DockerConnectionExceptionTests { @Test void createWhenHostIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new DockerConnectionException(null, null)) - .withMessage("Host must not be null"); + .withMessage("Host must not be null"); } @Test void createWhenCauseIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new DockerConnectionException(HOST, null)) - .withMessage("Cause must not be null"); + .withMessage("Cause must not be null"); } @Test void createWithIOException() { DockerConnectionException exception = new DockerConnectionException(HOST, new IOException("error")); assertThat(exception.getMessage()) - .contains("Connection to the Docker daemon at 'docker://localhost/' failed with error \"error\""); + .contains("Connection to the Docker daemon at 'docker://localhost/' failed with error \"error\""); } @Test @@ -56,7 +56,7 @@ class DockerConnectionExceptionTests { DockerConnectionException exception = new DockerConnectionException(HOST, new IOException(new com.sun.jna.LastErrorException("root cause"))); assertThat(exception.getMessage()) - .contains("Connection to the Docker daemon at 'docker://localhost/' failed with error \"root cause\""); + .contains("Connection to the Docker daemon at 'docker://localhost/' failed with error \"root cause\""); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/DockerEngineExceptionTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/DockerEngineExceptionTests.java index d3a76a38ce..72c3ff0321 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/DockerEngineExceptionTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/DockerEngineExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,15 +56,15 @@ class DockerEngineExceptionTests { @Test void createWhenHostIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DockerEngineException(null, null, 404, null, NO_ERRORS, NO_MESSAGE)) - .withMessage("Host must not be null"); + .isThrownBy(() -> new DockerEngineException(null, null, 404, null, NO_ERRORS, NO_MESSAGE)) + .withMessage("Host must not be null"); } @Test void createWhenUriIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DockerEngineException(HOST, null, 404, null, NO_ERRORS, NO_MESSAGE)) - .withMessage("URI must not be null"); + .isThrownBy(() -> new DockerEngineException(HOST, null, 404, null, NO_ERRORS, NO_MESSAGE)) + .withMessage("URI must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/HttpClientTransportTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/HttpClientTransportTests.java index 397aa5194c..96a6b3dba1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/HttpClientTransportTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/HttpClientTransportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -264,10 +264,10 @@ class HttpClientTransportTests { given(this.entity.getContent()).willReturn(getClass().getResourceAsStream("errors.json")); given(this.statusLine.getStatusCode()).willReturn(404); assertThatExceptionOfType(DockerEngineException.class).isThrownBy(() -> this.http.get(this.uri)) - .satisfies((ex) -> { - assertThat(ex.getErrors()).hasSize(2); - assertThat(ex.getResponseMessage()).isNull(); - }); + .satisfies((ex) -> { + assertThat(ex.getErrors()).hasSize(2); + assertThat(ex.getResponseMessage()).isNull(); + }); } @Test @@ -275,10 +275,10 @@ class HttpClientTransportTests { givenClientWillReturnResponse(); given(this.statusLine.getStatusCode()).willReturn(500); assertThatExceptionOfType(DockerEngineException.class).isThrownBy(() -> this.http.get(this.uri)) - .satisfies((ex) -> { - assertThat(ex.getErrors()).isNull(); - assertThat(ex.getResponseMessage()).isNull(); - }); + .satisfies((ex) -> { + assertThat(ex.getErrors()).isNull(); + assertThat(ex.getResponseMessage()).isNull(); + }); } @Test @@ -287,10 +287,10 @@ class HttpClientTransportTests { given(this.entity.getContent()).willReturn(getClass().getResourceAsStream("message.json")); given(this.statusLine.getStatusCode()).willReturn(500); assertThatExceptionOfType(DockerEngineException.class).isThrownBy(() -> this.http.get(this.uri)) - .satisfies((ex) -> { - assertThat(ex.getErrors()).isNull(); - assertThat(ex.getResponseMessage().getMessage()).contains("test message"); - }); + .satisfies((ex) -> { + assertThat(ex.getErrors()).isNull(); + assertThat(ex.getResponseMessage().getMessage()).contains("test message"); + }); } @Test @@ -299,18 +299,18 @@ class HttpClientTransportTests { given(this.entity.getContent()).willReturn(this.content); given(this.statusLine.getStatusCode()).willReturn(500); assertThatExceptionOfType(DockerEngineException.class).isThrownBy(() -> this.http.get(this.uri)) - .satisfies((ex) -> { - assertThat(ex.getErrors()).isNull(); - assertThat(ex.getResponseMessage()).isNull(); - }); + .satisfies((ex) -> { + assertThat(ex.getErrors()).isNull(); + assertThat(ex.getResponseMessage()).isNull(); + }); } @Test void executeWhenClientThrowsIOExceptionRethrowsAsDockerException() throws IOException { given(this.client.execute(any(HttpHost.class), any(HttpRequest.class))) - .willThrow(new IOException("test IO exception")); + .willThrow(new IOException("test IO exception")); assertThatExceptionOfType(DockerConnectionException.class).isThrownBy(() -> this.http.get(this.uri)) - .satisfies((ex) -> assertThat(ex.getMessage()).contains("test IO exception")); + .satisfies((ex) -> assertThat(ex.getMessage()).contains("test IO exception")); } private String writeToString(HttpEntity entity) throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/RemoteHttpClientTransportTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/RemoteHttpClientTransportTests.java index 0bf2fb3685..7eb2fb5d06 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/RemoteHttpClientTransportTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/RemoteHttpClientTransportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -80,7 +80,7 @@ class RemoteHttpClientTransportTests { SslContextFactory sslContextFactory = mock(SslContextFactory.class); given(sslContextFactory.forDirectory("/test-cert-path")).willReturn(SSLContext.getDefault()); ResolvedDockerHost dockerHost = ResolvedDockerHost - .from(new DockerHost("tcp://192.168.1.2:2376", true, "/test-cert-path")); + .from(new DockerHost("tcp://192.168.1.2:2376", true, "/test-cert-path")); RemoteHttpClientTransport transport = RemoteHttpClientTransport.createIfPossible(dockerHost, sslContextFactory); assertThat(transport.getHost()).satisfies(hostOf("https", "192.168.1.2", 2376)); } @@ -89,7 +89,7 @@ class RemoteHttpClientTransportTests { void createIfPossibleWhenTlsVerifyWithMissingCertPathThrowsException() { ResolvedDockerHost dockerHost = ResolvedDockerHost.from(new DockerHost("tcp://192.168.1.2:2376", true, null)); assertThatIllegalArgumentException().isThrownBy(() -> RemoteHttpClientTransport.createIfPossible(dockerHost)) - .withMessageContaining("Docker host TLS verification requires trust material"); + .withMessageContaining("Docker host TLS verification requires trust material"); } private Consumer hostOf(String scheme, String hostName, int port) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/BindingTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/BindingTests.java index c8eb1783d8..3f0ec68cbe 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/BindingTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/BindingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ class BindingTests { @Test void ofWithNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Binding.of(null)) - .withMessageContaining("Value must not be null"); + .withMessageContaining("Value must not be null"); } @Test @@ -49,13 +49,13 @@ class BindingTests { @Test void fromWithNullSourceThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Binding.from((String) null, "container-dest")) - .withMessageContaining("Source must not be null"); + .withMessageContaining("Source must not be null"); } @Test void fromWithNullDestinationThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Binding.from("host-src", null)) - .withMessageContaining("Destination must not be null"); + .withMessageContaining("Destination must not be null"); } @Test @@ -67,7 +67,7 @@ class BindingTests { @Test void fromVolumeNameSourceWithNullSourceThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Binding.from((VolumeName) null, "container-dest")) - .withMessageContaining("SourceVolume must not be null"); + .withMessageContaining("SourceVolume must not be null"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerConfigTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerConfigTests.java index 0632602744..4807bd73b8 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerConfigTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerConfigTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ class ContainerConfigTests extends AbstractJsonTests { void ofWhenUpdateIsNullThrowsException() { ImageReference imageReference = ImageReference.of("ubuntu:bionic"); assertThatIllegalArgumentException().isThrownBy(() -> ContainerConfig.of(imageReference, null)) - .withMessage("Update must not be null"); + .withMessage("Update must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerContentTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerContentTests.java index c5390ac1de..e6027da592 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerContentTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerContentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,21 +34,21 @@ class ContainerContentTests { @Test void ofWhenArchiveIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ContainerContent.of(null)) - .withMessage("Archive must not be null"); + .withMessage("Archive must not be null"); } @Test void ofWhenDestinationPathIsNullThrowsException() { TarArchive archive = mock(TarArchive.class); assertThatIllegalArgumentException().isThrownBy(() -> ContainerContent.of(archive, null)) - .withMessage("DestinationPath must not be empty"); + .withMessage("DestinationPath must not be empty"); } @Test void ofWhenDestinationPathIsEmptyThrowsException() { TarArchive archive = mock(TarArchive.class); assertThatIllegalArgumentException().isThrownBy(() -> ContainerContent.of(archive, "")) - .withMessage("DestinationPath must not be empty"); + .withMessage("DestinationPath must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerReferenceTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerReferenceTests.java index 43f8cc33cf..10b9af5df2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerReferenceTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerReferenceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,30 +31,30 @@ class ContainerReferenceTests { @Test void ofCreatesInstance() { ContainerReference reference = ContainerReference - .of("92691aec176333f7ae890de9aaeeafef11166efcaa3908edf83eb44a5c943781"); + .of("92691aec176333f7ae890de9aaeeafef11166efcaa3908edf83eb44a5c943781"); assertThat(reference.toString()).isEqualTo("92691aec176333f7ae890de9aaeeafef11166efcaa3908edf83eb44a5c943781"); } @Test void ofWhenNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ContainerReference.of(null)) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test void ofWhenEmptyThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ContainerReference.of("")) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test void hashCodeAndEquals() { ContainerReference r1 = ContainerReference - .of("92691aec176333f7ae890de9aaeeafef11166efcaa3908edf83eb44a5c943781"); + .of("92691aec176333f7ae890de9aaeeafef11166efcaa3908edf83eb44a5c943781"); ContainerReference r2 = ContainerReference - .of("92691aec176333f7ae890de9aaeeafef11166efcaa3908edf83eb44a5c943781"); + .of("92691aec176333f7ae890de9aaeeafef11166efcaa3908edf83eb44a5c943781"); ContainerReference r3 = ContainerReference - .of("02691aec176333f7ae890de9aaeeafef11166efcaa3908edf83eb44a5c943781"); + .of("02691aec176333f7ae890de9aaeeafef11166efcaa3908edf83eb44a5c943781"); assertThat(r1.hashCode()).isEqualTo(r2.hashCode()); assertThat(r1).isEqualTo(r1).isEqualTo(r2).isNotEqualTo(r3); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageConfigTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageConfigTests.java index 38eb2e6787..592e1abd76 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageConfigTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageConfigTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,9 +68,9 @@ class ImageConfigTests extends AbstractJsonTests { void updateWithLabelUpdatesLabels() throws Exception { ImageConfig imageConfig = getImageConfig(); ImageConfig updatedImageConfig = imageConfig - .copy((update) -> update.withLabel("io.buildpacks.stack.id", "test")); + .copy((update) -> update.withLabel("io.buildpacks.stack.id", "test")); assertThat(imageConfig.getLabels()).hasSize(4) - .contains(entry("io.buildpacks.stack.id", "org.cloudfoundry.stacks.cflinuxfs3")); + .contains(entry("io.buildpacks.stack.id", "org.cloudfoundry.stacks.cflinuxfs3")); assertThat(updatedImageConfig.getLabels()).hasSize(4).contains(entry("io.buildpacks.stack.id", "test")); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageNameTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageNameTests.java index c1e667e093..44d1278dfa 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageNameTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageNameTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -118,7 +118,7 @@ class ImageNameTests { @Test void ofWhenNameIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ImageName.of(null)) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test @@ -129,20 +129,23 @@ class ImageNameTests { @Test void ofWhenContainsUppercaseThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ImageName.of("Test")) - .withMessageContaining("Unable to parse name").withMessageContaining("Test"); + .withMessageContaining("Unable to parse name") + .withMessageContaining("Test"); } @Test void ofWhenNameIncludesTagThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ImageName.of("ubuntu:latest")) - .withMessageContaining("Unable to parse name").withMessageContaining(":latest"); + .withMessageContaining("Unable to parse name") + .withMessageContaining(":latest"); } @Test void ofWhenNameIncludeDigestThrowsException() { assertThatIllegalArgumentException().isThrownBy( () -> ImageName.of("ubuntu@sha256:47bfdb88c3ae13e488167607973b7688f69d9e8c142c2045af343ec199649c09")) - .withMessageContaining("Unable to parse name").withMessageContaining("@sha256:47b"); + .withMessageContaining("Unable to parse name") + .withMessageContaining("@sha256:47b"); } @Test @@ -153,8 +156,10 @@ class ImageNameTests { ImageName n4 = ImageName.of("docker.io/library/ubuntu"); ImageName n5 = ImageName.of("index.docker.io/library/ubuntu"); ImageName n6 = ImageName.of("alpine"); - assertThat(n1.hashCode()).isEqualTo(n2.hashCode()).isEqualTo(n3.hashCode()).isEqualTo(n4.hashCode()) - .isEqualTo(n5.hashCode()); + assertThat(n1.hashCode()).isEqualTo(n2.hashCode()) + .isEqualTo(n3.hashCode()) + .isEqualTo(n4.hashCode()) + .isEqualTo(n5.hashCode()); assertThat(n1).isEqualTo(n1).isEqualTo(n2).isEqualTo(n3).isEqualTo(n4).isNotEqualTo(n6); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageReferenceTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageReferenceTests.java index e19c0e14fb..b5ad72e1ef 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageReferenceTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageReferenceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -115,12 +115,12 @@ class ImageReferenceTests { @Test void ofNameAndDigest() { ImageReference reference = ImageReference - .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); assertThat(reference.getDomain()).isEqualTo("docker.io"); assertThat(reference.getName()).isEqualTo("library/ubuntu"); assertThat(reference.getTag()).isNull(); assertThat(reference.getDigest()) - .isEqualTo("sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + .isEqualTo("sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); assertThat(reference.toString()).isEqualTo( "docker.io/library/ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); } @@ -128,25 +128,25 @@ class ImageReferenceTests { @Test void ofNameAndTagAndDigest() { ImageReference reference = ImageReference - .of("ubuntu:bionic@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + .of("ubuntu:bionic@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); assertThat(reference.getDomain()).isEqualTo("docker.io"); assertThat(reference.getName()).isEqualTo("library/ubuntu"); assertThat(reference.getTag()).isEqualTo("bionic"); assertThat(reference.getDigest()) - .isEqualTo("sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + .isEqualTo("sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); assertThat(reference.toString()).isEqualTo( "docker.io/library/ubuntu:bionic@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); } @Test void ofCustomDomainAndPortWithTag() { - ImageReference reference = ImageReference.of( - "example.com:8080/canonical/ubuntu:bionic@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + ImageReference reference = ImageReference + .of("example.com:8080/canonical/ubuntu:bionic@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); assertThat(reference.getDomain()).isEqualTo("example.com:8080"); assertThat(reference.getName()).isEqualTo("canonical/ubuntu"); assertThat(reference.getTag()).isEqualTo("bionic"); assertThat(reference.getDigest()) - .isEqualTo("sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + .isEqualTo("sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); assertThat(reference.toString()).isEqualTo( "example.com:8080/canonical/ubuntu:bionic@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); } @@ -174,9 +174,9 @@ class ImageReferenceTests { @Test void ofWhenHasIllegalCharacter() { assertThatIllegalArgumentException() - .isThrownBy(() -> ImageReference - .of("registry.example.com/example/example-app:1.6.0-dev.2.uncommitted+wip.foo.c75795d")) - .withMessageContaining("Unable to parse image reference"); + .isThrownBy(() -> ImageReference + .of("registry.example.com/example/example-app:1.6.0-dev.2.uncommitted+wip.foo.c75795d")) + .withMessageContaining("Unable to parse image reference"); } @Test @@ -219,15 +219,16 @@ class ImageReferenceTests { @Test void randomWherePrefixIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ImageReference.random(null)) - .withMessage("Prefix must not be null"); + .withMessage("Prefix must not be null"); } @Test void inTaggedFormWhenHasDigestThrowsException() { ImageReference reference = ImageReference - .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); - assertThatIllegalStateException().isThrownBy(() -> reference.inTaggedForm()).withMessage( - "Image reference 'docker.io/library/ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d' cannot contain a digest"); + .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + assertThatIllegalStateException().isThrownBy(() -> reference.inTaggedForm()) + .withMessage( + "Image reference 'docker.io/library/ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d' cannot contain a digest"); } @Test @@ -245,7 +246,7 @@ class ImageReferenceTests { @Test void inTaggedOrDigestFormWhenHasDigestUsesDigest() { ImageReference reference = ImageReference - .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); assertThat(reference.inTaggedOrDigestForm().toString()).isEqualTo( "docker.io/library/ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageTests.java index c4535b23a4..8497a9b591 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,9 +56,9 @@ class ImageTests extends AbstractJsonTests { List layers = image.getLayers(); assertThat(layers).hasSize(46); assertThat(layers.get(0).toString()) - .isEqualTo("sha256:733a8e5ce32984099ef675fce04730f6e2a6dcfdf5bd292fea01a8f936265342"); + .isEqualTo("sha256:733a8e5ce32984099ef675fce04730f6e2a6dcfdf5bd292fea01a8f936265342"); assertThat(layers.get(45).toString()) - .isEqualTo("sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef"); + .isEqualTo("sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/LayerIdTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/LayerIdTests.java index 34d9bd52e2..0d1c66a0d3 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/LayerIdTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/LayerIdTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ class LayerIdTests { @Test void ofWhenValueIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> LayerId.of((String) null)) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test @@ -80,13 +80,13 @@ class LayerIdTests { @Test void ofSha256DigestWhenNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> LayerId.ofSha256Digest((byte[]) null)) - .withMessage("Digest must not be null"); + .withMessage("Digest must not be null"); } @Test void ofSha256DigestWhenWrongLengthThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> LayerId.ofSha256Digest(new byte[31])) - .withMessage("Digest must be exactly 32 bytes"); + .withMessage("Digest must be exactly 32 bytes"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/LayerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/LayerTests.java index 6f237af476..42f8f94e9a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/LayerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/LayerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,13 +40,13 @@ class LayerTests { @Test void ofWhenLayoutIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Layer.of((IOConsumer) null)) - .withMessage("Layout must not be null"); + .withMessage("Layout must not be null"); } @Test void fromTarArchiveWhenTarArchiveIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Layer.fromTarArchive(null)) - .withMessage("TarArchive must not be null"); + .withMessage("TarArchive must not be null"); } @Test @@ -56,7 +56,7 @@ class LayerTests { layout.file("/directory/file", Owner.ROOT, Content.of("test")); }); assertThat(layer.getId().toString()) - .isEqualTo("sha256:d03a34f73804698c875eb56ff694fc2fceccc69b645e4adceb004ed13588613b"); + .isEqualTo("sha256:d03a34f73804698c875eb56ff694fc2fceccc69b645e4adceb004ed13588613b"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); layer.writeTo(outputStream); try (TarArchiveInputStream tarStream = new TarArchiveInputStream( diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/RandomStringTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/RandomStringTests.java index 8305239a9f..aa9284485d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/RandomStringTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/RandomStringTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ class RandomStringTests { @Test void generateWhenPrefixIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> RandomString.generate(null, 10)) - .withMessage("Prefix must not be null"); + .withMessage("Prefix must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/VolumeNameTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/VolumeNameTests.java index 365caa9e68..97e13e8bbc 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/VolumeNameTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/VolumeNameTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ class VolumeNameTests { @Test void randomWhenPrefixIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> VolumeName.random(null)) - .withMessage("Prefix must not be null"); + .withMessage("Prefix must not be null"); } @Test @@ -57,25 +57,25 @@ class VolumeNameTests { @Test void basedOnWhenSourceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> VolumeName.basedOn(null, "prefix", "suffix", 6)) - .withMessage("Source must not be null"); + .withMessage("Source must not be null"); } @Test void basedOnWhenNameExtractorIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> VolumeName.basedOn("test", null, "prefix", "suffix", 6)) - .withMessage("NameExtractor must not be null"); + .withMessage("NameExtractor must not be null"); } @Test void basedOnWhenPrefixIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> VolumeName.basedOn("test", null, "suffix", 6)) - .withMessage("Prefix must not be null"); + .withMessage("Prefix must not be null"); } @Test void basedOnWhenSuffixIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> VolumeName.basedOn("test", "prefix", null, 6)) - .withMessage("Suffix must not be null"); + .withMessage("Suffix must not be null"); } @Test @@ -87,13 +87,13 @@ class VolumeNameTests { @Test void basedOnWhenSizeIsTooBigThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> VolumeName.basedOn("name", "prefix", "suffix", 33)) - .withMessage("DigestLength must be less than or equal to 32"); + .withMessage("DigestLength must be less than or equal to 32"); } @Test void ofWhenValueIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> VolumeName.of(null)) - .withMessage("Value must not be null"); + .withMessage("Value must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/ContentTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/ContentTests.java index 5dd9e14873..cb9a8eb1f2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/ContentTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/ContentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ class ContentTests { @Test void ofWhenStreamIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Content.of(1, (IOSupplier) null)) - .withMessage("Supplier must not be null"); + .withMessage("Supplier must not be null"); } @Test @@ -51,7 +51,7 @@ class ContentTests { @Test void ofWhenStringIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Content.of((String) null)) - .withMessage("String must not be null"); + .withMessage("String must not be null"); } @Test @@ -63,7 +63,7 @@ class ContentTests { @Test void ofWhenBytesIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Content.of((byte[]) null)) - .withMessage("Bytes must not be null"); + .withMessage("Bytes must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/FilePermissionsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/FilePermissionsTests.java index cb70a7dad4..42e77176e6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/FilePermissionsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/FilePermissionsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,7 @@ class FilePermissionsTests { @DisabledOnOs(OS.WINDOWS) void umaskForPath() throws IOException { FileAttribute> fileAttribute = PosixFilePermissions - .asFileAttribute(PosixFilePermissions.fromString("rw-r-----")); + .asFileAttribute(PosixFilePermissions.fromString("rw-r-----")); Path tempFile = Files.createTempFile(this.tempDir, "umask", null, fileAttribute); assertThat(FilePermissions.umaskForPath(tempFile)).isEqualTo(0640); } @@ -60,7 +60,7 @@ class FilePermissionsTests { @DisabledOnOs(OS.WINDOWS) void umaskForPathWithNonExistentFile() { assertThatIOException() - .isThrownBy(() -> FilePermissions.umaskForPath(Paths.get(this.tempDir.toString(), "does-not-exist"))); + .isThrownBy(() -> FilePermissions.umaskForPath(Paths.get(this.tempDir.toString(), "does-not-exist"))); } @Test @@ -68,7 +68,7 @@ class FilePermissionsTests { void umaskForPathOnWindowsFails() throws IOException { Path tempFile = Files.createTempFile("umask", null); assertThatIllegalStateException().isThrownBy(() -> FilePermissions.umaskForPath(tempFile)) - .withMessageContaining("Unsupported file type for retrieving Posix attributes"); + .withMessageContaining("Unsupported file type for retrieving Posix attributes"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/InspectedContentTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/InspectedContentTests.java index 9997291847..dfbf2483ba 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/InspectedContentTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/InspectedContentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,19 +39,19 @@ class InspectedContentTests { @Test void ofWhenInputStreamThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> InspectedContent.of((InputStream) null)) - .withMessage("InputStream must not be null"); + .withMessage("InputStream must not be null"); } @Test void ofWhenContentIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> InspectedContent.of((Content) null)) - .withMessage("Content must not be null"); + .withMessage("Content must not be null"); } @Test void ofWhenConsumerIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> InspectedContent.of((IOConsumer) null)) - .withMessage("Writer must not be null"); + .withMessage("Writer must not be null"); } @Test @@ -85,9 +85,9 @@ class InspectedContentTests { InputStream inputStream = new ByteArrayInputStream("test".getBytes(StandardCharsets.UTF_8)); MessageDigest digest = MessageDigest.getInstance("SHA-256"); InspectedContent.of(inputStream, digest::update); - assertThat(digest.digest()).inHexadecimal().contains(0x9f, 0x86, 0xd0, 0x81, 0x88, 0x4c, 0x7d, 0x65, 0x9a, 0x2f, - 0xea, 0xa0, 0xc5, 0x5a, 0xd0, 0x15, 0xa3, 0xbf, 0x4f, 0x1b, 0x2b, 0x0b, 0x82, 0x2c, 0xd1, 0x5d, 0x6c, - 0x15, 0xb0, 0xf0, 0x0a, 0x08); + assertThat(digest.digest()).inHexadecimal() + .contains(0x9f, 0x86, 0xd0, 0x81, 0x88, 0x4c, 0x7d, 0x65, 0x9a, 0x2f, 0xea, 0xa0, 0xc5, 0x5a, 0xd0, 0x15, + 0xa3, 0xbf, 0x4f, 0x1b, 0x2b, 0x0b, 0x82, 0x2c, 0xd1, 0x5d, 0x6c, 0x15, 0xb0, 0xf0, 0x0a, 0x08); } private byte[] readBytes(InspectedContent content) throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/ZipFileTarArchiveTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/ZipFileTarArchiveTests.java index 23ae04ae54..cd11ef3929 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/ZipFileTarArchiveTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/ZipFileTarArchiveTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ class ZipFileTarArchiveTests { @Test void createWhenZipIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ZipFileTarArchive(null, Owner.ROOT)) - .withMessage("Zip must not be null"); + .withMessage("Zip must not be null"); } @Test @@ -54,7 +54,7 @@ class ZipFileTarArchiveTests { File file = new File(this.tempDir, "test.zip"); writeTestZip(file); assertThatIllegalArgumentException().isThrownBy(() -> new ZipFileTarArchive(file, null)) - .withMessage("Owner must not be null"); + .withMessage("Owner must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/AbstractJsonTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/AbstractJsonTests.java index 7065adeba8..edc27b5554 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/AbstractJsonTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/AbstractJsonTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ public abstract class AbstractJsonTests { protected final String getContentAsString(String name) { return new BufferedReader(new InputStreamReader(getContent(name), StandardCharsets.UTF_8)).lines() - .collect(Collectors.joining("\n")); + .collect(Collectors.joining("\n")); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/JsonStreamTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/JsonStreamTests.java index 285cc599e3..533d20c033 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/JsonStreamTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/JsonStreamTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,7 @@ class JsonStreamTests extends AbstractJsonTests { this.jsonStream.get(getContent("stream.json"), result::add); assertThat(result).hasSize(595); assertThat(result.get(594).toString()) - .contains("Status: Downloaded newer image for paketo-buildpacks/cnb:base"); + .contains("Status: Downloaded newer image for paketo-buildpacks/cnb:base"); } @Test @@ -55,7 +55,7 @@ class JsonStreamTests extends AbstractJsonTests { assertThat(result).hasSize(595); assertThat(result.get(1).getId()).isEqualTo("5667fdb72017"); assertThat(result.get(594).getStatus()) - .isEqualTo("Status: Downloaded newer image for paketo-buildpacks/cnb:base"); + .isEqualTo("Status: Downloaded newer image for paketo-buildpacks/cnb:base"); } /** diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/SharedObjectMapperTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/SharedObjectMapperTests.java index 16a7b2844d..32f9a9d13d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/SharedObjectMapperTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/SharedObjectMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,13 +38,13 @@ class SharedObjectMapperTests { assertThat(mapper).isNotNull(); assertThat(mapper.getRegisteredModuleIds()).contains(new ParameterNamesModule().getTypeId()); assertThat(SerializationFeature.INDENT_OUTPUT - .enabledIn(mapper.getSerializationConfig().getSerializationFeatures())).isTrue(); + .enabledIn(mapper.getSerializationConfig().getSerializationFeatures())).isTrue(); assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES - .enabledIn(mapper.getDeserializationConfig().getDeserializationFeatures())).isFalse(); + .enabledIn(mapper.getDeserializationConfig().getDeserializationFeatures())).isFalse(); assertThat(mapper.getSerializationConfig().getPropertyNamingStrategy()) - .isEqualTo(PropertyNamingStrategies.LOWER_CAMEL_CASE); + .isEqualTo(PropertyNamingStrategies.LOWER_CAMEL_CASE); assertThat(mapper.getDeserializationConfig().getPropertyNamingStrategy()) - .isEqualTo(PropertyNamingStrategies.LOWER_CAMEL_CASE); + .isEqualTo(PropertyNamingStrategies.LOWER_CAMEL_CASE); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/RawConfigurationMetadata.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/RawConfigurationMetadata.java index 954f46fc49..3a9147dea8 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/RawConfigurationMetadata.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/RawConfigurationMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,9 +52,10 @@ class RawConfigurationMetadata { return null; } return this.sources.stream() - .filter((candidate) -> item.getSourceType().equals(candidate.getType()) - && item.getId().startsWith(candidate.getGroupId())) - .max(Comparator.comparingInt((candidate) -> candidate.getGroupId().length())).orElse(null); + .filter((candidate) -> item.getSourceType().equals(candidate.getType()) + && item.getId().startsWith(candidate.getGroupId())) + .max(Comparator.comparingInt((candidate) -> candidate.getGroupId().length())) + .orElse(null); } List getItems() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java index 123a8f10cf..e64bf99768 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractConfigurat @Test void nullResource() { assertThatIllegalArgumentException() - .isThrownBy(() -> ConfigurationMetadataRepositoryJsonBuilder.create().withJsonResource(null)); + .isThrownBy(() -> ConfigurationMetadataRepositoryJsonBuilder.create().withJsonResource(null)); } @Test @@ -105,7 +105,7 @@ class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractConfigurat assertThat(group.getSources().get("org.acme.Foo2").getProperties()).containsOnlyKeys("spring.foo.enabled", "spring.foo.type"); assertThat(group.getSources().get("org.springframework.boot.FooProperties").getProperties()) - .containsOnlyKeys("spring.foo.name", "spring.foo.counter"); + .containsOnlyKeys("spring.foo.name", "spring.foo.counter"); } } @@ -123,7 +123,7 @@ class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractConfigurat assertThat(group.getSources().get("org.acme.Foo").getProperties()).containsOnlyKeys("spring.foo.name", "spring.foo.description", "spring.foo.enabled", "spring.foo.type"); assertThat(group.getSources().get("org.springframework.boot.FooProperties").getProperties()) - .containsOnlyKeys("spring.foo.name", "spring.foo.counter"); + .containsOnlyKeys("spring.foo.name", "spring.foo.counter"); } } @@ -243,7 +243,7 @@ class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractConfigurat assertThat(values.getHints().getValueProviders().get(0).getName()).isEqualTo("handle-as"); assertThat(values.getHints().getValueProviders().get(0).getParameters()).hasSize(1); assertThat(values.getHints().getValueProviders().get(0).getParameters().get("target")) - .isEqualTo("java.lang.Integer"); + .isEqualTo("java.lang.Integer"); } private void validateEmptyGroup(ConfigurationMetadataRepository repo) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java index 68550fb34f..281649db42 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -94,7 +94,7 @@ class JsonReaderTests extends AbstractConfigurationMetadataTests { ValueHint valueHint = hint.getValueHints().get(0); assertThat(valueHint.getValue()).isEqualTo(42); assertThat(valueHint.getDescription()) - .isEqualTo("Because that's the answer to any question, choose it. \nReally."); + .isEqualTo("Because that's the answer to any question, choose it. \nReally."); assertThat(valueHint.getShortDescription()).isEqualTo("Because that's the answer to any question, choose it."); assertThat(hint.getValueProviders()).hasSize(1); ValueProvider valueProvider = hint.getValueProviders().get(0); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/SentenceExtractorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/SentenceExtractorTests.java index 95b2fe9d72..fa75393cad 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/SentenceExtractorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/SentenceExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,14 +40,14 @@ class SentenceExtractorTests { @Test void extractFirstSentenceNewLineBeforeDot() { String sentence = this.extractor - .getFirstSentence("My short" + NEW_LINE + "description." + NEW_LINE + "More stuff."); + .getFirstSentence("My short" + NEW_LINE + "description." + NEW_LINE + "More stuff."); assertThat(sentence).isEqualTo("My short description."); } @Test void extractFirstSentenceNewLineBeforeDotWithSpaces() { String sentence = this.extractor - .getFirstSentence("My short " + NEW_LINE + " description. " + NEW_LINE + "More stuff."); + .getFirstSentence("My short " + NEW_LINE + " description. " + NEW_LINE + "More stuff."); assertThat(sentence).isEqualTo("My short description."); } 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 8077b44623..decb191c71 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -101,7 +101,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor static final String AUTO_CONFIGURATION_ANNOTATION = "org.springframework.boot.autoconfigure.AutoConfiguration"; private static final Set SUPPORTED_OPTIONS = Collections - .unmodifiableSet(Collections.singleton(ADDITIONAL_METADATA_LOCATIONS_OPTION)); + .unmodifiableSet(Collections.singleton(ADDITIONAL_METADATA_LOCATIONS_OPTION)); private MetadataStore metadataStore; @@ -235,8 +235,9 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor this.metadataEnv.getTypeUtils().getQualifiedName(element.getEnclosingElement()), element.toString()); if (this.metadataCollector.hasSimilarGroup(group)) { - this.processingEnv.getMessager().printMessage(Kind.ERROR, - "Duplicate @ConfigurationProperties definition for prefix '" + prefix + "'", element); + this.processingEnv.getMessager() + .printMessage(Kind.ERROR, + "Duplicate @ConfigurationProperties definition for prefix '" + prefix + "'", element); } else { this.metadataCollector.add(group); @@ -254,7 +255,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor this.metadataCollector.add(descriptor.resolveItemMetadata(prefix, this.metadataEnv)); if (descriptor.isNested(this.metadataEnv)) { TypeElement nestedTypeElement = (TypeElement) this.metadataEnv.getTypeUtils() - .asElement(descriptor.getType()); + .asElement(descriptor.getType()); String nestedPrefix = ConfigurationMetadata.nestedPrefix(prefix, descriptor.getName()); processTypeElement(nestedPrefix, nestedTypeElement, source, seen); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptor.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptor.java index dfc6f00653..6a5aea4be7 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,8 +69,9 @@ class ConstructorParameterPropertyDescriptor extends PropertyDescriptor coerceValue(specificType, value)) - .collect(Collectors.toList()); + return defaultValue.stream() + .map((value) -> coerceValue(specificType, value)) + .collect(Collectors.toList()); } catch (IllegalArgumentException ex) { environment.getMessager().printMessage(Kind.ERROR, ex.getMessage(), element, annotation); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment.java index 4e5ad965c5..5dc1769683 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -242,7 +242,7 @@ class MetadataGenerationEnvironment { Map getAnnotationElementValues(AnnotationMirror annotation) { Map values = new LinkedHashMap<>(); annotation.getElementValues() - .forEach((name, value) -> values.put(name.getSimpleName().toString(), getAnnotationValue(value))); + .forEach((name, value) -> values.put(name.getSimpleName().toString(), getAnnotationValue(value))); return values; } @@ -273,8 +273,10 @@ class MetadataGenerationEnvironment { } Set getEndpointAnnotationElements() { - return this.endpointAnnotations.stream().map(this.elements::getTypeElement).filter(Objects::nonNull) - .collect(Collectors.toSet()); + return this.endpointAnnotations.stream() + .map(this.elements::getTypeElement) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); } AnnotationMirror getReadOperationAnnotation(Element element) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java index c44724f9b1..879190e9f6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -102,8 +102,8 @@ public class MetadataStore { private InputStream getAdditionalMetadataStream() throws IOException { // Most build systems will have copied the file to the class output location - FileObject fileObject = this.environment.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", - ADDITIONAL_METADATA_PATH); + FileObject fileObject = this.environment.getFiler() + .getResource(StandardLocation.CLASS_OUTPUT, "", ADDITIONAL_METADATA_PATH); File file = locateAdditionalMetadataFile(new File(fileObject.toUri())); return (file.exists() ? new FileInputStream(file) : fileObject.toUri().toURL().openStream()); } @@ -113,7 +113,7 @@ public class MetadataStore { return standardLocation; } String locations = this.environment.getOptions() - .get(ConfigurationMetadataAnnotationProcessor.ADDITIONAL_METADATA_LOCATIONS_OPTION); + .get(ConfigurationMetadataAnnotationProcessor.ADDITIONAL_METADATA_LOCATIONS_OPTION); if (locations != null) { for (String location : locations.split(",")) { File candidate = new File(location, ADDITIONAL_METADATA_PATH); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolver.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolver.java index b182e66ea3..ccf52432f0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolver.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolver.java @@ -191,7 +191,8 @@ class PropertyDescriptorResolver { boolean constructorBoundType = isConstructorBoundType(type, env); List constructors = ElementFilter.constructorsIn(type.getEnclosedElements()); List boundConstructors = constructors.stream() - .filter(env::hasConstructorBindingAnnotation).collect(Collectors.toList()); + .filter(env::hasConstructorBindingAnnotation) + .collect(Collectors.toList()); return new ConfigurationPropertiesTypeElement(type, constructorBoundType, constructors, boundConstructors); } 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..6cd5a22bd5 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -234,7 +234,8 @@ class TypeUtils { if (type.getKind() == TypeKind.DECLARED) { DeclaredType declaredType = (DeclaredType) type; DeclaredType freshType = (DeclaredType) this.env.getElementUtils() - .getTypeElement(this.types.asElement(type).toString()).asType(); + .getTypeElement(this.types.asElement(type).toString()) + .asType(); List arguments = declaredType.getTypeArguments(); for (int i = 0; i < arguments.size(); i++) { TypeMirror specificType = arguments.get(i); @@ -267,9 +268,12 @@ class TypeUtils { } StringBuilder name = new StringBuilder(); name.append(qualifiedName); - name.append("<").append( - type.getTypeArguments().stream().map((t) -> visit(t, descriptor)).collect(Collectors.joining(","))) - .append(">"); + name.append("<") + .append(type.getTypeArguments() + .stream() + .map((t) -> visit(t, descriptor)) + .collect(Collectors.joining(","))) + .append(">"); return name.toString(); } @@ -303,8 +307,9 @@ 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)); + return ((DeclaredType) upperBound).getTypeArguments() + .stream() + .anyMatch((candidate) -> candidate.equals(variable)); } return false; } @@ -368,15 +373,20 @@ class TypeUtils { } TypeMirror resolveGeneric(String parameterName) { - return this.generics.entrySet().stream().filter((e) -> getParameterName(e.getKey()).equals(parameterName)) - .findFirst().map(Entry::getValue).orElse(null); + return this.generics.entrySet() + .stream() + .filter((e) -> getParameterName(e.getKey()).equals(parameterName)) + .findFirst() + .map(Entry::getValue) + .orElse(null); } private void registerIfNecessary(TypeMirror variable, TypeMirror resolution) { if (variable instanceof TypeVariable) { TypeVariable typeVariable = (TypeVariable) variable; - if (this.generics.keySet().stream() - .noneMatch((candidate) -> getParameterName(candidate).equals(getParameterName(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/JsonConverter.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonConverter.java index de97b71f32..c35b5042b2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonConverter.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,11 @@ class JsonConverter { JSONArray toJsonArray(ConfigurationMetadata metadata, ItemType itemType) throws Exception { JSONArray jsonArray = new JSONArray(); - List items = metadata.getItems().stream().filter((item) -> item.isOfItemType(itemType)) - .sorted(ITEM_COMPARATOR).collect(Collectors.toList()); + List items = metadata.getItems() + .stream() + .filter((item) -> item.isOfItemType(itemType)) + .sorted(ITEM_COMPARATOR) + .collect(Collectors.toList()); for (ItemMetadata item : items) { if (item.isOfItemType(itemType)) { jsonArray.put(toJsonObject(item)); @@ -161,11 +164,11 @@ class JsonConverter { private static class ItemMetadataComparator implements Comparator { private static final Comparator GROUP = Comparator.comparing(ItemMetadata::getName) - .thenComparing(ItemMetadata::getSourceType, Comparator.nullsFirst(Comparator.naturalOrder())); + .thenComparing(ItemMetadata::getSourceType, Comparator.nullsFirst(Comparator.naturalOrder())); private static final Comparator ITEM = Comparator.comparing(ItemMetadataComparator::isDeprecated) - .thenComparing(ItemMetadata::getName) - .thenComparing(ItemMetadata::getSourceType, Comparator.nullsFirst(Comparator.naturalOrder())); + .thenComparing(ItemMetadata::getName) + .thenComparing(ItemMetadata::getSourceType, Comparator.nullsFirst(Comparator.naturalOrder())); @Override public int compare(ItemMetadata o1, ItemMetadata o2) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java index 6b700ba43e..02fef0d139 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java @@ -81,15 +81,15 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene @Test void supportedAnnotations() { assertThat(new ConfigurationMetadataAnnotationProcessor().getSupportedAnnotationTypes()) - .containsExactlyInAnyOrder("org.springframework.boot.autoconfigure.AutoConfiguration", - "org.springframework.boot.context.properties.ConfigurationProperties", - "org.springframework.context.annotation.Configuration", - "org.springframework.boot.actuate.endpoint.annotation.Endpoint", - "org.springframework.boot.actuate.endpoint.jmx.annotation.JmxEndpoint", - "org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpoint", - "org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint", - "org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpoint", - "org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint"); + .containsExactlyInAnyOrder("org.springframework.boot.autoconfigure.AutoConfiguration", + "org.springframework.boot.context.properties.ConfigurationProperties", + "org.springframework.context.annotation.Configuration", + "org.springframework.boot.actuate.endpoint.annotation.Endpoint", + "org.springframework.boot.actuate.endpoint.jmx.annotation.JmxEndpoint", + "org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpoint", + "org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint", + "org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpoint", + "org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint"); } @Test @@ -103,10 +103,15 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene ConfigurationMetadata metadata = compile(SimpleProperties.class); assertThat(metadata).has(Metadata.withGroup("simple").fromSource(SimpleProperties.class)); assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class).withDescription("The name of this simple properties.") - .withDefaultValue("boot").withDeprecation(null, null)); - assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class).withDefaultValue(false) - .fromSource(SimpleProperties.class).withDescription("A simple flag.").withDeprecation(null, null)); + .fromSource(SimpleProperties.class) + .withDescription("The name of this simple properties.") + .withDefaultValue("boot") + .withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class) + .withDefaultValue(false) + .fromSource(SimpleProperties.class) + .withDescription("A simple flag.") + .withDeprecation(null, null)); assertThat(metadata).has(Metadata.withProperty("simple.comparator")); assertThat(metadata).doesNotHave(Metadata.withProperty("simple.counter")); assertThat(metadata).doesNotHave(Metadata.withProperty("simple.size")); @@ -117,7 +122,7 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene ConfigurationMetadata metadata = compile(SimplePrefixValueProperties.class); assertThat(metadata).has(Metadata.withGroup("simple").fromSource(SimplePrefixValueProperties.class)); assertThat(metadata) - .has(Metadata.withProperty("simple.name", String.class).fromSource(SimplePrefixValueProperties.class)); + .has(Metadata.withProperty("simple.name", String.class).fromSource(SimplePrefixValueProperties.class)); } @Test @@ -127,21 +132,21 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene assertThat(metadata).has(Metadata.withProperty("simple.type.my-string", String.class)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-byte", Byte.class)); assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-primitive-byte", Byte.class).withDefaultValue(0)); + .has(Metadata.withProperty("simple.type.my-primitive-byte", Byte.class).withDefaultValue(0)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-char", Character.class)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-char", Character.class)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-boolean", Boolean.class)); assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-primitive-boolean", Boolean.class).withDefaultValue(false)); + .has(Metadata.withProperty("simple.type.my-primitive-boolean", Boolean.class).withDefaultValue(false)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-short", Short.class)); assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-primitive-short", Short.class).withDefaultValue(0)); + .has(Metadata.withProperty("simple.type.my-primitive-short", Short.class).withDefaultValue(0)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-integer", Integer.class)); assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-primitive-integer", Integer.class).withDefaultValue(0)); + .has(Metadata.withProperty("simple.type.my-primitive-integer", Integer.class).withDefaultValue(0)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-long", Long.class)); assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-primitive-long", Long.class).withDefaultValue(0)); + .has(Metadata.withProperty("simple.type.my-primitive-long", Long.class).withDefaultValue(0)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-double", Double.class)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-double", Double.class)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-float", Float.class)); @@ -154,12 +159,15 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene ConfigurationMetadata metadata = compile(HierarchicalProperties.class, HierarchicalPropertiesParent.class, HierarchicalPropertiesGrandparent.class); assertThat(metadata).has(Metadata.withGroup("hierarchical").fromSource(HierarchicalProperties.class)); - assertThat(metadata).has(Metadata.withProperty("hierarchical.first", String.class).withDefaultValue("one") - .fromSource(HierarchicalProperties.class)); - assertThat(metadata).has(Metadata.withProperty("hierarchical.second", String.class).withDefaultValue("two") - .fromSource(HierarchicalProperties.class)); - assertThat(metadata).has(Metadata.withProperty("hierarchical.third", String.class).withDefaultValue("three") - .fromSource(HierarchicalProperties.class)); + assertThat(metadata).has(Metadata.withProperty("hierarchical.first", String.class) + .withDefaultValue("one") + .fromSource(HierarchicalProperties.class)); + assertThat(metadata).has(Metadata.withProperty("hierarchical.second", String.class) + .withDefaultValue("two") + .fromSource(HierarchicalProperties.class)); + assertThat(metadata).has(Metadata.withProperty("hierarchical.third", String.class) + .withDefaultValue("three") + .fromSource(HierarchicalProperties.class)); } @Test @@ -167,10 +175,12 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene ConfigurationMetadata metadata = compile(DescriptionProperties.class); assertThat(metadata).has(Metadata.withGroup("description").fromSource(DescriptionProperties.class)); assertThat(metadata).has(Metadata.withProperty("description.simple", String.class) - .fromSource(DescriptionProperties.class).withDescription("A simple description.")); + .fromSource(DescriptionProperties.class) + .withDescription("A simple description.")); assertThat(metadata).has(Metadata.withProperty("description.multi-line", String.class) - .fromSource(DescriptionProperties.class).withDescription( - "This is a lengthy description that spans across multiple lines to showcase that the line separators are cleaned automatically.")); + .fromSource(DescriptionProperties.class) + .withDescription( + "This is a lengthy description that spans across multiple lines to showcase that the line separators are cleaned automatically.")); } @Test @@ -179,10 +189,11 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene Class type = org.springframework.boot.configurationsample.simple.DeprecatedProperties.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("deprecated").fromSource(type)); - assertThat(metadata).has( - Metadata.withProperty("deprecated.name", String.class).fromSource(type).withDeprecation(null, null)); - assertThat(metadata).has(Metadata.withProperty("deprecated.description", String.class).fromSource(type) - .withDeprecation(null, null)); + assertThat(metadata) + .has(Metadata.withProperty("deprecated.name", String.class).fromSource(type).withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("deprecated.description", String.class) + .fromSource(type) + .withDeprecation(null, null)); } @Test @@ -191,8 +202,9 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("singledeprecated").fromSource(type)); assertThat(metadata).has(Metadata.withProperty("singledeprecated.new-name", String.class).fromSource(type)); - assertThat(metadata).has(Metadata.withProperty("singledeprecated.name", String.class).fromSource(type) - .withDeprecation("renamed", "singledeprecated.new-name")); + assertThat(metadata).has(Metadata.withProperty("singledeprecated.name", String.class) + .fromSource(type) + .withDeprecation("renamed", "singledeprecated.new-name")); } @Test @@ -200,8 +212,9 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene Class type = DeprecatedFieldSingleProperty.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("singlefielddeprecated").fromSource(type)); - assertThat(metadata).has(Metadata.withProperty("singlefielddeprecated.name", String.class).fromSource(type) - .withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("singlefielddeprecated.name", String.class) + .fromSource(type) + .withDeprecation(null, null)); } @Test @@ -209,10 +222,12 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene Class type = DeprecatedUnrelatedMethodPojo.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("not.deprecated").fromSource(type)); - assertThat(metadata).has( - Metadata.withProperty("not.deprecated.counter", Integer.class).withNoDeprecation().fromSource(type)); - assertThat(metadata).has(Metadata.withProperty("not.deprecated.flag", Boolean.class).withDefaultValue(false) - .withNoDeprecation().fromSource(type)); + assertThat(metadata) + .has(Metadata.withProperty("not.deprecated.counter", Integer.class).withNoDeprecation().fromSource(type)); + assertThat(metadata).has(Metadata.withProperty("not.deprecated.flag", Boolean.class) + .withDefaultValue(false) + .withNoDeprecation() + .fromSource(type)); } @Test @@ -220,8 +235,10 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene Class type = DeprecatedLessPreciseTypePojo.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("not.deprecated").fromSource(type)); - assertThat(metadata).has(Metadata.withProperty("not.deprecated.flag", Boolean.class).withDefaultValue(false) - .withNoDeprecation().fromSource(type)); + assertThat(metadata).has(Metadata.withProperty("not.deprecated.flag", Boolean.class) + .withDefaultValue(false) + .withNoDeprecation() + .fromSource(type)); } @Test @@ -241,8 +258,8 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene } ConfigurationMetadata metadata = compile(exampleRecord); assertThat(metadata).has(Metadata.withGroup("deprecated-record")); - assertThat(metadata).has( - Metadata.withProperty("deprecated-record.alpha", String.class).withDeprecation("some-reason", null)); + assertThat(metadata) + .has(Metadata.withProperty("deprecated-record.alpha", String.class).withDeprecation("some-reason", null)); assertThat(metadata).has(Metadata.withProperty("deprecated-record.bravo", String.class)); } @@ -252,7 +269,7 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("boxing").fromSource(type)); assertThat(metadata) - .has(Metadata.withProperty("boxing.flag", Boolean.class).withDefaultValue(false).fromSource(type)); + .has(Metadata.withProperty("boxing.flag", Boolean.class).withDefaultValue(false).fromSource(type)); assertThat(metadata).has(Metadata.withProperty("boxing.another-flag", Boolean.class).fromSource(type)); assertThat(metadata).has(Metadata.withProperty("boxing.counter", Integer.class).fromSource(type)); } @@ -282,8 +299,8 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene assertThat(metadata).has(Metadata.withProperty("array.simple", "java.lang.String[]")); assertThat(metadata).has(Metadata.withProperty("array.inner", "org.springframework.boot.configurationsample.simple.SimpleArrayProperties$Holder[]")); - assertThat(metadata).has( - Metadata.withProperty("array.name-to-integer", "java.util.Map[]")); + assertThat(metadata) + .has(Metadata.withProperty("array.name-to-integer", "java.util.Map[]")); assertThat(metadata.getItems()).hasSize(5); } @@ -292,7 +309,7 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene ConfigurationMetadata metadata = compile(AnnotatedGetter.class); assertThat(metadata).has(Metadata.withGroup("specific").fromSource(AnnotatedGetter.class)); assertThat(metadata) - .has(Metadata.withProperty("specific.name", String.class).fromSource(AnnotatedGetter.class)); + .has(Metadata.withProperty("specific.name", String.class).fromSource(AnnotatedGetter.class)); } @Test @@ -300,9 +317,10 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene ConfigurationMetadata metadata = compile(StaticAccessor.class); assertThat(metadata).has(Metadata.withGroup("specific").fromSource(StaticAccessor.class)); assertThat(metadata).has(Metadata.withProperty("specific.counter", Integer.class) - .fromSource(StaticAccessor.class).withDefaultValue(42)); + .fromSource(StaticAccessor.class) + .withDefaultValue(42)); assertThat(metadata) - .doesNotHave(Metadata.withProperty("specific.name", String.class).fromSource(StaticAccessor.class)); + .doesNotHave(Metadata.withProperty("specific.name", String.class).fromSource(StaticAccessor.class)); assertThat(metadata.getItems()).hasSize(2); } @@ -316,16 +334,17 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene void innerClassProperties() { ConfigurationMetadata metadata = compile(InnerClassProperties.class); assertThat(metadata).has(Metadata.withGroup("config").fromSource(InnerClassProperties.class)); - assertThat(metadata).has(Metadata.withGroup("config.first").ofType(InnerClassProperties.Foo.class) - .fromSource(InnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.first") + .ofType(InnerClassProperties.Foo.class) + .fromSource(InnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.first.name")); assertThat(metadata).has(Metadata.withProperty("config.first.bar.name")); assertThat(metadata).has(Metadata.withGroup("config.the-second", InnerClassProperties.Foo.class) - .fromSource(InnerClassProperties.class)); + .fromSource(InnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.the-second.name")); assertThat(metadata).has(Metadata.withProperty("config.the-second.bar.name")); - assertThat(metadata).has( - Metadata.withGroup("config.third").ofType(SimplePojo.class).fromSource(InnerClassProperties.class)); + assertThat(metadata) + .has(Metadata.withGroup("config.third").ofType(SimplePojo.class).fromSource(InnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.third.value")); assertThat(metadata).has(Metadata.withProperty("config.fourth")); assertThat(metadata).isNotEqualTo(Metadata.withGroup("config.fourth")); @@ -336,9 +355,9 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene ConfigurationMetadata metadata = compile(InnerClassHierarchicalProperties.class); assertThat(metadata).has(Metadata.withGroup("config.foo").ofType(InnerClassHierarchicalProperties.Foo.class)); assertThat(metadata) - .has(Metadata.withGroup("config.foo.bar").ofType(InnerClassHierarchicalProperties.Bar.class)); + .has(Metadata.withGroup("config.foo.bar").ofType(InnerClassHierarchicalProperties.Bar.class)); assertThat(metadata) - .has(Metadata.withGroup("config.foo.bar.baz").ofType(InnerClassHierarchicalProperties.Foo.Baz.class)); + .has(Metadata.withGroup("config.foo.bar.baz").ofType(InnerClassHierarchicalProperties.Foo.Baz.class)); assertThat(metadata).has(Metadata.withProperty("config.foo.bar.baz.blah")); assertThat(metadata).has(Metadata.withProperty("config.foo.bar.bling")); } @@ -354,12 +373,14 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene @Test void nestedClassChildProperties() { ConfigurationMetadata metadata = compile(ClassWithNestedProperties.class); - assertThat(metadata).has( - Metadata.withGroup("nestedChildProps").fromSource(ClassWithNestedProperties.NestedChildClass.class)); + assertThat(metadata) + .has(Metadata.withGroup("nestedChildProps").fromSource(ClassWithNestedProperties.NestedChildClass.class)); assertThat(metadata).has(Metadata.withProperty("nestedChildProps.child-class-property", Integer.class) - .fromSource(ClassWithNestedProperties.NestedChildClass.class).withDefaultValue(20)); + .fromSource(ClassWithNestedProperties.NestedChildClass.class) + .withDefaultValue(20)); assertThat(metadata).has(Metadata.withProperty("nestedChildProps.parent-class-property", Integer.class) - .fromSource(ClassWithNestedProperties.NestedChildClass.class).withDefaultValue(10)); + .fromSource(ClassWithNestedProperties.NestedChildClass.class) + .withDefaultValue(10)); } @Test @@ -399,33 +420,36 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene @Test void invalidDoubleRegistration() { assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDoubleRegistrationProperties.class)) - .withMessageContaining("Compilation failed"); + .withMessageContaining("Compilation failed"); } @Test void constructorParameterPropertyWithInvalidDefaultValueOnNumber() { assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDefaultValueNumberProperties.class)) - .withMessageContaining("Compilation failed"); + .withMessageContaining("Compilation failed"); } @Test void constructorParameterPropertyWithInvalidDefaultValueOnFloatingPoint() { assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDefaultValueFloatingPointProperties.class)) - .withMessageContaining("Compilation failed"); + .withMessageContaining("Compilation failed"); } @Test void constructorParameterPropertyWithInvalidDefaultValueOnCharacter() { assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDefaultValueCharacterProperties.class)) - .withMessageContaining("Compilation failed"); + .withMessageContaining("Compilation failed"); } @Test void constructorParameterPropertyWithEmptyDefaultValueOnProperty() { ConfigurationMetadata metadata = compile(EmptyDefaultValueProperties.class); assertThat(metadata).has(Metadata.withProperty("test.name")); - ItemMetadata nameMetadata = metadata.getItems().stream().filter((item) -> item.getName().equals("test.name")) - .findFirst().get(); + ItemMetadata nameMetadata = metadata.getItems() + .stream() + .filter((item) -> item.getName().equals("test.name")) + .findFirst() + .get(); assertThat(nameMetadata.getDefaultValue()).isNull(); } @@ -455,8 +479,8 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene File exampleRecord = new File(temp, "ExampleRecord.java"); try (PrintWriter writer = new PrintWriter(new FileWriter(exampleRecord))) { writer.println("@org.springframework.boot.configurationsample.ConstructorBinding"); - writer.println( - "@org.springframework.boot.configurationsample.ConfigurationProperties(\"record.defaults\")"); + writer + .println("@org.springframework.boot.configurationsample.ConfigurationProperties(\"record.defaults\")"); writer.println("public record ExampleRecord("); writer.println("@org.springframework.boot.configurationsample.DefaultValue(\"An1s9n\") String someString,"); writer.println("@org.springframework.boot.configurationsample.DefaultValue(\"594\") Integer someInteger"); @@ -465,9 +489,9 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene } ConfigurationMetadata metadata = compile(exampleRecord); assertThat(metadata) - .has(Metadata.withProperty("record.defaults.some-string", String.class).withDefaultValue("An1s9n")); + .has(Metadata.withProperty("record.defaults.some-string", String.class).withDefaultValue("An1s9n")); assertThat(metadata) - .has(Metadata.withProperty("record.defaults.some-integer", Integer.class).withDefaultValue(594)); + .has(Metadata.withProperty("record.defaults.some-integer", Integer.class).withDefaultValue(594)); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptorTests.java index c4a01ad1ca..3400d8af52 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -101,8 +101,12 @@ class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTest process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class); ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "counter"); - assertItemMetadata(metadataEnv, property).isProperty().hasName("test.counter").hasType(Long.class) - .hasSourceType(ImmutableSimpleProperties.class).hasNoDescription().isNotDeprecated(); + assertItemMetadata(metadataEnv, property).isProperty() + .hasName("test.counter") + .hasType(Long.class) + .hasSourceType(ImmutableSimpleProperties.class) + .hasNoDescription() + .isNotDeprecated(); }); } @@ -111,10 +115,13 @@ class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTest process(ImmutableInnerClassProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(ImmutableInnerClassProperties.class); ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); - assertItemMetadata(metadataEnv, property).isGroup().hasName("test.first") - .hasType("org.springframework.boot.configurationsample.immutable.ImmutableInnerClassProperties$Foo") - .hasSourceType(ImmutableInnerClassProperties.class).hasSourceMethod("getFirst()").hasNoDescription() - .isNotDeprecated(); + assertItemMetadata(metadataEnv, property).isGroup() + .hasName("test.first") + .hasType("org.springframework.boot.configurationsample.immutable.ImmutableInnerClassProperties$Foo") + .hasSourceType(ImmutableInnerClassProperties.class) + .hasSourceMethod("getFirst()") + .hasNoDescription() + .isNotDeprecated(); }); } @@ -137,7 +144,7 @@ class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTest TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class); ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName"); assertItemMetadata(metadataEnv, property).isProperty() - .hasDescription("The name of this simple properties."); + .hasDescription("The name of this simple properties."); }); } @@ -158,7 +165,7 @@ class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTest assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "octet")).hasDefaultValue((byte) 0); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "letter")).hasDefaultValue(null); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "number")) - .hasDefaultValue((short) 0); + .hasDefaultValue((short) 0); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "counter")).hasDefaultValue(0); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "value")).hasDefaultValue(0L); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "percentage")).hasDefaultValue(0F); @@ -172,10 +179,10 @@ class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTest TypeElement ownerElement = roundEnv.getRootElement(ImmutablePrimitiveWithDefaultsProperties.class); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flag")).hasDefaultValue(true); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "octet")) - .hasDefaultValue((byte) 120); + .hasDefaultValue((byte) 120); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "letter")).hasDefaultValue("a"); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "number")) - .hasDefaultValue((short) 1000); + .hasDefaultValue((short) 1000); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "counter")).hasDefaultValue(42); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "value")).hasDefaultValue(2000L); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "percentage")).hasDefaultValue(0.5F); @@ -189,10 +196,10 @@ class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTest TypeElement ownerElement = roundEnv.getRootElement(ImmutablePrimitiveWrapperWithDefaultsProperties.class); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flag")).hasDefaultValue(true); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "octet")) - .hasDefaultValue((byte) 120); + .hasDefaultValue((byte) 120); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "letter")).hasDefaultValue("a"); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "number")) - .hasDefaultValue((short) 1000); + .hasDefaultValue((short) 1000); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "counter")).hasDefaultValue(42); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "value")).hasDefaultValue(2000L); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "percentage")).hasDefaultValue(0.5F); @@ -206,9 +213,9 @@ class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTest TypeElement ownerElement = roundEnv.getRootElement(ImmutableCollectionProperties.class); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "names")).hasDefaultValue(null); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flags")) - .hasDefaultValue(Arrays.asList(true, false)); + .hasDefaultValue(Arrays.asList(true, false)); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "durations")) - .hasDefaultValue(Arrays.asList("10s", "1m", "1h")); + .hasDefaultValue(Arrays.asList("10s", "1m", "1h")); }); } @@ -222,13 +229,19 @@ class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTest } private VariableElement getConstructorParameter(TypeElement ownerElement, String name) { - List constructors = ElementFilter.constructorsIn(ownerElement.getEnclosedElements()).stream() - .filter((constructor) -> !constructor.getParameters().isEmpty()).collect(Collectors.toList()); + List constructors = ElementFilter.constructorsIn(ownerElement.getEnclosedElements()) + .stream() + .filter((constructor) -> !constructor.getParameters().isEmpty()) + .collect(Collectors.toList()); if (constructors.size() != 1) { throw new IllegalStateException("No candidate constructor for " + ownerElement); } - return constructors.get(0).getParameters().stream() - .filter((parameter) -> parameter.getSimpleName().toString().equals(name)).findFirst().orElse(null); + return constructors.get(0) + .getParameters() + .stream() + .filter((parameter) -> parameter.getSimpleName().toString().equals(name)) + .findFirst() + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/DeducedImmutablePropertiesMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/DeducedImmutablePropertiesMetadataGenerationTests.java index bc74aca304..e85efc0e41 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/DeducedImmutablePropertiesMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/DeducedImmutablePropertiesMetadataGenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,11 +38,14 @@ class DeducedImmutablePropertiesMetadataGenerationTests extends AbstractMetadata ConfigurationMetadata metadata = compile(DeducedImmutableClassProperties.class); assertThat(metadata).has(Metadata.withGroup("test").fromSource(DeducedImmutableClassProperties.class)); assertThat(metadata).has(Metadata.withGroup("test.nested", DeducedImmutableClassProperties.Nested.class) - .fromSource(DeducedImmutableClassProperties.class)); + .fromSource(DeducedImmutableClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("test.nested.name", String.class) - .fromSource(DeducedImmutableClassProperties.Nested.class)); - ItemMetadata nestedMetadata = metadata.getItems().stream() - .filter((item) -> item.getName().equals("test.nested")).findFirst().get(); + .fromSource(DeducedImmutableClassProperties.Nested.class)); + ItemMetadata nestedMetadata = metadata.getItems() + .stream() + .filter((item) -> item.getName().equals("test.nested")) + .findFirst() + .get(); assertThat(nestedMetadata.getDefaultValue()).isNull(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java index 09c5f03d8f..7278138422 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,9 +68,10 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { void customPropertiesEndpoint() { ConfigurationMetadata metadata = compile(CustomPropertiesEndpoint.class); assertThat(metadata) - .has(Metadata.withGroup("management.endpoint.customprops").fromSource(CustomPropertiesEndpoint.class)); - assertThat(metadata).has(Metadata.withProperty("management.endpoint.customprops.name").ofType(String.class) - .withDefaultValue("test")); + .has(Metadata.withGroup("management.endpoint.customprops").fromSource(CustomPropertiesEndpoint.class)); + assertThat(metadata).has(Metadata.withProperty("management.endpoint.customprops.name") + .ofType(String.class) + .withDefaultValue("test")); assertThat(metadata).has(enabledFlag("customprops", true)); assertThat(metadata).has(cacheTtl("customprops")); assertThat(metadata.getItems()).hasSize(4); @@ -89,7 +90,7 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { void camelCaseEndpoint() { ConfigurationMetadata metadata = compile(CamelCaseEndpoint.class); assertThat(metadata) - .has(Metadata.withGroup("management.endpoint.pascal-case").fromSource(CamelCaseEndpoint.class)); + .has(Metadata.withGroup("management.endpoint.pascal-case").fromSource(CamelCaseEndpoint.class)); assertThat(metadata).has(enabledFlag("PascalCase", "pascal-case", true)); assertThat(metadata.getItems()).hasSize(2); } @@ -99,7 +100,7 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { TestProject project = new TestProject(this.tempDir, IncrementalEndpoint.class); ConfigurationMetadata metadata = project.fullBuild(); assertThat(metadata) - .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); + .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); assertThat(metadata).has(enabledFlag("incremental", true)); assertThat(metadata).has(cacheTtl("incremental")); assertThat(metadata.getItems()).hasSize(3); @@ -107,7 +108,7 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { "id = \"incremental\", enableByDefault = false"); metadata = project.incrementalBuild(IncrementalEndpoint.class); assertThat(metadata) - .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); + .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); assertThat(metadata).has(enabledFlag("incremental", false)); assertThat(metadata).has(cacheTtl("incremental")); assertThat(metadata.getItems()).hasSize(3); @@ -118,14 +119,14 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { TestProject project = new TestProject(this.tempDir, IncrementalEndpoint.class); ConfigurationMetadata metadata = project.fullBuild(); assertThat(metadata) - .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); + .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); assertThat(metadata).has(enabledFlag("incremental", true)); assertThat(metadata).has(cacheTtl("incremental")); assertThat(metadata.getItems()).hasSize(3); project.replaceText(IncrementalEndpoint.class, "@Nullable String param", "String param"); metadata = project.incrementalBuild(IncrementalEndpoint.class); assertThat(metadata) - .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); + .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); assertThat(metadata).has(enabledFlag("incremental", true)); assertThat(metadata.getItems()).hasSize(2); } @@ -148,8 +149,8 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { private Metadata.MetadataItemCondition enabledFlag(String endpointId, String endpointSuffix, Boolean defaultValue) { return Metadata.withEnabledFlag("management.endpoint." + endpointSuffix + ".enabled") - .withDefaultValue(defaultValue) - .withDescription(String.format("Whether to enable the %s endpoint.", endpointId)); + .withDefaultValue(defaultValue) + .withDescription(String.format("Whether to enable the %s endpoint.", endpointId)); } private Metadata.MetadataItemCondition enabledFlag(String endpointId, Boolean defaultValue) { @@ -157,8 +158,10 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { } private Metadata.MetadataItemCondition cacheTtl(String endpointId) { - return Metadata.withProperty("management.endpoint." + endpointId + ".cache.time-to-live").ofType(Duration.class) - .withDefaultValue("0ms").withDescription("Maximum time that a response can be cached."); + return Metadata.withProperty("management.endpoint." + endpointId + ".cache.time-to-live") + .ofType(Duration.class) + .withDefaultValue("0ms") + .withDescription("Maximum time that a response can be cached."); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/GenericsMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/GenericsMetadataGenerationTests.java index 575ea90cc1..4f465990f5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/GenericsMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/GenericsMetadataGenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,10 +43,14 @@ class GenericsMetadataGenerationTests extends AbstractMetadataGenerationTests { ConfigurationMetadata metadata = compile(AbstractGenericProperties.class, SimpleGenericProperties.class); assertThat(metadata).has(Metadata.withGroup("generic").fromSource(SimpleGenericProperties.class)); assertThat(metadata).has(Metadata.withProperty("generic.name", String.class) - .fromSource(SimpleGenericProperties.class).withDescription("Generic name.").withDefaultValue(null)); - assertThat(metadata).has(Metadata - .withProperty("generic.mappings", "java.util.Map") - .fromSource(SimpleGenericProperties.class).withDescription("Generic mappings.").withDefaultValue(null)); + .fromSource(SimpleGenericProperties.class) + .withDescription("Generic name.") + .withDefaultValue(null)); + assertThat(metadata) + .has(Metadata.withProperty("generic.mappings", "java.util.Map") + .fromSource(SimpleGenericProperties.class) + .withDescription("Generic mappings.") + .withDefaultValue(null)); assertThat(metadata.getItems()).hasSize(3); } @@ -54,11 +58,12 @@ class GenericsMetadataGenerationTests extends AbstractMetadataGenerationTests { void complexGenericProperties() { ConfigurationMetadata metadata = compile(ComplexGenericProperties.class); assertThat(metadata).has(Metadata.withGroup("generic").fromSource(ComplexGenericProperties.class)); - assertThat(metadata).has(Metadata.withGroup("generic.test").ofType(UpperBoundGenericPojo.class) - .fromSource(ComplexGenericProperties.class)); + assertThat(metadata).has(Metadata.withGroup("generic.test") + .ofType(UpperBoundGenericPojo.class) + .fromSource(ComplexGenericProperties.class)); assertThat(metadata) - .has(Metadata.withProperty("generic.test.mappings", "java.util.Map,java.lang.String>") - .fromSource(UpperBoundGenericPojo.class)); + .has(Metadata.withProperty("generic.test.mappings", "java.util.Map,java.lang.String>") + .fromSource(UpperBoundGenericPojo.class)); assertThat(metadata.getItems()).hasSize(3); } @@ -67,11 +72,14 @@ class GenericsMetadataGenerationTests extends AbstractMetadataGenerationTests { ConfigurationMetadata metadata = compile(AbstractGenericProperties.class, UnresolvedGenericProperties.class); assertThat(metadata).has(Metadata.withGroup("generic").fromSource(UnresolvedGenericProperties.class)); assertThat(metadata).has(Metadata.withProperty("generic.name", String.class) - .fromSource(UnresolvedGenericProperties.class).withDescription("Generic name.").withDefaultValue(null)); + .fromSource(UnresolvedGenericProperties.class) + .withDescription("Generic name.") + .withDefaultValue(null)); assertThat(metadata) - .has(Metadata.withProperty("generic.mappings", "java.util.Map") - .fromSource(UnresolvedGenericProperties.class).withDescription("Generic mappings.") - .withDefaultValue(null)); + .has(Metadata.withProperty("generic.mappings", "java.util.Map") + .fromSource(UnresolvedGenericProperties.class) + .withDescription("Generic mappings.") + .withDefaultValue(null)); assertThat(metadata.getItems()).hasSize(3); } @@ -79,24 +87,27 @@ class GenericsMetadataGenerationTests extends AbstractMetadataGenerationTests { void genericTypes() { ConfigurationMetadata metadata = compile(GenericConfig.class); assertThat(metadata).has(Metadata.withGroup("generic") - .ofType("org.springframework.boot.configurationsample.generic.GenericConfig")); + .ofType("org.springframework.boot.configurationsample.generic.GenericConfig")); assertThat(metadata).has(Metadata.withGroup("generic.foo") - .ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Foo")); + .ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Foo")); assertThat(metadata).has(Metadata.withGroup("generic.foo.bar") - .ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Bar")); + .ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Bar")); assertThat(metadata).has(Metadata.withGroup("generic.foo.bar.biz") - .ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Bar$Biz")); - assertThat(metadata).has( - Metadata.withProperty("generic.foo.name").ofType(String.class).fromSource(GenericConfig.Foo.class)); - assertThat(metadata).has(Metadata.withProperty("generic.foo.string-to-bar").ofType( - "java.util.Map>") - .fromSource(GenericConfig.Foo.class)); + .ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Bar$Biz")); + assertThat(metadata) + .has(Metadata.withProperty("generic.foo.name").ofType(String.class).fromSource(GenericConfig.Foo.class)); + assertThat(metadata).has(Metadata.withProperty("generic.foo.string-to-bar") + .ofType("java.util.Map>") + .fromSource(GenericConfig.Foo.class)); assertThat(metadata).has(Metadata.withProperty("generic.foo.string-to-integer") - .ofType("java.util.Map").fromSource(GenericConfig.Foo.class)); - assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.name").ofType("java.lang.String") - .fromSource(GenericConfig.Bar.class)); - assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.biz.name").ofType("java.lang.String") - .fromSource(GenericConfig.Bar.Biz.class)); + .ofType("java.util.Map") + .fromSource(GenericConfig.Foo.class)); + assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.name") + .ofType("java.lang.String") + .fromSource(GenericConfig.Bar.class)); + assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.biz.name") + .ofType("java.lang.String") + .fromSource(GenericConfig.Bar.Biz.class)); assertThat(metadata.getItems()).hasSize(9); } @@ -105,9 +116,11 @@ class GenericsMetadataGenerationTests extends AbstractMetadataGenerationTests { ConfigurationMetadata metadata = compile(WildcardConfig.class); assertThat(metadata).has(Metadata.withGroup("wildcard").ofType(WildcardConfig.class)); assertThat(metadata).has(Metadata.withProperty("wildcard.string-to-number") - .ofType("java.util.Map").fromSource(WildcardConfig.class)); + .ofType("java.util.Map") + .fromSource(WildcardConfig.class)); assertThat(metadata).has(Metadata.withProperty("wildcard.integers") - .ofType("java.util.List").fromSource(WildcardConfig.class)); + .ofType("java.util.List") + .fromSource(WildcardConfig.class)); assertThat(metadata.getItems()).hasSize(3); } @@ -115,8 +128,8 @@ class GenericsMetadataGenerationTests extends AbstractMetadataGenerationTests { void builderPatternWithGenericReturnType() { ConfigurationMetadata metadata = compile(ConcreteBuilderProperties.class); assertThat(metadata).has(Metadata.withGroup("builder").fromSource(ConcreteBuilderProperties.class)); - assertThat(metadata).has( - Metadata.withProperty("builder.number", Integer.class).fromSource(ConcreteBuilderProperties.class)); + assertThat(metadata) + .has(Metadata.withProperty("builder.number", Integer.class).fromSource(ConcreteBuilderProperties.class)); assertThat(metadata).has( Metadata.withProperty("builder.description", String.class).fromSource(ConcreteBuilderProperties.class)); assertThat(metadata.getItems()).hasSize(3); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutableNameAnnotationPropertiesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutableNameAnnotationPropertiesTests.java index 8000658dd9..26a81530f4 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutableNameAnnotationPropertiesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutableNameAnnotationPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ class ImmutableNameAnnotationPropertiesTests extends AbstractMetadataGenerationT void immutableNameAnnotationProperties() { ConfigurationMetadata metadata = compile(ImmutableNameAnnotationProperties.class); assertThat(metadata).has(Metadata.withProperty("named.import", String.class) - .fromSource(ImmutableNameAnnotationProperties.class)); + .fromSource(ImmutableNameAnnotationProperties.class)); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutablePropertiesMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutablePropertiesMetadataGenerationTests.java index c2de06ba0c..6e3571539f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutablePropertiesMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutablePropertiesMetadataGenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,12 +35,15 @@ class ImmutablePropertiesMetadataGenerationTests extends AbstractMetadataGenerat void immutableSimpleProperties() { ConfigurationMetadata metadata = compile(ImmutableSimpleProperties.class); assertThat(metadata).has(Metadata.withGroup("immutable").fromSource(ImmutableSimpleProperties.class)); - assertThat(metadata).has( - Metadata.withProperty("immutable.the-name", String.class).fromSource(ImmutableSimpleProperties.class) - .withDescription("The name of this simple properties.").withDefaultValue("boot")); - assertThat(metadata).has(Metadata.withProperty("immutable.flag", Boolean.class).withDefaultValue(false) - .fromSource(ImmutableSimpleProperties.class).withDescription("A simple flag.") - .withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("immutable.the-name", String.class) + .fromSource(ImmutableSimpleProperties.class) + .withDescription("The name of this simple properties.") + .withDefaultValue("boot")); + assertThat(metadata).has(Metadata.withProperty("immutable.flag", Boolean.class) + .withDefaultValue(false) + .fromSource(ImmutableSimpleProperties.class) + .withDescription("A simple flag.") + .withDeprecation(null, null)); assertThat(metadata).has(Metadata.withProperty("immutable.comparator")); assertThat(metadata).has(Metadata.withProperty("immutable.counter")); assertThat(metadata.getItems()).hasSize(5); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/IncrementalBuildMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/IncrementalBuildMetadataGenerationTests.java index 150e9b4813..f5e80e4eae 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/IncrementalBuildMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/IncrementalBuildMetadataGenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,14 +42,14 @@ class IncrementalBuildMetadataGenerationTests extends AbstractMetadataGeneration ConfigurationMetadata metadata = project.fullBuild(); assertThat(project.getOutputFile(MetadataStore.METADATA_PATH).exists()).isTrue(); assertThat(metadata) - .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); + .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); assertThat(metadata) - .has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); + .has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); metadata = project.incrementalBuild(BarProperties.class); assertThat(metadata) - .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); + .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); assertThat(metadata) - .has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); + .has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); project.addSourceCode(BarProperties.class, BarProperties.class.getResourceAsStream("BarProperties.snippet")); metadata = project.incrementalBuild(BarProperties.class); assertThat(metadata).has(Metadata.withProperty("bar.extra")); @@ -79,19 +79,19 @@ class IncrementalBuildMetadataGenerationTests extends AbstractMetadataGeneration TestProject project = new TestProject(this.tempDir, FooProperties.class, BarProperties.class); ConfigurationMetadata metadata = project.fullBuild(); assertThat(metadata) - .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); + .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); assertThat(metadata) - .has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); + .has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); assertThat(metadata).doesNotHave(Metadata.withProperty("bar.counter").fromSource(RenamedBarProperties.class)); project.delete(BarProperties.class); project.add(RenamedBarProperties.class); metadata = project.incrementalBuild(RenamedBarProperties.class); assertThat(metadata) - .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); + .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); assertThat(metadata) - .doesNotHave(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); + .doesNotHave(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); assertThat(metadata) - .has(Metadata.withProperty("bar.counter").withDefaultValue(0).fromSource(RenamedBarProperties.class)); + .has(Metadata.withProperty("bar.counter").withDefaultValue(0).fromSource(RenamedBarProperties.class)); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptorTests.java index a4ced722c7..c283530011 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -130,8 +130,12 @@ class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { process(SimpleTypeProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleTypeProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "myString"); - assertItemMetadata(metadataEnv, property).isProperty().hasName("test.my-string").hasType(String.class) - .hasSourceType(SimpleTypeProperties.class).hasNoDescription().isNotDeprecated(); + assertItemMetadata(metadataEnv, property).isProperty() + .hasName("test.my-string") + .hasType(String.class) + .hasSourceType(SimpleTypeProperties.class) + .hasNoDescription() + .isNotDeprecated(); }); } @@ -140,9 +144,12 @@ class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { process(SimpleCollectionProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleCollectionProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "doubles"); - assertItemMetadata(metadataEnv, property).isProperty().hasName("test.doubles") - .hasType("java.util.List").hasSourceType(SimpleCollectionProperties.class) - .hasNoDescription().isNotDeprecated(); + assertItemMetadata(metadataEnv, property).isProperty() + .hasName("test.doubles") + .hasType("java.util.List") + .hasSourceType(SimpleCollectionProperties.class) + .hasNoDescription() + .isNotDeprecated(); }); } @@ -151,10 +158,13 @@ class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { process(InnerClassProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(InnerClassProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); - assertItemMetadata(metadataEnv, property).isGroup().hasName("test.first") - .hasType("org.springframework.boot.configurationsample.specific.InnerClassProperties$Foo") - .hasSourceType(InnerClassProperties.class).hasSourceMethod("getFirst()").hasNoDescription() - .isNotDeprecated(); + assertItemMetadata(metadataEnv, property).isGroup() + .hasName("test.first") + .hasType("org.springframework.boot.configurationsample.specific.InnerClassProperties$Foo") + .hasSourceType(InnerClassProperties.class) + .hasSourceMethod("getFirst()") + .hasNoDescription() + .isNotDeprecated(); }); } @@ -174,8 +184,8 @@ class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { void javaBeanDeprecatedPropertyOnClass() throws IOException { process(org.springframework.boot.configurationsample.simple.DeprecatedProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv.getRootElement( - org.springframework.boot.configurationsample.simple.DeprecatedProperties.class); + TypeElement ownerElement = roundEnv + .getRootElement(org.springframework.boot.configurationsample.simple.DeprecatedProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name"); assertItemMetadata(metadataEnv, property).isProperty().isDeprecatedWithNoInformation(); }); @@ -186,8 +196,9 @@ class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { process(DeprecatedSingleProperty.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(DeprecatedSingleProperty.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name"); - assertItemMetadata(metadataEnv, property).isProperty().isDeprecatedWithReason("renamed") - .isDeprecatedWithReplacement("singledeprecated.new-name"); + assertItemMetadata(metadataEnv, property).isProperty() + .isDeprecatedWithReason("renamed") + .isDeprecatedWithReplacement("singledeprecated.new-name"); }); } @@ -215,7 +226,7 @@ class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName"); assertItemMetadata(metadataEnv, property).isProperty() - .hasDescription("The name of this simple properties."); + .hasDescription("The name of this simple properties."); }); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokMetadataGenerationTests.java index 524c200f77..69f0bb8718 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokMetadataGenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -97,16 +97,18 @@ class LombokMetadataGenerationTests extends AbstractMetadataGenerationTests { void lombokInnerClassProperties() { ConfigurationMetadata metadata = compile(LombokInnerClassProperties.class); assertThat(metadata).has(Metadata.withGroup("config").fromSource(LombokInnerClassProperties.class)); - assertThat(metadata).has(Metadata.withGroup("config.first").ofType(LombokInnerClassProperties.Foo.class) - .fromSource(LombokInnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.first") + .ofType(LombokInnerClassProperties.Foo.class) + .fromSource(LombokInnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.first.name")); assertThat(metadata).has(Metadata.withProperty("config.first.bar.name")); assertThat(metadata).has(Metadata.withGroup("config.second", LombokInnerClassProperties.Foo.class) - .fromSource(LombokInnerClassProperties.class)); + .fromSource(LombokInnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.second.name")); assertThat(metadata).has(Metadata.withProperty("config.second.bar.name")); - assertThat(metadata).has(Metadata.withGroup("config.third").ofType(SimpleLombokPojo.class) - .fromSource(LombokInnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.third") + .ofType(SimpleLombokPojo.class) + .fromSource(LombokInnerClassProperties.class)); // For some reason the annotation processor resolves a type for SimpleLombokPojo // that is resolved (compiled) and the source annotations are gone. Because we // don't see the @Data annotation anymore, no field is harvested. What is crazy is @@ -121,9 +123,10 @@ class LombokMetadataGenerationTests extends AbstractMetadataGenerationTests { void lombokInnerClassWithGetterProperties() { ConfigurationMetadata metadata = compile(LombokInnerClassWithGetterProperties.class); assertThat(metadata).has(Metadata.withGroup("config").fromSource(LombokInnerClassWithGetterProperties.class)); - assertThat(metadata) - .has(Metadata.withGroup("config.first").ofType(LombokInnerClassWithGetterProperties.Foo.class) - .fromSourceMethod("getFirst()").fromSource(LombokInnerClassWithGetterProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.first") + .ofType(LombokInnerClassWithGetterProperties.Foo.class) + .fromSourceMethod("getFirst()") + .fromSource(LombokInnerClassWithGetterProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.first.name")); assertThat(metadata.getItems()).hasSize(3); } @@ -131,12 +134,15 @@ class LombokMetadataGenerationTests extends AbstractMetadataGenerationTests { private void assertSimpleLombokProperties(ConfigurationMetadata metadata, Class source, String prefix) { assertThat(metadata).has(Metadata.withGroup(prefix).fromSource(source)); assertThat(metadata).doesNotHave(Metadata.withProperty(prefix + ".id")); - assertThat(metadata).has(Metadata.withProperty(prefix + ".name", String.class).fromSource(source) - .withDescription("Name description.")); + assertThat(metadata).has(Metadata.withProperty(prefix + ".name", String.class) + .fromSource(source) + .withDescription("Name description.")); assertThat(metadata).has(Metadata.withProperty(prefix + ".description")); assertThat(metadata).has(Metadata.withProperty(prefix + ".counter")); - assertThat(metadata).has(Metadata.withProperty(prefix + ".number").fromSource(source).withDefaultValue(0) - .withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty(prefix + ".number") + .fromSource(source) + .withDefaultValue(0) + .withDeprecation(null, null)); assertThat(metadata).has(Metadata.withProperty(prefix + ".items")); assertThat(metadata).doesNotHave(Metadata.withProperty(prefix + ".ignored")); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptorTests.java index 66d02ce82f..8093c5205c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -150,8 +150,12 @@ class LombokPropertyDescriptorTests extends PropertyDescriptorTests { process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "description"); - assertItemMetadata(metadataEnv, property).isProperty().hasName("test.description").hasType(String.class) - .hasSourceType(LombokSimpleProperties.class).hasNoDescription().isNotDeprecated(); + assertItemMetadata(metadataEnv, property).isProperty() + .hasName("test.description") + .hasType(String.class) + .hasSourceType(LombokSimpleProperties.class) + .hasNoDescription() + .isNotDeprecated(); }); } @@ -160,9 +164,12 @@ class LombokPropertyDescriptorTests extends PropertyDescriptorTests { process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "items"); - assertItemMetadata(metadataEnv, property).isProperty().hasName("test.items") - .hasType("java.util.List").hasSourceType(LombokSimpleProperties.class) - .hasNoDescription().isNotDeprecated(); + assertItemMetadata(metadataEnv, property).isProperty() + .hasName("test.items") + .hasType("java.util.List") + .hasSourceType(LombokSimpleProperties.class) + .hasNoDescription() + .isNotDeprecated(); }); } @@ -174,10 +181,13 @@ class LombokPropertyDescriptorTests extends PropertyDescriptorTests { ExecutableElement getter = getMethod(ownerElement, "getThird"); LombokPropertyDescriptor property = new LombokPropertyDescriptor(ownerElement, null, field, "third", field.asType(), getter, null); - assertItemMetadata(metadataEnv, property).isGroup().hasName("test.third") - .hasType("org.springframework.boot.configurationsample.lombok.SimpleLombokPojo") - .hasSourceType(LombokInnerClassProperties.class).hasSourceMethod("getThird()").hasNoDescription() - .isNotDeprecated(); + assertItemMetadata(metadataEnv, property).isGroup() + .hasName("test.third") + .hasType("org.springframework.boot.configurationsample.lombok.SimpleLombokPojo") + .hasSourceType(LombokInnerClassProperties.class) + .hasSourceMethod("getThird()") + .hasNoDescription() + .isNotDeprecated(); }); } @@ -186,10 +196,13 @@ class LombokPropertyDescriptorTests extends PropertyDescriptorTests { process(LombokInnerClassProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokInnerClassProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); - assertItemMetadata(metadataEnv, property).isGroup().hasName("test.first") - .hasType("org.springframework.boot.configurationsample.lombok.LombokInnerClassProperties$Foo") - .hasSourceType(LombokInnerClassProperties.class).hasSourceMethod(null).hasNoDescription() - .isNotDeprecated(); + assertItemMetadata(metadataEnv, property).isGroup() + .hasName("test.first") + .hasType("org.springframework.boot.configurationsample.lombok.LombokInnerClassProperties$Foo") + .hasSourceType(LombokInnerClassProperties.class) + .hasSourceMethod(null) + .hasNoDescription() + .isNotDeprecated(); }); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MergeMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MergeMetadataGenerationTests.java index 7b439437c8..2545511c7f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MergeMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MergeMetadataGenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,8 +74,11 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { ItemMetadata property = ItemMetadata.newProperty("simple", "flag", null, null, null, null, true, null); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class).fromSource(SimpleProperties.class) - .withDescription("A simple flag.").withDeprecation(null, null).withDefaultValue(true)); + assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class) + .fromSource(SimpleProperties.class) + .withDescription("A simple flag.") + .withDeprecation(null, null) + .withDefaultValue(true)); assertThat(metadata.getItems()).hasSize(4); } @@ -86,17 +89,23 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class, SimpleConflictingProperties.class); assertThat(metadata.getItems()).hasSize(6); - List items = metadata.getItems().stream().filter((item) -> item.getName().equals("simple.flag")) - .collect(Collectors.toList()); + List items = metadata.getItems() + .stream() + .filter((item) -> item.getName().equals("simple.flag")) + .collect(Collectors.toList()); assertThat(items).hasSize(2); - ItemMetadata matchingProperty = items.stream().filter((item) -> item.getType().equals(Boolean.class.getName())) - .findFirst().orElse(null); + ItemMetadata matchingProperty = items.stream() + .filter((item) -> item.getType().equals(Boolean.class.getName())) + .findFirst() + .orElse(null); assertThat(matchingProperty).isNotNull(); assertThat(matchingProperty.getDefaultValue()).isEqualTo(true); assertThat(matchingProperty.getSourceType()).isEqualTo(SimpleProperties.class.getName()); assertThat(matchingProperty.getDescription()).isEqualTo("A simple flag."); ItemMetadata nonMatchingProperty = items.stream() - .filter((item) -> item.getType().equals(String.class.getName())).findFirst().orElse(null); + .filter((item) -> item.getType().equals(String.class.getName())) + .findFirst() + .orElse(null); assertThat(nonMatchingProperty).isNotNull(); assertThat(nonMatchingProperty.getDefaultValue()).isEqualTo("hello"); assertThat(nonMatchingProperty.getSourceType()).isEqualTo(SimpleConflictingProperties.class.getName()); @@ -110,7 +119,8 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.comparator", "java.util.Comparator") - .fromSource(SimpleProperties.class).withDescription("A nice comparator.")); + .fromSource(SimpleProperties.class) + .withDescription("A nice comparator.")); assertThat(metadata.getItems()).hasSize(4); } @@ -120,9 +130,9 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { new ItemDeprecation("Don't use this.", "simple.complex-comparator", "error")); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata).has( - Metadata.withProperty("simple.comparator", "java.util.Comparator").fromSource(SimpleProperties.class) - .withDeprecation("Don't use this.", "simple.complex-comparator", "error")); + assertThat(metadata).has(Metadata.withProperty("simple.comparator", "java.util.Comparator") + .fromSource(SimpleProperties.class) + .withDeprecation("Don't use this.", "simple.complex-comparator", "error")); assertThat(metadata.getItems()).hasSize(4); } @@ -133,7 +143,8 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(DeprecatedSingleProperty.class); assertThat(metadata).has(Metadata.withProperty("singledeprecated.name", String.class.getName()) - .fromSource(DeprecatedSingleProperty.class).withDeprecation("Don't use this.", "single.name")); + .fromSource(DeprecatedSingleProperty.class) + .withDeprecation("Don't use this.", "single.name")); assertThat(metadata.getItems()).hasSize(3); } @@ -144,8 +155,8 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(DeprecatedSingleProperty.class); assertThat(metadata).has(Metadata.withProperty("singledeprecated.name", String.class.getName()) - .fromSource(DeprecatedSingleProperty.class) - .withDeprecation("renamed", "singledeprecated.new-name", "error")); + .fromSource(DeprecatedSingleProperty.class) + .withDeprecation("renamed", "singledeprecated.new-name", "error")); assertThat(metadata.getItems()).hasSize(3); } @@ -154,7 +165,7 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { File additionalMetadataFile = createAdditionalMetadataFile(); FileCopyUtils.copy("Hello World", new FileWriter(additionalMetadataFile)); assertThatIllegalStateException().isThrownBy(() -> compile(SimpleProperties.class)) - .withMessage("Compilation failed"); + .withMessage("Compilation failed"); } @Test @@ -163,10 +174,12 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { new ItemHint.ValueHint("spring", null))); ConfigurationMetadata metadata = compile(SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class).withDescription("The name of this simple properties.") - .withDefaultValue("boot").withDeprecation(null, null)); + .fromSource(SimpleProperties.class) + .withDescription("The name of this simple properties.") + .withDefaultValue("boot") + .withDeprecation(null, null)); assertThat(metadata) - .has(Metadata.withHint("simple.the-name").withValue(0, "boot", "Bla bla").withValue(1, "spring", null)); + .has(Metadata.withHint("simple.the-name").withValue(0, "boot", "Bla bla").withValue(1, "spring", null)); } @Test @@ -174,8 +187,10 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { writeAdditionalHints(ItemHint.newHint("simple.theName", new ItemHint.ValueHint("boot", "Bla bla"))); ConfigurationMetadata metadata = compile(SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class).withDescription("The name of this simple properties.") - .withDefaultValue("boot").withDeprecation(null, null)); + .fromSource(SimpleProperties.class) + .withDescription("The name of this simple properties.") + .withDefaultValue("boot") + .withDeprecation(null, null)); assertThat(metadata).has(Metadata.withHint("simple.the-name").withValue(0, "boot", "Bla bla")); } @@ -186,8 +201,10 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { new ItemHint.ValueProvider("second", null)))); ConfigurationMetadata metadata = compile(SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class).withDescription("The name of this simple properties.") - .withDefaultValue("boot").withDeprecation(null, null)); + .fromSource(SimpleProperties.class) + .withDescription("The name of this simple properties.") + .withDefaultValue("boot") + .withDeprecation(null, null)); assertThat(metadata).has( Metadata.withHint("simple.the-name").withProvider("first", "target", "org.foo").withProvider("second")); } @@ -197,8 +214,8 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { writePropertyDeprecation(ItemMetadata.newProperty("simple", "wrongName", "java.lang.String", null, null, null, null, new ItemDeprecation("Lame name.", "simple.the-name"))); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata).has(Metadata.withProperty("simple.wrong-name", String.class).withDeprecation("Lame name.", - "simple.the-name")); + assertThat(metadata).has(Metadata.withProperty("simple.wrong-name", String.class) + .withDeprecation("Lame name.", "simple.the-name")); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java index ea284745c2..77ea482da2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ class MetadataStoreTests { additionalMetadata.createNewFile(); assertThat(this.metadataStore.locateAdditionalMetadataFile( new File(classesLocation, "META-INF/additional-spring-configuration-metadata.json"))) - .isEqualTo(additionalMetadata); + .isEqualTo(additionalMetadata); } @Test @@ -67,7 +67,7 @@ class MetadataStoreTests { additionalMetadata.createNewFile(); assertThat(this.metadataStore.locateAdditionalMetadataFile( new File(classesLocation, "META-INF/additional-spring-configuration-metadata.json"))) - .isEqualTo(additionalMetadata); + .isEqualTo(additionalMetadata); } @Test @@ -81,7 +81,7 @@ class MetadataStoreTests { additionalMetadata.createNewFile(); assertThat(this.metadataStore.locateAdditionalMetadataFile( new File(classesLocation, "META-INF/additional-spring-configuration-metadata.json"))) - .isEqualTo(additionalMetadata); + .isEqualTo(additionalMetadata); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MethodBasedMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MethodBasedMetadataGenerationTests.java index 5aa5d34ae6..fd1a1c723d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MethodBasedMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MethodBasedMetadataGenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,7 +59,7 @@ class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerationTests assertThat(metadata).has(Metadata.withGroup("foo").fromSource(config)); assertThat(metadata).has(Metadata.withProperty("foo.name", String.class).fromSource(properties)); assertThat(metadata) - .has(Metadata.withProperty("foo.flag", Boolean.class).withDefaultValue(false).fromSource(properties)); + .has(Metadata.withProperty("foo.flag", Boolean.class).withDefaultValue(false).fromSource(properties)); } @Test @@ -72,7 +72,7 @@ class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerationTests void invalidMethodConfig() { ConfigurationMetadata metadata = compile(InvalidMethodConfig.class); assertThat(metadata) - .has(Metadata.withProperty("something.name", String.class).fromSource(InvalidMethodConfig.class)); + .has(Metadata.withProperty("something.name", String.class).fromSource(InvalidMethodConfig.class)); assertThat(metadata).isNotEqualTo(Metadata.withProperty("invalid.name")); } @@ -80,22 +80,24 @@ class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerationTests void methodAndClassConfig() { ConfigurationMetadata metadata = compile(MethodAndClassConfig.class); assertThat(metadata) - .has(Metadata.withProperty("conflict.name", String.class).fromSource(MethodAndClassConfig.Foo.class)); - assertThat(metadata).has(Metadata.withProperty("conflict.flag", Boolean.class).withDefaultValue(false) - .fromSource(MethodAndClassConfig.Foo.class)); + .has(Metadata.withProperty("conflict.name", String.class).fromSource(MethodAndClassConfig.Foo.class)); + assertThat(metadata).has(Metadata.withProperty("conflict.flag", Boolean.class) + .withDefaultValue(false) + .fromSource(MethodAndClassConfig.Foo.class)); assertThat(metadata) - .has(Metadata.withProperty("conflict.value", String.class).fromSource(MethodAndClassConfig.class)); + .has(Metadata.withProperty("conflict.value", String.class).fromSource(MethodAndClassConfig.class)); } @Test void singleConstructorMethodConfig() { ConfigurationMetadata metadata = compile(SingleConstructorMethodConfig.class); assertThat(metadata).doesNotHave(Metadata.withProperty("foo.my-service", Object.class) - .fromSource(SingleConstructorMethodConfig.Foo.class)); - assertThat(metadata).has( - Metadata.withProperty("foo.name", String.class).fromSource(SingleConstructorMethodConfig.Foo.class)); - assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class).withDefaultValue(false) - .fromSource(SingleConstructorMethodConfig.Foo.class)); + .fromSource(SingleConstructorMethodConfig.Foo.class)); + assertThat(metadata) + .has(Metadata.withProperty("foo.name", String.class).fromSource(SingleConstructorMethodConfig.Foo.class)); + assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class) + .withDefaultValue(false) + .fromSource(SingleConstructorMethodConfig.Foo.class)); } @Test @@ -110,9 +112,12 @@ class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerationTests ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("foo").fromSource(type)); assertThat(metadata).has(Metadata.withProperty("foo.name", String.class) - .fromSource(DeprecatedMethodConfig.Foo.class).withDeprecation(null, null)); - assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class).withDefaultValue(false) - .fromSource(DeprecatedMethodConfig.Foo.class).withDeprecation(null, null)); + .fromSource(DeprecatedMethodConfig.Foo.class) + .withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class) + .withDefaultValue(false) + .fromSource(DeprecatedMethodConfig.Foo.class) + .withDeprecation(null, null)); } @Test @@ -122,11 +127,12 @@ class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerationTests ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("foo").fromSource(type)); assertThat(metadata).has(Metadata.withProperty("foo.name", String.class) - .fromSource(org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class) - .withDeprecation(null, null)); - assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class).withDefaultValue(false) - .fromSource(org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class) - .withDeprecation(null, null)); + .fromSource(org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class) + .withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class) + .withDefaultValue(false) + .fromSource(org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class) + .withDeprecation(null, null)); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolverTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolverTests.java index 69b4f051ff..d0e73cb5c8 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolverTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,13 +77,13 @@ class PropertyDescriptorResolverTests { PropertyDescriptorResolver resolver = new PropertyDescriptorResolver(metadataEnv); assertThat(resolver.resolve(type, null).map(PropertyDescriptor::getName)).containsExactly("third", "second", "first"); - assertThat(resolver.resolve(type, null).map( - (descriptor) -> descriptor.getGetter().getEnclosingElement().getSimpleName().toString())) - .containsExactly("HierarchicalProperties", "HierarchicalPropertiesParent", - "HierarchicalPropertiesParent"); assertThat(resolver.resolve(type, null) - .map((descriptor) -> descriptor.resolveItemMetadata("test", metadataEnv)) - .map(ItemMetadata::getDefaultValue)).containsExactly("three", "two", "one"); + .map((descriptor) -> descriptor.getGetter().getEnclosingElement().getSimpleName().toString())) + .containsExactly("HierarchicalProperties", "HierarchicalPropertiesParent", + "HierarchicalPropertiesParent"); + assertThat(resolver.resolve(type, null) + .map((descriptor) -> descriptor.resolveItemMetadata("test", metadataEnv)) + .map(ItemMetadata::getDefaultValue)).containsExactly("three", "two", "one"); }); } @@ -116,7 +116,7 @@ class PropertyDescriptorResolverTests { process(ImmutableSimpleProperties.class, propertyNames( (stream) -> assertThat(stream).containsExactly("theName", "flag", "comparator", "counter"))); process(ImmutableSimpleProperties.class, properties((stream) -> assertThat(stream) - .allMatch((predicate) -> predicate instanceof ConstructorParameterPropertyDescriptor))); + .allMatch((predicate) -> predicate instanceof ConstructorParameterPropertyDescriptor))); } @Test @@ -124,7 +124,7 @@ class PropertyDescriptorResolverTests { process(ImmutableClassConstructorBindingProperties.class, propertyNames((stream) -> assertThat(stream).containsExactly("name", "description"))); process(ImmutableClassConstructorBindingProperties.class, properties((stream) -> assertThat(stream) - .allMatch((predicate) -> predicate instanceof ConstructorParameterPropertyDescriptor))); + .allMatch((predicate) -> predicate instanceof ConstructorParameterPropertyDescriptor))); } @Test @@ -138,7 +138,7 @@ class PropertyDescriptorResolverTests { process(MatchingConstructorNoDirectiveProperties.class, propertyNames((stream) -> assertThat(stream).containsExactly("name"))); process(MatchingConstructorNoDirectiveProperties.class, properties((stream) -> assertThat(stream) - .allMatch((predicate) -> predicate instanceof JavaBeanPropertyDescriptor))); + .allMatch((predicate) -> predicate instanceof JavaBeanPropertyDescriptor))); } @Test @@ -146,7 +146,7 @@ class PropertyDescriptorResolverTests { process(ImmutableMultiConstructorProperties.class, propertyNames((stream) -> assertThat(stream).containsExactly("name", "description"))); process(ImmutableMultiConstructorProperties.class, properties((stream) -> assertThat(stream) - .allMatch((predicate) -> predicate instanceof ConstructorParameterPropertyDescriptor))); + .allMatch((predicate) -> predicate instanceof ConstructorParameterPropertyDescriptor))); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorTests.java index e1e885297b..fcee70d83c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,15 +50,19 @@ public abstract class PropertyDescriptorTests { } protected ExecutableElement getMethod(TypeElement element, String name) { - return ElementFilter.methodsIn(element.getEnclosedElements()).stream() - .filter((method) -> ((Element) method).getSimpleName().toString().equals(name)).findFirst() - .orElse(null); + return ElementFilter.methodsIn(element.getEnclosedElements()) + .stream() + .filter((method) -> ((Element) method).getSimpleName().toString().equals(name)) + .findFirst() + .orElse(null); } protected VariableElement getField(TypeElement element, String name) { - return ElementFilter.fieldsIn(element.getEnclosedElements()).stream() - .filter((method) -> ((Element) method).getSimpleName().toString().equals(name)).findFirst() - .orElse(null); + return ElementFilter.fieldsIn(element.getEnclosedElements()) + .stream() + .filter((method) -> ((Element) method).getSimpleName().toString().equals(name)) + .findFirst() + .orElse(null); } protected ItemMetadataAssert assertItemMetadata(MetadataGenerationEnvironment metadataEnv, diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TypeUtilsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TypeUtilsTests.java index 4bc54fef59..bf184b29ba 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TypeUtilsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TypeUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ class TypeUtilsTests { void resolveTypeDescriptorOnConcreteClass() throws IOException { process(SimpleGenericProperties.class, (roundEnv, typeUtils) -> { TypeDescriptor typeDescriptor = typeUtils - .resolveTypeDescriptor(roundEnv.getRootElement(SimpleGenericProperties.class)); + .resolveTypeDescriptor(roundEnv.getRootElement(SimpleGenericProperties.class)); assertThat(typeDescriptor.getGenerics().keySet().stream().map(Object::toString)).containsOnly("A", "B", "C"); assertThat(typeDescriptor.resolveGeneric("A")).hasToString(String.class.getName()); @@ -62,7 +62,7 @@ class TypeUtilsTests { void resolveTypeDescriptorOnIntermediateClass() throws IOException { process(AbstractIntermediateGenericProperties.class, (roundEnv, typeUtils) -> { TypeDescriptor typeDescriptor = typeUtils - .resolveTypeDescriptor(roundEnv.getRootElement(AbstractIntermediateGenericProperties.class)); + .resolveTypeDescriptor(roundEnv.getRootElement(AbstractIntermediateGenericProperties.class)); assertThat(typeDescriptor.getGenerics().keySet().stream().map(Object::toString)).containsOnly("A", "B", "C"); assertThat(typeDescriptor.resolveGeneric("A")).hasToString(String.class.getName()); @@ -75,7 +75,7 @@ class TypeUtilsTests { void resolveTypeDescriptorWithOnlyGenerics() throws IOException { process(AbstractGenericProperties.class, (roundEnv, typeUtils) -> { TypeDescriptor typeDescriptor = typeUtils - .resolveTypeDescriptor(roundEnv.getRootElement(AbstractGenericProperties.class)); + .resolveTypeDescriptor(roundEnv.getRootElement(AbstractGenericProperties.class)); assertThat(typeDescriptor.getGenerics().keySet().stream().map(Object::toString)).containsOnly("A", "B", "C"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java index 1f9c8d241e..2cbda570e8 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,8 +55,11 @@ class JsonMarshallerTests { JsonMarshaller marshaller = new JsonMarshaller(); marshaller.write(metadata, outputStream); ConfigurationMetadata read = marshaller.read(new ByteArrayInputStream(outputStream.toByteArray())); - assertThat(read).has(Metadata.withProperty("a.b", StringBuffer.class).fromSource(InputStream.class) - .withDescription("desc").withDefaultValue("x").withDeprecation("Deprecation comment", "b.c.d")); + assertThat(read).has(Metadata.withProperty("a.b", StringBuffer.class) + .fromSource(InputStream.class) + .withDescription("desc") + .withDefaultValue("x") + .withDeprecation("Deprecation comment", "b.c.d")); assertThat(read).has(Metadata.withProperty("b.c.d")); assertThat(read).has(Metadata.withProperty("c").withDefaultValue(123)); assertThat(read).has(Metadata.withProperty("d").withDefaultValue(true)); @@ -126,10 +129,10 @@ class JsonMarshallerTests { null, null, null)); metadata.add(ItemMetadata.newProperty("com.example.bravo", "aaa", "java.lang.Integer", "com.example.Bar", null, null, null, null)); - metadata.add( - ItemMetadata.newProperty("com.example.alpha", "ddd", null, "com.example.Bar", null, null, null, null)); - metadata.add( - ItemMetadata.newProperty("com.example.alpha", "ccc", null, "com.example.Foo", null, null, null, null)); + metadata + .add(ItemMetadata.newProperty("com.example.alpha", "ddd", null, "com.example.Bar", null, null, null, null)); + metadata + .add(ItemMetadata.newProperty("com.example.alpha", "ccc", null, "com.example.Foo", null, null, null, null)); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonMarshaller marshaller = new JsonMarshaller(); marshaller.write(metadata, outputStream); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/Metadata.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/Metadata.java index 49faa351a4..898138eebd 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/Metadata.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/Metadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -209,9 +209,10 @@ public final class Metadata { } private ItemMetadata findItem(ConfigurationMetadata metadata, String name) { - List candidates = metadata.getItems().stream() - .filter((item) -> item.isOfItemType(this.itemType) && name.equals(item.getName())) - .collect(Collectors.toList()); + List candidates = metadata.getItems() + .stream() + .filter((item) -> item.isOfItemType(this.itemType) && name.equals(item.getName())) + .collect(Collectors.toList()); if (candidates.size() > 1) { throw new IllegalStateException("More than one metadata item with name '" + name + "': " + candidates); } @@ -391,7 +392,7 @@ public final class Metadata { if (this.parameters != null) { for (Map.Entry entry : this.parameters.entrySet()) { if (!IsMapContaining.hasEntry(entry.getKey(), entry.getValue()) - .matches(valueProvider.getParameters())) { + .matches(valueProvider.getParameters())) { return false; } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/RoundEnvironmentTester.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/RoundEnvironmentTester.java index c33496fb50..a6376066e5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/RoundEnvironmentTester.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/RoundEnvironmentTester.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,10 +38,12 @@ public class RoundEnvironmentTester { * @return the {@link TypeElement} */ public TypeElement getRootElement(Class type) { - return (TypeElement) this.roundEnvironment.getRootElements().stream() - .filter((element) -> element.toString().equals(type.getName())).findFirst() - .orElseThrow(() -> new IllegalStateException("No element found for " + type - + " make sure it is included in the list of classes to compile")); + return (TypeElement) this.roundEnvironment.getRootElements() + .stream() + .filter((element) -> element.toString().equals(type.getName())) + .findFirst() + .orElseThrow(() -> new IllegalStateException( + "No element found for " + type + " make sure it is included in the list of classes to compile")); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/dsl/SpringBootExtension.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/dsl/SpringBootExtension.java index 8bce3e9a3e..92f8d565d6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/dsl/SpringBootExtension.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/dsl/SpringBootExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -107,8 +107,8 @@ public class SpringBootExtension { private void configureBuildInfoTask(BuildInfo task) { task.setGroup(BasePlugin.BUILD_GROUP); task.setDescription("Generates a META-INF/build-info.properties file."); - task.getConventionMapping().map("destinationDir", - () -> new File(determineMainSourceSetResourcesOutputDir(), "META-INF")); + task.getConventionMapping() + .map("destinationDir", () -> new File(determineMainSourceSetResourcesOutputDir(), "META-INF")); } private File determineMainSourceSetResourcesOutputDir() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ApplicationPluginAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ApplicationPluginAction.java index 84b2fe03d6..a8bd949c62 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ApplicationPluginAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ApplicationPluginAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,10 +49,10 @@ final class ApplicationPluginAction implements PluginApplicationAction { DistributionContainer distributions = project.getExtensions().getByType(DistributionContainer.class); Distribution distribution = distributions.create("boot"); distribution.getDistributionBaseName() - .convention((project.provider(() -> javaApplication.getApplicationName() + "-boot"))); - TaskProvider bootStartScripts = project.getTasks().register("bootStartScripts", - CreateStartScripts.class, - (task) -> configureCreateStartScripts(project, javaApplication, distribution, task)); + .convention((project.provider(() -> javaApplication.getApplicationName() + "-boot"))); + TaskProvider bootStartScripts = project.getTasks() + .register("bootStartScripts", CreateStartScripts.class, + (task) -> configureCreateStartScripts(project, javaApplication, distribution, task)); CopySpec binCopySpec = project.copySpec().into("bin").from(bootStartScripts); binCopySpec.setFileMode(0755); distribution.getContents().with(binCopySpec); @@ -61,19 +61,19 @@ final class ApplicationPluginAction implements PluginApplicationAction { private void configureCreateStartScripts(Project project, JavaApplication javaApplication, Distribution distribution, CreateStartScripts createStartScripts) { createStartScripts - .setDescription("Generates OS-specific start scripts to run the project as a Spring Boot application."); + .setDescription("Generates OS-specific start scripts to run the project as a Spring Boot application."); ((TemplateBasedScriptGenerator) createStartScripts.getUnixStartScriptGenerator()) - .setTemplate(project.getResources().getText().fromString(loadResource("/unixStartScript.txt"))); + .setTemplate(project.getResources().getText().fromString(loadResource("/unixStartScript.txt"))); ((TemplateBasedScriptGenerator) createStartScripts.getWindowsStartScriptGenerator()) - .setTemplate(project.getResources().getText().fromString(loadResource("/windowsStartScript.txt"))); + .setTemplate(project.getResources().getText().fromString(loadResource("/windowsStartScript.txt"))); project.getConfigurations().all((configuration) -> { if ("bootArchives".equals(configuration.getName())) { distribution.getContents().with(artifactFilesToLibCopySpec(project, configuration)); createStartScripts.setClasspath(configuration.getArtifacts().getFiles()); } }); - createStartScripts.getConventionMapping().map("outputDir", - () -> new File(project.getBuildDir(), "bootScripts")); + createStartScripts.getConventionMapping() + .map("outputDir", () -> new File(project.getBuildDir(), "bootScripts")); createStartScripts.getConventionMapping().map("applicationName", javaApplication::getApplicationName); createStartScripts.getConventionMapping().map("defaultJvmOpts", javaApplication::getApplicationDefaultJvmArgs); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginAction.java index c8b6759f12..8e9e7dd2af 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,9 @@ final class DependencyManagementPluginAction implements PluginApplicationAction @Override public void execute(Project project) { - project.getExtensions().findByType(DependencyManagementExtension.class) - .imports((importsHandler) -> importsHandler.mavenBom(SpringBootPlugin.BOM_COORDINATES)); + project.getExtensions() + .findByType(DependencyManagementExtension.class) + .imports((importsHandler) -> importsHandler.mavenBom(SpringBootPlugin.BOM_COORDINATES)); } @Override 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 8935e4024e..168a933f14 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,34 +87,38 @@ final class JavaPluginAction implements PluginApplicationAction { } private void classifyJarTask(Project project) { - project.getTasks().named(JavaPlugin.JAR_TASK_NAME, Jar.class) - .configure((task) -> task.getArchiveClassifier().convention("plain")); + project.getTasks() + .named(JavaPlugin.JAR_TASK_NAME, Jar.class) + .configure((task) -> task.getArchiveClassifier().convention("plain")); } private void configureBuildTask(Project project) { - project.getTasks().named(BasePlugin.ASSEMBLE_TASK_NAME) - .configure((task) -> task.dependsOn(this.singlePublishedArtifact)); + project.getTasks() + .named(BasePlugin.ASSEMBLE_TASK_NAME) + .configure((task) -> task.dependsOn(this.singlePublishedArtifact)); } private TaskProvider configureBootJarTask(Project project) { SourceSet mainSourceSet = sourceSets(project).getByName(SourceSet.MAIN_SOURCE_SET_NAME); Configuration developmentOnly = project.getConfigurations() - .getByName(SpringBootPlugin.DEVELOPMENT_ONLY_CONFIGURATION_NAME); + .getByName(SpringBootPlugin.DEVELOPMENT_ONLY_CONFIGURATION_NAME); Configuration productionRuntimeClasspath = project.getConfigurations() - .getByName(SpringBootPlugin.PRODUCTION_RUNTIME_CLASSPATH_CONFIGURATION_NAME); + .getByName(SpringBootPlugin.PRODUCTION_RUNTIME_CLASSPATH_CONFIGURATION_NAME); Callable classpath = () -> mainSourceSet.getRuntimeClasspath() - .minus((developmentOnly.minus(productionRuntimeClasspath))).filter(new JarTypeFileSpec()); + .minus((developmentOnly.minus(productionRuntimeClasspath))) + .filter(new JarTypeFileSpec()); TaskProvider resolveMainClassName = ResolveMainClassName - .registerForTask(SpringBootPlugin.BOOT_JAR_TASK_NAME, project, classpath); + .registerForTask(SpringBootPlugin.BOOT_JAR_TASK_NAME, project, classpath); return project.getTasks().register(SpringBootPlugin.BOOT_JAR_TASK_NAME, BootJar.class, (bootJar) -> { bootJar.setDescription( "Assembles an executable jar archive containing the main classes and their dependencies."); bootJar.setGroup(BasePlugin.BUILD_GROUP); bootJar.classpath(classpath); Provider manifestStartClass = project - .provider(() -> (String) bootJar.getManifest().getAttributes().get("Start-Class")); - bootJar.getMainClass().convention(resolveMainClassName.flatMap((resolver) -> manifestStartClass.isPresent() - ? manifestStartClass : resolveMainClassName.get().readMainClassName())); + .provider(() -> (String) bootJar.getManifest().getAttributes().get("Start-Class")); + bootJar.getMainClass() + .convention(resolveMainClassName.flatMap((resolver) -> manifestStartClass.isPresent() + ? manifestStartClass : resolveMainClassName.get().readMainClassName())); }); } @@ -123,8 +127,9 @@ final class JavaPluginAction implements PluginApplicationAction { buildImage.setDescription("Builds an OCI image of the application using the output of the bootJar task"); buildImage.setGroup(BasePlugin.BUILD_GROUP); buildImage.getArchiveFile().set(bootJar.get().getArchiveFile()); - buildImage.getTargetJavaVersion().set(project.provider( - () -> project.getExtensions().getByType(JavaPluginExtension.class).getTargetCompatibility())); + buildImage.getTargetJavaVersion() + .set(project.provider( + () -> project.getExtensions().getByType(JavaPluginExtension.class).getTargetCompatibility())); }); } @@ -134,7 +139,8 @@ final class JavaPluginAction implements PluginApplicationAction { private void configureBootRunTask(Project project) { Callable classpath = () -> sourceSets(project).findByName(SourceSet.MAIN_SOURCE_SET_NAME) - .getRuntimeClasspath().filter(new JarTypeFileSpec()); + .getRuntimeClasspath() + .filter(new JarTypeFileSpec()); TaskProvider resolveProvider = ResolveMainClassName.registerForTask("bootRun", project, classpath); project.getTasks().register("bootRun", BootRun.class, (run) -> { @@ -183,26 +189,28 @@ final class JavaPluginAction implements PluginApplicationAction { } private void configureAdditionalMetadataLocations(Project project) { - project.afterEvaluate((evaluated) -> evaluated.getTasks().withType(JavaCompile.class) - .configureEach(this::configureAdditionalMetadataLocations)); + project.afterEvaluate((evaluated) -> evaluated.getTasks() + .withType(JavaCompile.class) + .configureEach(this::configureAdditionalMetadataLocations)); } private void configureAdditionalMetadataLocations(JavaCompile compile) { sourceSets(compile.getProject()).stream() - .filter((candidate) -> candidate.getCompileJavaTaskName().equals(compile.getName())) - .map((match) -> match.getResources().getSrcDirs()).findFirst() - .ifPresent((locations) -> compile.doFirst(new AdditionalMetadataLocationsConfigurer(locations))); + .filter((candidate) -> candidate.getCompileJavaTaskName().equals(compile.getName())) + .map((match) -> match.getResources().getSrcDirs()) + .findFirst() + .ifPresent((locations) -> compile.doFirst(new AdditionalMetadataLocationsConfigurer(locations))); } private void configureDevelopmentOnlyConfiguration(Project project) { Configuration developmentOnly = project.getConfigurations() - .create(SpringBootPlugin.DEVELOPMENT_ONLY_CONFIGURATION_NAME); + .create(SpringBootPlugin.DEVELOPMENT_ONLY_CONFIGURATION_NAME); developmentOnly - .setDescription("Configuration for development-only dependencies such as Spring Boot's DevTools."); + .setDescription("Configuration for development-only dependencies such as Spring Boot's DevTools."); Configuration runtimeClasspath = project.getConfigurations() - .getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME); + .getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME); Configuration productionRuntimeClasspath = project.getConfigurations() - .create(SpringBootPlugin.PRODUCTION_RUNTIME_CLASSPATH_CONFIGURATION_NAME); + .create(SpringBootPlugin.PRODUCTION_RUNTIME_CLASSPATH_CONFIGURATION_NAME); AttributeContainer attributes = productionRuntimeClasspath.getAttributes(); ObjectFactory objectFactory = project.getObjects(); attributes.attribute(Usage.USAGE_ATTRIBUTE, objectFactory.named(Usage.class, Usage.JAVA_RUNTIME)); @@ -243,14 +251,16 @@ final class JavaPluginAction implements PluginApplicationAction { private boolean hasConfigurationProcessorOnClasspath(JavaCompile compile) { Set files = (compile.getOptions().getAnnotationProcessorPath() != null) ? compile.getOptions().getAnnotationProcessorPath().getFiles() : compile.getClasspath().getFiles(); - return files.stream().map(File::getName) - .anyMatch((name) -> name.startsWith("spring-boot-configuration-processor")); + return files.stream() + .map(File::getName) + .anyMatch((name) -> name.startsWith("spring-boot-configuration-processor")); } private void configureAdditionalMetadataLocations(JavaCompile compile) { - compile.getOptions().getCompilerArgs() - .add("-Aorg.springframework.boot.configurationprocessor.additionalMetadataLocations=" - + StringUtils.collectionToCommaDelimitedString(this.locations)); + compile.getOptions() + .getCompilerArgs() + .add("-Aorg.springframework.boot.configurationprocessor.additionalMetadataLocations=" + + StringUtils.collectionToCommaDelimitedString(this.locations)); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/KotlinPluginAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/KotlinPluginAction.java index a4bce532bd..afb5eefac1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/KotlinPluginAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/KotlinPluginAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,9 @@ class KotlinPluginAction implements PluginApplicationAction { } private void enableJavaParametersOption(Project project) { - project.getTasks().withType(KotlinCompile.class) - .configureEach((compile) -> compile.getKotlinOptions().setJavaParameters(true)); + project.getTasks() + .withType(KotlinCompile.class) + .configureEach((compile) -> compile.getKotlinOptions().setJavaParameters(true)); } @Override diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ResolveMainClassName.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ResolveMainClassName.java index 86dbbd99c3..7981243af9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ResolveMainClassName.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ResolveMainClassName.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -136,8 +136,13 @@ public class ResolveMainClassName extends DefaultTask { if (configuredMainClass != null) { return configuredMainClass; } - return getClasspath().filter(File::isDirectory).getFiles().stream().map(this::findMainClass) - .filter(Objects::nonNull).findFirst().orElse(""); + return getClasspath().filter(File::isDirectory) + .getFiles() + .stream() + .map(this::findMainClass) + .filter(Objects::nonNull) + .findFirst() + .orElse(""); } private String findMainClass(File file) { @@ -156,23 +161,23 @@ public class ResolveMainClassName extends DefaultTask { static TaskProvider registerForTask(String taskName, Project project, Callable classpath) { TaskProvider resolveMainClassNameProvider = project.getTasks() - .register(taskName + "MainClassName", ResolveMainClassName.class, (resolveMainClassName) -> { - resolveMainClassName.setDescription( - "Resolves the name of the application's main class for the " + taskName + " task."); - resolveMainClassName.setGroup(BasePlugin.BUILD_GROUP); - resolveMainClassName.setClasspath(classpath); - resolveMainClassName.getConfiguredMainClassName().convention(project.provider(() -> { - String javaApplicationMainClass = getJavaApplicationMainClass(project); - if (javaApplicationMainClass != null) { - return javaApplicationMainClass; - } - SpringBootExtension springBootExtension = project.getExtensions() - .findByType(SpringBootExtension.class); - return springBootExtension.getMainClass().getOrNull(); - })); - resolveMainClassName.getOutputFile() - .set(project.getLayout().getBuildDirectory().file(taskName + "MainClassName")); - }); + .register(taskName + "MainClassName", ResolveMainClassName.class, (resolveMainClassName) -> { + resolveMainClassName + .setDescription("Resolves the name of the application's main class for the " + taskName + " task."); + resolveMainClassName.setGroup(BasePlugin.BUILD_GROUP); + resolveMainClassName.setClasspath(classpath); + resolveMainClassName.getConfiguredMainClassName().convention(project.provider(() -> { + String javaApplicationMainClass = getJavaApplicationMainClass(project); + if (javaApplicationMainClass != null) { + return javaApplicationMainClass; + } + SpringBootExtension springBootExtension = project.getExtensions() + .findByType(SpringBootExtension.class); + return springBootExtension.getMainClass().getOrNull(); + })); + resolveMainClassName.getOutputFile() + .set(project.getLayout().getBuildDirectory().file(taskName + "MainClassName")); + }); return resolveMainClassNameProvider; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/WarPluginAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/WarPluginAction.java index 308ef31b8f..c5f5fe365b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/WarPluginAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/WarPluginAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,33 +63,36 @@ class WarPluginAction implements PluginApplicationAction { } private void classifyWarTask(Project project) { - project.getTasks().named(WarPlugin.WAR_TASK_NAME, War.class) - .configure((war) -> war.getArchiveClassifier().convention("plain")); + project.getTasks() + .named(WarPlugin.WAR_TASK_NAME, War.class) + .configure((war) -> war.getArchiveClassifier().convention("plain")); } private TaskProvider configureBootWarTask(Project project) { Configuration developmentOnly = project.getConfigurations() - .getByName(SpringBootPlugin.DEVELOPMENT_ONLY_CONFIGURATION_NAME); + .getByName(SpringBootPlugin.DEVELOPMENT_ONLY_CONFIGURATION_NAME); Configuration productionRuntimeClasspath = project.getConfigurations() - .getByName(SpringBootPlugin.PRODUCTION_RUNTIME_CLASSPATH_CONFIGURATION_NAME); + .getByName(SpringBootPlugin.PRODUCTION_RUNTIME_CLASSPATH_CONFIGURATION_NAME); Callable classpath = () -> sourceSets(project).getByName(SourceSet.MAIN_SOURCE_SET_NAME) - .getRuntimeClasspath().minus(providedRuntimeConfiguration(project)) - .minus((developmentOnly.minus(productionRuntimeClasspath))).filter(new JarTypeFileSpec()); + .getRuntimeClasspath() + .minus(providedRuntimeConfiguration(project)) + .minus((developmentOnly.minus(productionRuntimeClasspath))) + .filter(new JarTypeFileSpec()); TaskProvider resolveMainClassName = ResolveMainClassName - .registerForTask(SpringBootPlugin.BOOT_WAR_TASK_NAME, project, classpath); - TaskProvider bootWarProvider = project.getTasks().register(SpringBootPlugin.BOOT_WAR_TASK_NAME, - BootWar.class, (bootWar) -> { - bootWar.setGroup(BasePlugin.BUILD_GROUP); - bootWar.setDescription("Assembles an executable war archive containing webapp" - + " content, and the main classes and their dependencies."); - bootWar.providedClasspath(providedRuntimeConfiguration(project)); - bootWar.setClasspath(classpath); - Provider manifestStartClass = project - .provider(() -> (String) bootWar.getManifest().getAttributes().get("Start-Class")); - bootWar.getMainClass() - .convention(resolveMainClassName.flatMap((resolver) -> manifestStartClass.isPresent() - ? manifestStartClass : resolveMainClassName.get().readMainClassName())); - }); + .registerForTask(SpringBootPlugin.BOOT_WAR_TASK_NAME, project, classpath); + TaskProvider bootWarProvider = project.getTasks() + .register(SpringBootPlugin.BOOT_WAR_TASK_NAME, BootWar.class, (bootWar) -> { + bootWar.setGroup(BasePlugin.BUILD_GROUP); + bootWar.setDescription("Assembles an executable war archive containing webapp" + + " content, and the main classes and their dependencies."); + bootWar.providedClasspath(providedRuntimeConfiguration(project)); + bootWar.setClasspath(classpath); + Provider manifestStartClass = project + .provider(() -> (String) bootWar.getManifest().getAttributes().get("Start-Class")); + bootWar.getMainClass() + .convention(resolveMainClassName.flatMap((resolver) -> manifestStartClass.isPresent() + ? manifestStartClass : resolveMainClassName.get().readMainClassName())); + }); bootWarProvider.map(War::getClasspath); return bootWarProvider; } @@ -105,8 +108,9 @@ class WarPluginAction implements PluginApplicationAction { } private void configureBootBuildImageTask(Project project, TaskProvider bootWar) { - project.getTasks().named(SpringBootPlugin.BOOT_BUILD_IMAGE_TASK_NAME, BootBuildImage.class) - .configure((buildImage) -> buildImage.getArchiveFile().set(bootWar.get().getArchiveFile())); + project.getTasks() + .named(SpringBootPlugin.BOOT_BUILD_IMAGE_TASK_NAME, BootBuildImage.class) + .configure((buildImage) -> buildImage.getArchiveFile().set(bootWar.get().getArchiveFile())); } private void configureArtifactPublication(TaskProvider bootWar) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfo.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfo.java index 993937d7b0..b9b53ed36a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfo.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfo.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,9 @@ public class BuildInfo extends ConventionTask { private final DirectoryProperty destinationDir; public BuildInfo() { - this.destinationDir = getProject().getObjects().directoryProperty() - .convention(getProject().getLayout().getBuildDirectory()); + this.destinationDir = getProject().getObjects() + .directoryProperty() + .convention(getProject().getLayout().getBuildDirectory()); } /** @@ -65,7 +66,7 @@ public class BuildInfo extends ConventionTask { this.properties.getVersion(), this.properties.getName(), this.properties.getTime(), coerceToStringValues(this.properties.getAdditional())); new BuildPropertiesWriter(new File(getDestinationDir(), "build-info.properties")) - .writeBuildProperties(details); + .writeBuildProperties(details); } catch (IOException ex) { throw new TaskExecutionException(this, ex); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootWar.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootWar.java index 120086aa78..1af2003be5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootWar.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootWar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -165,7 +165,7 @@ public class BootWar extends War implements BootArchive { public void providedClasspath(Object... classpath) { FileCollection existingClasspath = this.providedClasspath; this.providedClasspath = getProject() - .files((existingClasspath != null) ? existingClasspath : Collections.emptyList(), classpath); + .files((existingClasspath != null) ? existingClasspath : Collections.emptyList(), classpath); } /** diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootZipCopyAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootZipCopyAction.java index 39e512ec6d..b9c7c59c48 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootZipCopyAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootZipCopyAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,7 +68,7 @@ import org.springframework.util.StringUtils; class BootZipCopyAction implements CopyAction { static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = new GregorianCalendar(1980, Calendar.FEBRUARY, 1, 0, 0, 0) - .getTimeInMillis(); + .getTimeInMillis(); private final File output; @@ -322,8 +322,9 @@ class BootZipCopyAction implements CopyAction { Attributes manifestAttributes = BootZipCopyAction.this.manifest.getAttributes(); String classPathIndex = (String) manifestAttributes.get("Spring-Boot-Classpath-Index"); if (classPathIndex != null) { - List lines = this.writtenLibraries.stream().map((line) -> "- \"" + line + "\"") - .collect(Collectors.toList()); + List lines = this.writtenLibraries.stream() + .map((line) -> "- \"" + line + "\"") + .collect(Collectors.toList()); writeEntry(classPathIndex, ZipEntryContentWriter.fromLines(BootZipCopyAction.this.encoding, lines), true); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/LayeredSpec.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/LayeredSpec.java index d9e77e883a..f27954c6d9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/LayeredSpec.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/LayeredSpec.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -361,14 +361,16 @@ public class LayeredSpec { ContentSelector asLibrarySelector(Function> filterFactory) { Layer layer = new Layer(getIntoLayer()); - List> includeFilters = getIncludes().stream().map(filterFactory) - .collect(Collectors.toList()); + List> includeFilters = getIncludes().stream() + .map(filterFactory) + .collect(Collectors.toList()); if (this.includeProjectDependencies) { includeFilters = new ArrayList<>(includeFilters); includeFilters.add(Library::isLocal); } - List> excludeFilters = getExcludes().stream().map(filterFactory) - .collect(Collectors.toList()); + List> excludeFilters = getExcludes().stream() + .map(filterFactory) + .collect(Collectors.toList()); if (this.excludeProjectDependencies) { excludeFilters = new ArrayList<>(excludeFilters); excludeFilters.add(Library::isLocal); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/ResolvedDependencies.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/ResolvedDependencies.java index b4644094b0..630f15794b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/ResolvedDependencies.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/ResolvedDependencies.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,11 @@ class ResolvedDependencies { } void processConfiguration(Project project, Configuration configuration) { - Set localProjectIds = project.getRootProject().getAllprojects().stream().map(this::projectId) - .collect(Collectors.toSet()); + Set localProjectIds = project.getRootProject() + .getAllprojects() + .stream() + .map(this::projectId) + .collect(Collectors.toSet()); this.configurationDependencies.put(configuration, new ResolvedConfigurationDependencies(localProjectIds, configuration.getResolvedConfiguration())); } @@ -83,7 +86,7 @@ class ResolvedDependencies { for (ResolvedArtifact resolvedArtifact : lenientConfiguration.getArtifacts()) { ModuleVersionIdentifier id = resolvedArtifact.getModuleVersion().getId(); boolean projectDependency = projectDependencyIds - .contains(id.getGroup() + ":" + id.getName() + ":" + id.getVersion()); + .contains(id.getGroup() + ":" + id.getName() + ":" + id.getVersion()); this.dependencies.put(resolvedArtifact.getFile(), new DependencyDescriptor( new ModuleVersionIdentifierLibraryCoordinates(id), projectDependency)); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/TaskConfigurationAvoidanceTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/TaskConfigurationAvoidanceTests.java index e8c779803b..7b3e241388 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/TaskConfigurationAvoidanceTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/TaskConfigurationAvoidanceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,12 +47,14 @@ class TaskConfigurationAvoidanceTests { @ArchTest void noApisThatCauseEagerTaskConfigurationShouldBeCalled(JavaClasses classes) { ProhibitedMethods prohibited = new ProhibitedMethods(); - prohibited.on(TaskContainer.class).methodsNamed("create", "findByPath, getByPath").method("withType", - Class.class, Action.class); + prohibited.on(TaskContainer.class) + .methodsNamed("create", "findByPath, getByPath") + .method("withType", Class.class, Action.class); prohibited.on(TaskCollection.class).methodsNamed("findByName", "getByName"); - ArchRuleDefinition.noClasses().should() - .callMethodWhere(DescribedPredicate.describe("it would cause eager task configuration", prohibited)) - .check(classes); + ArchRuleDefinition.noClasses() + .should() + .callMethodWhere(DescribedPredicate.describe("it would cause eager task configuration", prohibited)) + .check(classes); } static class DoNotIncludeTests implements ImportOption { @@ -99,7 +101,7 @@ class TaskConfigurationAvoidanceTests { private ProhibitedConfigurer method(String name, Class... parameterTypes) { ProhibitedMethods.this.prohibited - .add(new ProhibitMethod(this.type, name, Arrays.asList(parameterTypes))); + .add(new ProhibitMethod(this.type, name, Arrays.asList(parameterTypes))); return this; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/IntegratingWithActuatorDocumentationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/IntegratingWithActuatorDocumentationTests.java index 748899b2aa..62a36a5803 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/IntegratingWithActuatorDocumentationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/IntegratingWithActuatorDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,13 +44,13 @@ class IntegratingWithActuatorDocumentationTests { void basicBuildInfo() { this.gradleBuild.script("src/docs/gradle/integrating-with-actuator/build-info-basic").build("bootBuildInfo"); assertThat(new File(this.gradleBuild.getProjectDir(), "build/resources/main/META-INF/build-info.properties")) - .isFile(); + .isFile(); } @TestTemplate void buildInfoCustomValues() { this.gradleBuild.script("src/docs/gradle/integrating-with-actuator/build-info-custom-values") - .build("bootBuildInfo"); + .build("bootBuildInfo"); File file = new File(this.gradleBuild.getProjectDir(), "build/resources/main/META-INF/build-info.properties"); assertThat(file).isFile(); Properties properties = buildInfoProperties(file); @@ -63,7 +63,7 @@ class IntegratingWithActuatorDocumentationTests { @TestTemplate void buildInfoAdditional() { this.gradleBuild.script("src/docs/gradle/integrating-with-actuator/build-info-additional") - .build("bootBuildInfo"); + .build("bootBuildInfo"); File file = new File(this.gradleBuild.getProjectDir(), "build/resources/main/META-INF/build-info.properties"); assertThat(file).isFile(); Properties properties = buildInfoProperties(file); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/ManagingDependenciesDocumentationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/ManagingDependenciesDocumentationTests.java index be33e3567d..e33ee06b03 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/ManagingDependenciesDocumentationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/ManagingDependenciesDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,14 +44,16 @@ class ManagingDependenciesDocumentationTests { @TestTemplate void customManagedVersions() { - assertThat(this.gradleBuild.script("src/docs/gradle/managing-dependencies/custom-version").build("slf4jVersion") - .getOutput()).contains("1.7.20"); + assertThat(this.gradleBuild.script("src/docs/gradle/managing-dependencies/custom-version") + .build("slf4jVersion") + .getOutput()).contains("1.7.20"); } @TestTemplate void dependencyManagementInIsolation() { assertThat(this.gradleBuild.script("src/docs/gradle/managing-dependencies/configure-bom") - .build("dependencyManagement").getOutput()).contains("org.springframework.boot:spring-boot-starter "); + .build("dependencyManagement") + .getOutput()).contains("org.springframework.boot:spring-boot-starter "); } @TestTemplate @@ -59,21 +61,23 @@ class ManagingDependenciesDocumentationTests { assumingThat(this.gradleBuild.getDsl() == Dsl.KOTLIN, () -> assertThat( this.gradleBuild.script("src/docs/gradle/managing-dependencies/configure-bom-with-plugins") - .build("dependencyManagement").getOutput()) - .contains("org.springframework.boot:spring-boot-starter TEST-SNAPSHOT")); + .build("dependencyManagement") + .getOutput()) + .contains("org.springframework.boot:spring-boot-starter TEST-SNAPSHOT")); } @TestTemplate void configurePlatform() { assertThat(this.gradleBuild.script("src/docs/gradle/managing-dependencies/configure-platform") - .build("dependencies", "--configuration", "compileClasspath").getOutput()) - .contains("org.springframework.boot:spring-boot-starter "); + .build("dependencies", "--configuration", "compileClasspath") + .getOutput()).contains("org.springframework.boot:spring-boot-starter "); } @TestTemplate void customManagedVersionsWithPlatform() { assertThat(this.gradleBuild.script("src/docs/gradle/managing-dependencies/custom-version-with-platform") - .build("dependencies", "--configuration", "compileClasspath").getOutput()).contains("1.7.20"); + .build("dependencies", "--configuration", "compileClasspath") + .getOutput()).contains("1.7.20"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PackagingDocumentationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PackagingDocumentationTests.java index 9a7e64872f..a6f7d97230 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PackagingDocumentationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PackagingDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,7 +63,7 @@ class PackagingDocumentationTests { assertThat(file).isFile(); try (JarFile jar = new JarFile(file)) { assertThat(jar.getManifest().getMainAttributes().getValue("Start-Class")) - .isEqualTo("com.example.ExampleApplication"); + .isEqualTo("com.example.ExampleApplication"); } } @@ -75,7 +75,7 @@ class PackagingDocumentationTests { assertThat(file).isFile(); try (JarFile jar = new JarFile(file)) { assertThat(jar.getManifest().getMainAttributes().getValue("Start-Class")) - .isEqualTo("com.example.ExampleApplication"); + .isEqualTo("com.example.ExampleApplication"); } } @@ -87,7 +87,7 @@ class PackagingDocumentationTests { assertThat(file).isFile(); try (JarFile jar = new JarFile(file)) { assertThat(jar.getManifest().getMainAttributes().getValue("Start-Class")) - .isEqualTo("com.example.ExampleApplication"); + .isEqualTo("com.example.ExampleApplication"); } } @@ -99,7 +99,7 @@ class PackagingDocumentationTests { assertThat(file).isFile(); try (JarFile jar = new JarFile(file)) { assertThat(jar.getManifest().getMainAttributes().getValue("Start-Class")) - .isEqualTo("com.example.ExampleApplication"); + .isEqualTo("com.example.ExampleApplication"); } } @@ -166,7 +166,7 @@ class PackagingDocumentationTests { assertThat(file).isFile(); try (JarFile jar = new JarFile(file)) { assertThat(jar.getManifest().getMainAttributes().getValue("Main-Class")) - .isEqualTo("org.springframework.boot.loader.PropertiesLauncher"); + .isEqualTo("org.springframework.boot.loader.PropertiesLauncher"); } } @@ -222,8 +222,10 @@ class PackagingDocumentationTests { try (JarFile jar = new JarFile(file)) { JarEntry entry = jar.getJarEntry("BOOT-INF/layers.idx"); assertThat(entry).isNotNull(); - assertThat(Collections.list(jar.entries()).stream().map(JarEntry::getName) - .filter((name) -> name.startsWith("BOOT-INF/lib/spring-boot"))).isNotEmpty(); + assertThat(Collections.list(jar.entries()) + .stream() + .map(JarEntry::getName) + .filter((name) -> name.startsWith("BOOT-INF/lib/spring-boot"))).isNotEmpty(); } } @@ -236,100 +238,105 @@ class PackagingDocumentationTests { try (JarFile jar = new JarFile(file)) { JarEntry entry = jar.getJarEntry("BOOT-INF/layers.idx"); assertThat(entry).isNotNull(); - assertThat(Collections.list(jar.entries()).stream().map(JarEntry::getName) - .filter((name) -> name.startsWith("BOOT-INF/lib/spring-boot"))).isEmpty(); + assertThat(Collections.list(jar.entries()) + .stream() + .map(JarEntry::getName) + .filter((name) -> name.startsWith("BOOT-INF/lib/spring-boot"))).isEmpty(); } } @TestTemplate void bootBuildImageWithBuilder() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-builder") - .build("bootBuildImageBuilder"); + .build("bootBuildImageBuilder"); assertThat(result.getOutput()).contains("builder=mine/java-cnb-builder").contains("runImage=mine/java-cnb-run"); } @TestTemplate void bootBuildImageWithCustomBuildpackJvmVersion() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-env") - .build("bootBuildImageEnvironment"); + .build("bootBuildImageEnvironment"); assertThat(result.getOutput()).contains("BP_JVM_VERSION=8.*"); } @TestTemplate void bootBuildImageWithCustomProxySettings() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-env-proxy") - .build("bootBuildImageEnvironment"); + .build("bootBuildImageEnvironment"); assertThat(result.getOutput()).contains("HTTP_PROXY=http://proxy.example.com") - .contains("HTTPS_PROXY=https://proxy.example.com"); + .contains("HTTPS_PROXY=https://proxy.example.com"); } @TestTemplate void bootBuildImageWithCustomRuntimeConfiguration() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-env-runtime") - .build("bootBuildImageEnvironment"); + .build("bootBuildImageEnvironment"); assertThat(result.getOutput()).contains("BPE_DELIM_JAVA_TOOL_OPTIONS= ") - .contains("BPE_APPEND_JAVA_TOOL_OPTIONS=-XX:+HeapDumpOnOutOfMemoryError"); + .contains("BPE_APPEND_JAVA_TOOL_OPTIONS=-XX:+HeapDumpOnOutOfMemoryError"); } @TestTemplate void bootBuildImageWithCustomImageName() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-name") - .build("bootBuildImageName"); + .build("bootBuildImageName"); assertThat(result.getOutput()).contains("example.com/library/" + this.gradleBuild.getProjectDir().getName()); } @TestTemplate void bootBuildImageWithDockerHostMinikube() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-docker-host") - .build("bootBuildImageDocker"); - assertThat(result.getOutput()).contains("host=tcp://192.168.99.100:2376").contains("tlsVerify=true") - .contains("certPath=/home/user/.minikube/certs"); + .build("bootBuildImageDocker"); + assertThat(result.getOutput()).contains("host=tcp://192.168.99.100:2376") + .contains("tlsVerify=true") + .contains("certPath=/home/user/.minikube/certs"); } @TestTemplate void bootBuildImageWithDockerHostPodman() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-docker-host-podman") - .build("bootBuildImageDocker"); + .build("bootBuildImageDocker"); assertThat(result.getOutput()).contains("host=unix:///run/user/1000/podman/podman.sock") - .contains("bindHostToBuilder=true"); + .contains("bindHostToBuilder=true"); } @TestTemplate void bootBuildImageWithDockerUserAuth() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-docker-auth-user") - .build("bootBuildImageDocker"); - assertThat(result.getOutput()).contains("username=user").contains("password=secret") - .contains("url=https://docker.example.com/v1/").contains("email=user@example.com"); + .build("bootBuildImageDocker"); + assertThat(result.getOutput()).contains("username=user") + .contains("password=secret") + .contains("url=https://docker.example.com/v1/") + .contains("email=user@example.com"); } @TestTemplate void bootBuildImageWithDockerTokenAuth() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-docker-auth-token") - .build("bootBuildImageDocker"); + .build("bootBuildImageDocker"); assertThat(result.getOutput()).contains("token=9cbaf023786cd7..."); } @TestTemplate void bootBuildImagePublish() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-publish") - .build("bootBuildImagePublish"); + .build("bootBuildImagePublish"); assertThat(result.getOutput()).contains("true"); } @TestTemplate void bootBuildImageWithBuildpacks() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-buildpacks") - .build("bootBuildImageBuildpacks"); + .build("bootBuildImageBuildpacks"); assertThat(result.getOutput()).contains("file:///path/to/example-buildpack.tgz") - .contains("urn:cnb:builder:paketo-buildpacks/java"); + .contains("urn:cnb:builder:paketo-buildpacks/java"); } @TestTemplate void bootBuildImageWithCaches() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-caches") - .build("bootBuildImageCaches"); + .build("bootBuildImageCaches"); assertThat(result.getOutput()).containsPattern("buildCache=cache-gradle-[\\d]+.build") - .containsPattern("launchCache=cache-gradle-[\\d]+.launch"); + .containsPattern("launchCache=cache-gradle-[\\d]+.launch"); } protected void jarFile(File file) throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PublishingDocumentationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PublishingDocumentationTests.java index 6bbba73fac..fd28670837 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PublishingDocumentationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PublishingDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,14 +41,16 @@ class PublishingDocumentationTests { @TestTemplate void mavenUpload() { assertThat(this.gradleBuild.expectDeprecationWarningsWithAtLeastVersion("5.6") - .script("src/docs/gradle/publishing/maven").build("deployerRepository").getOutput()) - .contains("https://repo.example.com"); + .script("src/docs/gradle/publishing/maven") + .build("deployerRepository") + .getOutput()).contains("https://repo.example.com"); } @TestTemplate void mavenPublish() { - assertThat(this.gradleBuild.script("src/docs/gradle/publishing/maven-publish").build("publishingConfiguration") - .getOutput()).contains("MavenPublication").contains("https://repo.example.com"); + assertThat(this.gradleBuild.script("src/docs/gradle/publishing/maven-publish") + .build("publishingConfiguration") + .getOutput()).contains("MavenPublication").contains("https://repo.example.com"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/RunningDocumentationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/RunningDocumentationTests.java index 704af45fde..6cdde060b9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/RunningDocumentationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/RunningDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,46 +47,51 @@ class RunningDocumentationTests { void bootRunMain() throws IOException { writeMainClass(); assertThat(this.gradleBuild.script("src/docs/gradle/running/boot-run-main").build("bootRun").getOutput()) - .contains("com.example.ExampleApplication"); + .contains("com.example.ExampleApplication"); } @TestTemplate void applicationPluginMainClassName() throws IOException { writeMainClass(); assertThat(this.gradleBuild.script("src/docs/gradle/running/application-plugin-main-class-name") - .build("bootRun").getOutput()).contains("com.example.ExampleApplication"); + .build("bootRun") + .getOutput()).contains("com.example.ExampleApplication"); } @TestTemplate void springBootDslMainClassName() throws IOException { writeMainClass(); - assertThat(this.gradleBuild.script("src/docs/gradle/running/spring-boot-dsl-main-class-name").build("bootRun") - .getOutput()).contains("com.example.ExampleApplication"); + assertThat(this.gradleBuild.script("src/docs/gradle/running/spring-boot-dsl-main-class-name") + .build("bootRun") + .getOutput()).contains("com.example.ExampleApplication"); } @TestTemplate void bootRunSourceResources() { assertThat(this.gradleBuild.script("src/docs/gradle/running/boot-run-source-resources") - .build("configuredClasspath").getOutput()).contains(new File("src/main/resources").getPath()); + .build("configuredClasspath") + .getOutput()).contains(new File("src/main/resources").getPath()); } @TestTemplate void bootRunDisableOptimizedLaunch() { assertThat(this.gradleBuild.script("src/docs/gradle/running/boot-run-disable-optimized-launch") - .build("optimizedLaunch").getOutput()).contains("false"); + .build("optimizedLaunch") + .getOutput()).contains("false"); } @TestTemplate void bootRunSystemPropertyDefaultValue() { assertThat(this.gradleBuild.script("src/docs/gradle/running/boot-run-system-property") - .build("configuredSystemProperties").getOutput()).contains("com.example.property = default"); + .build("configuredSystemProperties") + .getOutput()).contains("com.example.property = default"); } @TestTemplate void bootRunSystemProperty() { assertThat(this.gradleBuild.script("src/docs/gradle/running/boot-run-system-property") - .build("-Pexample=custom", "configuredSystemProperties").getOutput()) - .contains("com.example.property = custom"); + .build("-Pexample=custom", "configuredSystemProperties") + .getOutput()).contains("com.example.property = custom"); } private void writeMainClass() throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/dsl/BuildInfoDslIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/dsl/BuildInfoDslIntegrationTests.java index c584b3deda..1d4e130e11 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/dsl/BuildInfoDslIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/dsl/BuildInfoDslIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ class BuildInfoDslIntegrationTests { @TestTemplate void basicJar() { assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); Properties properties = buildInfoProperties(); assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName()); assertThat(properties).containsEntry("build.artifact", this.gradleBuild.getProjectDir().getName()); @@ -55,7 +55,7 @@ class BuildInfoDslIntegrationTests { @TestTemplate void jarWithCustomName() { assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); Properties properties = buildInfoProperties(); assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName()); assertThat(properties).containsEntry("build.artifact", "foo"); @@ -66,7 +66,7 @@ class BuildInfoDslIntegrationTests { @TestTemplate void basicWar() { assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); Properties properties = buildInfoProperties(); assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName()); assertThat(properties).containsEntry("build.artifact", this.gradleBuild.getProjectDir().getName()); @@ -77,7 +77,7 @@ class BuildInfoDslIntegrationTests { @TestTemplate void warWithCustomName() { assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); Properties properties = buildInfoProperties(); assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName()); assertThat(properties).containsEntry("build.artifact", "foo"); @@ -88,7 +88,7 @@ class BuildInfoDslIntegrationTests { @TestTemplate void additionalProperties() { assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); Properties properties = buildInfoProperties(); assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName()); assertThat(properties).containsEntry("build.artifact", this.gradleBuild.getProjectDir().getName()); @@ -101,7 +101,7 @@ class BuildInfoDslIntegrationTests { @TestTemplate void classesDependency() { assertThat(this.gradleBuild.build("classes", "--stacktrace").task(":bootBuildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); } private Properties buildInfoProperties() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleCompatibilityExtension.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleCompatibilityExtension.java index dad0414b88..3e18bfd59e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleCompatibilityExtension.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleCompatibilityExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,11 +49,12 @@ final class GradleCompatibilityExtension implements TestTemplateInvocationContex public Stream provideTestTemplateInvocationContexts(ExtensionContext context) { Stream gradleVersions = GRADLE_VERSIONS.stream(); GradleCompatibility gradleCompatibility = AnnotationUtils - .findAnnotation(context.getRequiredTestClass(), GradleCompatibility.class).get(); + .findAnnotation(context.getRequiredTestClass(), GradleCompatibility.class) + .get(); if (StringUtils.hasText(gradleCompatibility.versionsLessThan())) { GradleVersion upperExclusive = GradleVersion.version(gradleCompatibility.versionsLessThan()); gradleVersions = gradleVersions - .filter((version) -> GradleVersion.version(version).compareTo(upperExclusive) < 0); + .filter((version) -> GradleVersion.version(version).compareTo(upperExclusive) < 0); } return gradleVersions.flatMap((version) -> { List invocationContexts = new ArrayList<>(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/ApplicationPluginActionIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/ApplicationPluginActionIntegrationTests.java index 1354085b9f..d30629bb32 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/ApplicationPluginActionIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/ApplicationPluginActionIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,37 +55,37 @@ class ApplicationPluginActionIntegrationTests { @TestTemplate void noBootDistributionWithoutApplicationPluginApplied() { assertThat(this.gradleBuild.build("distributionExists", "-PdistributionName=boot").getOutput()) - .contains("boot exists = false"); + .contains("boot exists = false"); } @TestTemplate void applyingApplicationPluginCreatesBootDistribution() { assertThat(this.gradleBuild.build("distributionExists", "-PdistributionName=boot", "-PapplyApplicationPlugin") - .getOutput()).contains("boot exists = true"); + .getOutput()).contains("boot exists = true"); } @TestTemplate void noBootStartScriptsTaskWithoutApplicationPluginApplied() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootStartScripts").getOutput()) - .contains("bootStartScripts exists = false"); + .contains("bootStartScripts exists = false"); } @TestTemplate void applyingApplicationPluginCreatesBootStartScriptsTask() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootStartScripts", "-PapplyApplicationPlugin") - .getOutput()).contains("bootStartScripts exists = true"); + .getOutput()).contains("bootStartScripts exists = true"); } @TestTemplate void createsBootStartScriptsTaskUsesApplicationPluginsDefaultJvmOpts() { assertThat(this.gradleBuild.build("startScriptsDefaultJvmOpts", "-PapplyApplicationPlugin").getOutput()) - .contains("bootStartScripts defaultJvmOpts = [-Dcom.example.a=alpha, -Dcom.example.b=bravo]"); + .contains("bootStartScripts defaultJvmOpts = [-Dcom.example.a=alpha, -Dcom.example.b=bravo]"); } @TestTemplate void zipDistributionForJarCanBeBuilt() throws IOException { assertThat(this.gradleBuild.build("bootDistZip").task(":bootDistZip").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); String name = this.gradleBuild.getProjectDir().getName(); File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.zip"); assertThat(distribution).isFile(); @@ -97,7 +97,7 @@ class ApplicationPluginActionIntegrationTests { @TestTemplate void tarDistributionForJarCanBeBuilt() throws IOException { assertThat(this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); String name = this.gradleBuild.getProjectDir().getName(); File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.tar"); assertThat(distribution).isFile(); @@ -109,7 +109,7 @@ class ApplicationPluginActionIntegrationTests { @TestTemplate void zipDistributionForWarCanBeBuilt() throws IOException { assertThat(this.gradleBuild.build("bootDistZip").task(":bootDistZip").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); String name = this.gradleBuild.getProjectDir().getName(); File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.zip"); assertThat(distribution).isFile(); @@ -121,7 +121,7 @@ class ApplicationPluginActionIntegrationTests { @TestTemplate void tarDistributionForWarCanBeBuilt() throws IOException { assertThat(this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); String name = this.gradleBuild.getProjectDir().getName(); File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.tar"); assertThat(distribution).isFile(); @@ -133,7 +133,7 @@ class ApplicationPluginActionIntegrationTests { @TestTemplate void applicationNameCanBeUsedToCustomizeDistributionName() throws IOException { assertThat(this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/custom-boot.tar"); assertThat(distribution).isFile(); String name = this.gradleBuild.getProjectDir().getName(); @@ -145,7 +145,7 @@ class ApplicationPluginActionIntegrationTests { @TestTemplate void scriptsHaveCorrectPermissions() throws IOException { assertThat(this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); String name = this.gradleBuild.getProjectDir().getName(); File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.tar"); assertThat(distribution).isFile(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginActionIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginActionIntegrationTests.java index 1041969f10..9ea28687c7 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginActionIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginActionIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,14 +37,16 @@ class DependencyManagementPluginActionIntegrationTests { @TestTemplate void noDependencyManagementIsAppliedByDefault() { - assertThat(this.gradleBuild.build("doesNotHaveDependencyManagement").task(":doesNotHaveDependencyManagement") - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("doesNotHaveDependencyManagement") + .task(":doesNotHaveDependencyManagement") + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate void bomIsImportedWhenDependencyManagementPluginIsApplied() { assertThat(this.gradleBuild.build("hasDependencyManagement", "-PapplyDependencyManagementPlugin") - .task(":hasDependencyManagement").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + .task(":hasDependencyManagement") + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/JavaPluginActionIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/JavaPluginActionIntegrationTests.java index cde3db181c..551d9cd51c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/JavaPluginActionIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/JavaPluginActionIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,52 +48,53 @@ class JavaPluginActionIntegrationTests { @TestTemplate void noBootJarTaskWithoutJavaPluginApplied() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootJar").getOutput()) - .contains("bootJar exists = false"); + .contains("bootJar exists = false"); } @TestTemplate void applyingJavaPluginCreatesBootJarTask() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootJar", "-PapplyJavaPlugin").getOutput()) - .contains("bootJar exists = true"); + .contains("bootJar exists = true"); } @TestTemplate void noBootRunTaskWithoutJavaPluginApplied() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootRun").getOutput()) - .contains("bootRun exists = false"); + .contains("bootRun exists = false"); } @TestTemplate void applyingJavaPluginCreatesBootRunTask() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootRun", "-PapplyJavaPlugin").getOutput()) - .contains("bootRun exists = true"); + .contains("bootRun exists = true"); } @TestTemplate void javaCompileTasksUseUtf8Encoding() { assertThat(this.gradleBuild.build("javaCompileEncoding", "-PapplyJavaPlugin").getOutput()) - .contains("compileJava = UTF-8").contains("compileTestJava = UTF-8"); + .contains("compileJava = UTF-8") + .contains("compileTestJava = UTF-8"); } @TestTemplate void javaCompileTasksUseParametersCompilerFlagByDefault() { assertThat(this.gradleBuild.build("javaCompileTasksCompilerArgs").getOutput()) - .contains("compileJava compiler args: [-parameters]") - .contains("compileTestJava compiler args: [-parameters]"); + .contains("compileJava compiler args: [-parameters]") + .contains("compileTestJava compiler args: [-parameters]"); } @TestTemplate void javaCompileTasksUseParametersAndAdditionalCompilerFlags() { assertThat(this.gradleBuild.build("javaCompileTasksCompilerArgs").getOutput()) - .contains("compileJava compiler args: [-parameters, -Xlint:all]") - .contains("compileTestJava compiler args: [-parameters, -Xlint:all]"); + .contains("compileJava compiler args: [-parameters, -Xlint:all]") + .contains("compileTestJava compiler args: [-parameters, -Xlint:all]"); } @TestTemplate void javaCompileTasksCanOverrideDefaultParametersCompilerFlag() { assertThat(this.gradleBuild.build("javaCompileTasksCompilerArgs").getOutput()) - .contains("compileJava compiler args: [-Xlint:all]") - .contains("compileTestJava compiler args: [-Xlint:all]"); + .contains("compileJava compiler args: [-Xlint:all]") + .contains("compileTestJava compiler args: [-Xlint:all]"); } @TestTemplate @@ -120,7 +121,7 @@ class JavaPluginActionIntegrationTests { File libs = new File(this.gradleBuild.getProjectDir(), "libs"); libs.mkdirs(); new JarOutputStream(new FileOutputStream(new File(libs, "spring-boot-configuration-processor-1.2.3.jar"))) - .close(); + .close(); BuildResult result = this.gradleBuild.build("compileJava"); assertThat(result.task(":compileJava").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(result.getOutput()).contains("compileJava compiler args: [-parameters, -Aorg.springframework.boot." @@ -139,27 +140,32 @@ class JavaPluginActionIntegrationTests { @TestTemplate void applyingJavaPluginCreatesDevelopmentOnlyConfiguration() { assertThat(this.gradleBuild - .build("configurationExists", "-PconfigurationName=developmentOnly", "-PapplyJavaPlugin").getOutput()) - .contains("developmentOnly exists = true"); + .build("configurationExists", "-PconfigurationName=developmentOnly", "-PapplyJavaPlugin") + .getOutput()).contains("developmentOnly exists = true"); } @TestTemplate void productionRuntimeClasspathIsConfiguredWithAttributes() { assertThat(this.gradleBuild - .build("configurationAttributes", "-PconfigurationName=productionRuntimeClasspath", "-PapplyJavaPlugin") - .getOutput()).contains("3 productionRuntimeClasspath attributes:") - .contains("org.gradle.usage: java-runtime").contains("org.gradle.libraryelements: jar") - .contains("org.gradle.dependency.bundling: external"); + .build("configurationAttributes", "-PconfigurationName=productionRuntimeClasspath", "-PapplyJavaPlugin") + .getOutput()).contains("3 productionRuntimeClasspath attributes:") + .contains("org.gradle.usage: java-runtime") + .contains("org.gradle.libraryelements: jar") + .contains("org.gradle.dependency.bundling: external"); } @TestTemplate void productionRuntimeClasspathIsConfiguredWithResolvabilityAndConsumabilityThatMatchesRuntimeClasspath() { - String runtime = this.gradleBuild.build("configurationResolvabilityAndConsumability", - "-PconfigurationName=runtimeClasspath", "-PapplyJavaPlugin").getOutput(); + String runtime = this.gradleBuild + .build("configurationResolvabilityAndConsumability", "-PconfigurationName=runtimeClasspath", + "-PapplyJavaPlugin") + .getOutput(); assertThat(runtime).contains("canBeResolved: true"); assertThat(runtime).contains("canBeConsumed: false"); - String productionRuntime = this.gradleBuild.build("configurationResolvabilityAndConsumability", - "-PconfigurationName=productionRuntimeClasspath", "-PapplyJavaPlugin").getOutput(); + String productionRuntime = this.gradleBuild + .build("configurationResolvabilityAndConsumability", "-PconfigurationName=productionRuntimeClasspath", + "-PapplyJavaPlugin") + .getOutput(); assertThat(productionRuntime).contains("canBeResolved: true"); assertThat(productionRuntime).contains("canBeConsumed: false"); } @@ -177,7 +183,7 @@ class JavaPluginActionIntegrationTests { } } if (!this.gradleBuild.isConfigurationCache() && GradleVersion.version(this.gradleBuild.getGradleVersion()) - .compareTo(GradleVersion.version("7.3.3")) < 0) { + .compareTo(GradleVersion.version("7.3.3")) < 0) { assertThat(configured).containsExactly("help"); } else { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/KotlinPluginActionIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/KotlinPluginActionIntegrationTests.java index 9025861bb8..cdab2b2925 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/KotlinPluginActionIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/KotlinPluginActionIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,20 +49,22 @@ class KotlinPluginActionIntegrationTests { @TestTemplate void kotlinVersionPropertyIsSet() { String output = this.gradleBuild.build("kotlinVersion", "dependencies", "--configuration", "compileClasspath") - .getOutput(); + .getOutput(); assertThat(output).containsPattern("Kotlin version: [0-9]\\.[0-9]\\.[0-9]+"); } @TestTemplate void kotlinCompileTasksUseJavaParametersFlagByDefault() { assertThat(this.gradleBuild.build("kotlinCompileTasksJavaParameters").getOutput()) - .contains("compileKotlin java parameters: true").contains("compileTestKotlin java parameters: true"); + .contains("compileKotlin java parameters: true") + .contains("compileTestKotlin java parameters: true"); } @TestTemplate void kotlinCompileTasksCanOverrideDefaultJavaParametersFlag() { assertThat(this.gradleBuild.build("kotlinCompileTasksJavaParameters").getOutput()) - .contains("compileKotlin java parameters: false").contains("compileTestKotlin java parameters: false"); + .contains("compileKotlin java parameters: false") + .contains("compileTestKotlin java parameters: false"); } @TestTemplate diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/OnlyDependencyManagementIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/OnlyDependencyManagementIntegrationTests.java index e9424d9032..cf9410917d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/OnlyDependencyManagementIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/OnlyDependencyManagementIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ class OnlyDependencyManagementIntegrationTests { @TestTemplate void dependencyManagementCanBeConfiguredUsingCoordinatesConstant() { assertThat(this.gradleBuild.build("dependencyManagement").getOutput()) - .contains("org.springframework.boot:spring-boot-starter "); + .contains("org.springframework.boot:spring-boot-starter "); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginIntegrationTests.java index 72361e8f82..d8b4d419e9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,8 @@ class SpringBootPluginIntegrationTests { @Test void failFastWithVersionOfGradle6LowerThanRequired() { BuildResult result = this.gradleBuild.gradleVersion("6.7.1").buildAndFail(); - assertThat(result.getOutput()).contains( - "Spring Boot plugin requires Gradle 6.8.x, 6.9.x, or 7.x. The current version is Gradle 6.7.1"); + assertThat(result.getOutput()) + .contains("Spring Boot plugin requires Gradle 6.8.x, 6.9.x, or 7.x. The current version is Gradle 6.7.1"); } @DisabledForJreRange(min = JRE.JAVA_16) diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginTests.java index 072baa977d..06cb321a24 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,7 @@ class SpringBootPluginTests { Project project = GradleProjectBuilder.builder().withProjectDir(this.temp).build(); project.getPlugins().apply(SpringBootPlugin.class); Configuration bootArchives = project.getConfigurations() - .getByName(SpringBootPlugin.BOOT_ARCHIVES_CONFIGURATION_NAME); + .getByName(SpringBootPlugin.BOOT_ARCHIVES_CONFIGURATION_NAME); assertThat(bootArchives.isCanBeResolved()).isFalse(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/WarPluginActionIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/WarPluginActionIntegrationTests.java index 524a914cc0..09e23e284a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/WarPluginActionIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/WarPluginActionIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,13 +46,13 @@ class WarPluginActionIntegrationTests { @TestTemplate void noBootWarTaskWithoutWarPluginApplied() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootWar").getOutput()) - .contains("bootWar exists = false"); + .contains("bootWar exists = false"); } @TestTemplate void applyingWarPluginCreatesBootWarTask() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootWar", "-PapplyWarPlugin").getOutput()) - .contains("bootWar exists = true"); + .contains("bootWar exists = true"); } @TestTemplate diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoIntegrationTests.java index a792c552e2..d41e72d07a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,17 +85,21 @@ class BuildInfoIntegrationTests { @TestTemplate void upToDateWhenExecutedTwiceWithFixedTime() { assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo").getOutcome()) - .isEqualTo(TaskOutcome.UP_TO_DATE); + .isEqualTo(TaskOutcome.UP_TO_DATE); } @TestTemplate void notUpToDateWhenExecutedTwiceWithFixedTimeAndChangedProjectVersion() { - assertThat(this.gradleBuild.scriptProperty("projectVersion", "0.1.0").build("buildInfo").task(":buildInfo") - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.scriptProperty("projectVersion", "0.2.0").build("buildInfo").task(":buildInfo") - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("projectVersion", "0.1.0") + .build("buildInfo") + .task(":buildInfo") + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("projectVersion", "0.2.0") + .build("buildInfo") + .task(":buildInfo") + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate @@ -112,13 +116,13 @@ class BuildInfoIntegrationTests { @TestTemplate void reproducibleOutputWithFixedTime() throws IOException, InterruptedException { assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); File buildInfoProperties = new File(this.gradleBuild.getProjectDir(), "build/build-info.properties"); String firstHash = FileUtils.sha1Hash(buildInfoProperties); assertThat(buildInfoProperties.delete()).isTrue(); Thread.sleep(1500); assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); String secondHash = FileUtils.sha1Hash(buildInfoProperties); assertThat(firstHash).isEqualTo(secondHash); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoTests.java index e1c86f4ab7..09d44d4598 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -192,14 +192,15 @@ class BuildInfoTests { BuildInfo task = createTask(createProject("test")); task.getProperties().getAdditional().put("a", null); assertThatThrownBy(() -> buildInfoProperties(task)) - .hasMessage("Additional property 'a' is illegal as its value is null"); + .hasMessage("Additional property 'a' is illegal as its value is null"); } private Project createProject(String projectName) { File projectDir = new File(this.temp, projectName); Project project = GradleProjectBuilder.builder().withProjectDir(projectDir).withName(projectName).build(); - ((ProjectInternal) project).getServices().get(GradlePropertiesController.class) - .loadGradlePropertiesFrom(projectDir); + ((ProjectInternal) project).getServices() + .get(GradlePropertiesController.class) + .loadGradlePropertiesFrom(projectDir); return project; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveIntegrationTests.java index b7dc7e1122..8da60564b6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -86,18 +86,18 @@ abstract class AbstractBootArchiveIntegrationTests { @TestTemplate void basicBuild() { assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate void reproducibleArchive() throws IOException, InterruptedException { assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); File jar = new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0]; String firstHash = FileUtils.sha1Hash(jar); Thread.sleep(1500); assertThat(this.gradleBuild.build("clean", this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); String secondHash = FileUtils.sha1Hash(jar); assertThat(firstHash).isEqualTo(secondHash); } @@ -105,67 +105,81 @@ abstract class AbstractBootArchiveIntegrationTests { @TestTemplate void upToDateWhenBuiltTwice() { assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.UP_TO_DATE); + .isEqualTo(TaskOutcome.UP_TO_DATE); } @TestTemplate void upToDateWhenBuiltTwiceWithLaunchScriptIncluded() { - assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE); + assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE); } @TestTemplate void notUpToDateWhenLaunchScriptWasNotIncludedAndThenIsIncluded() { - assertThat(this.gradleBuild.scriptProperty("launchScript", "").build(this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.scriptProperty("launchScript", "launchScript()").build(this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("launchScript", "") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("launchScript", "launchScript()") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate void notUpToDateWhenLaunchScriptWasIncludedAndThenIsNotIncluded() { - assertThat(this.gradleBuild.scriptProperty("launchScript", "launchScript()").build(this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.scriptProperty("launchScript", "").build(this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("launchScript", "launchScript()") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("launchScript", "") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate void notUpToDateWhenLaunchScriptPropertyChanges() { - assertThat(this.gradleBuild.scriptProperty("launchScriptProperty", "alpha").build(this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.scriptProperty("launchScriptProperty", "bravo").build(this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("launchScriptProperty", "alpha") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("launchScriptProperty", "bravo") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate void applicationPluginMainClassNameIsUsed() throws IOException { assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")) - .isEqualTo("com.example.CustomMain"); + .isEqualTo("com.example.CustomMain"); } } @TestTemplate void springBootExtensionMainClassNameIsUsed() throws IOException { assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")) - .isEqualTo("com.example.CustomMain"); + .isEqualTo("com.example.CustomMain"); } } @TestTemplate void duplicatesAreHandledGracefully() { assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate @@ -174,13 +188,17 @@ abstract class AbstractBootArchiveIntegrationTests { srcMainResources.mkdirs(); new File(srcMainResources, "resource").createNewFile(); assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { - Stream libEntryNames = jarFile.stream().filter((entry) -> !entry.isDirectory()) - .map(JarEntry::getName).filter((name) -> name.startsWith(this.libPath)); + Stream libEntryNames = jarFile.stream() + .filter((entry) -> !entry.isDirectory()) + .map(JarEntry::getName) + .filter((name) -> name.startsWith(this.libPath)); assertThat(libEntryNames).containsExactly(this.libPath + "commons-io-2.6.jar"); - Stream classesEntryNames = jarFile.stream().filter((entry) -> !entry.isDirectory()) - .map(JarEntry::getName).filter((name) -> name.startsWith(this.classesPath)); + Stream classesEntryNames = jarFile.stream() + .filter((entry) -> !entry.isDirectory()) + .map(JarEntry::getName) + .filter((name) -> name.startsWith(this.classesPath)); assertThat(classesEntryNames).containsExactly(this.classesPath + "resource"); } } @@ -188,10 +206,12 @@ abstract class AbstractBootArchiveIntegrationTests { @TestTemplate void developmentOnlyDependenciesCanBeIncludedInTheArchive() throws IOException { assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { - Stream libEntryNames = jarFile.stream().filter((entry) -> !entry.isDirectory()) - .map(JarEntry::getName).filter((name) -> name.startsWith(this.libPath)); + Stream libEntryNames = jarFile.stream() + .filter((entry) -> !entry.isDirectory()) + .map(JarEntry::getName) + .filter((name) -> name.startsWith(this.libPath)); assertThat(libEntryNames).containsExactly(this.libPath + "commons-io-2.6.jar", this.libPath + "commons-lang3-3.9.jar"); } @@ -203,10 +223,12 @@ abstract class AbstractBootArchiveIntegrationTests { createDependenciesStarterJar(new File(flatDirRepository, "starter.jar")); createStandardJar(new File(flatDirRepository, "standard.jar")); assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { - Stream libEntryNames = jarFile.stream().filter((entry) -> !entry.isDirectory()) - .map(JarEntry::getName).filter((name) -> name.startsWith(this.libPath)); + Stream libEntryNames = jarFile.stream() + .filter((entry) -> !entry.isDirectory()) + .map(JarEntry::getName) + .filter((name) -> name.startsWith(this.libPath)); assertThat(libEntryNames).containsExactly(this.libPath + "standard.jar"); } } @@ -215,44 +237,56 @@ abstract class AbstractBootArchiveIntegrationTests { void startClassIsSetByResolvingTheMainClass() throws IOException { copyMainClassApplication(); assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { Attributes mainAttributes = jarFile.getManifest().getMainAttributes(); assertThat(mainAttributes.getValue("Start-Class")) - .isEqualTo("com.example." + this.taskName.toLowerCase(Locale.ENGLISH) + ".main.CustomMainClass"); + .isEqualTo("com.example." + this.taskName.toLowerCase(Locale.ENGLISH) + ".main.CustomMainClass"); } assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.UP_TO_DATE); + .isEqualTo(TaskOutcome.UP_TO_DATE); } @TestTemplate void upToDateWhenBuiltWithDefaultLayeredAndThenWithExplicitLayered() { - assertThat(this.gradleBuild.scriptProperty("layered", "").build("" + this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.scriptProperty("layered", "layered {}").build("" + this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE); + assertThat(this.gradleBuild.scriptProperty("layered", "") + .build("" + this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("layered", "layered {}") + .build("" + this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE); } @TestTemplate void notUpToDateWhenBuiltWithoutLayersAndThenWithLayers() { - assertThat(this.gradleBuild.scriptProperty("layerEnablement", "enabled = false").build(this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.scriptProperty("layerEnablement", "enabled = true").build(this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("layerEnablement", "enabled = false") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("layerEnablement", "enabled = true") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate void notUpToDateWhenBuiltWithLayerToolsAndThenWithoutLayerTools() { - assertThat(this.gradleBuild.scriptProperty("layerTools", "").build(this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.scriptProperty("layerTools", "includeLayerTools = false").build(this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("layerTools", "") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("layerTools", "includeLayerTools = false") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate void layersWithCustomSourceSet() { assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate @@ -260,7 +294,7 @@ abstract class AbstractBootArchiveIntegrationTests { writeMainClass(); writeResource(); assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); Map> indexedLayers; String layerToolsJar = this.libPath + JarModeLibrary.LAYER_TOOLS.getName(); try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { @@ -294,7 +328,7 @@ abstract class AbstractBootArchiveIntegrationTests { assertThat(indexedLayers.get("spring-boot-loader")).containsExactly("org/"); assertThat(indexedLayers.get("snapshot-dependencies")).containsExactlyElementsOf(expectedSnapshotDependencies); assertThat(indexedLayers.get("application")) - .containsExactly(getExpectedApplicationLayerContents(this.classesPath)); + .containsExactly(getExpectedApplicationLayerContents(this.classesPath)); BuildResult listLayers = this.gradleBuild.build("listLayers"); assertThat(listLayers.task(":listLayers").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); String listLayersOutput = listLayers.getOutput(); @@ -312,7 +346,7 @@ abstract class AbstractBootArchiveIntegrationTests { writeMainClass(); writeResource(); assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); Map> indexedLayers; String layerToolsJar = this.libPath + JarModeLibrary.LAYER_TOOLS.getName(); try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { @@ -342,8 +376,8 @@ abstract class AbstractBootArchiveIntegrationTests { assertThat(indexedLayers.get("spring-boot-loader")).containsExactly("org/"); assertThat(indexedLayers.get("snapshot-dependencies")).containsExactlyElementsOf(expectedSnapshotDependencies); assertThat(indexedLayers.get("application")) - .containsExactly(getExpectedApplicationLayerContents(this.classesPath, this.libPath + "alpha-1.2.3.jar", - this.libPath + "bravo-1.2.3.jar", this.libPath + "charlie-1.2.3.jar")); + .containsExactly(getExpectedApplicationLayerContents(this.classesPath, this.libPath + "alpha-1.2.3.jar", + this.libPath + "bravo-1.2.3.jar", this.libPath + "charlie-1.2.3.jar")); BuildResult listLayers = this.gradleBuild.build("listLayers"); assertThat(listLayers.task(":listLayers").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); String listLayersOutput = listLayers.getOutput(); @@ -436,7 +470,7 @@ abstract class AbstractBootArchiveIntegrationTests { expectedSnapshotDependencies.add(this.libPath + "library-1.0-SNAPSHOT.jar"); (layerToolsJar.contains("SNAPSHOT") ? expectedSnapshotDependencies : expectedDependencies).add(layerToolsJar); assertThat(indexedLayers.get("subproject-dependencies")) - .containsExactlyElementsOf(expectedSubprojectDependencies); + .containsExactlyElementsOf(expectedSubprojectDependencies); assertThat(indexedLayers.get("dependencies")).containsExactlyElementsOf(expectedDependencies); assertThat(indexedLayers.get("commons-dependencies")).containsExactly(this.libPath + "commons-lang3-3.9.jar"); assertThat(indexedLayers.get("snapshot-dependencies")).containsExactlyElementsOf(expectedSnapshotDependencies); @@ -472,8 +506,10 @@ abstract class AbstractBootArchiveIntegrationTests { BuildResult build = this.gradleBuild.build(this.taskName); assertThat(build.task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { - Stream classesEntryNames = jarFile.stream().filter((entry) -> !entry.isDirectory()) - .map(JarEntry::getName).filter((name) -> name.startsWith(this.classesPath)); + Stream classesEntryNames = jarFile.stream() + .filter((entry) -> !entry.isDirectory()) + .map(JarEntry::getName) + .filter((name) -> name.startsWith(this.classesPath)); assertThat(classesEntryNames).containsExactly(this.classesPath + "example/Main.class", this.classesPath + "example/Secondary.class"); } @@ -543,8 +579,9 @@ abstract class AbstractBootArchiveIntegrationTests { private void writeResource() { try { - Path path = this.gradleBuild.getProjectDir().toPath() - .resolve(Paths.get("src", "main", "resources", "static", "file.txt")); + Path path = this.gradleBuild.getProjectDir() + .toPath() + .resolve(Paths.get("src", "main", "resources", "static", "file.txt")); Files.createDirectories(path.getParent()); Files.createFile(path); } @@ -578,8 +615,12 @@ abstract class AbstractBootArchiveIntegrationTests { File layer = new File(root, layerName); assertThat(layer).isDirectory(); extractedLayers.put(layerName, - Files.walk(layer.toPath()).filter((path) -> path.toFile().isFile()).map(layer.toPath()::relativize) - .map(Path::toString).map(StringUtils::cleanPath).collect(Collectors.toList())); + Files.walk(layer.toPath()) + .filter((path) -> path.toFile().isFile()) + .map(layer.toPath()::relativize) + .map(Path::toString) + .map(StringUtils::cleanPath) + .collect(Collectors.toList())); } return extractedLayers; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java index 2489dc6de1..b09ecb74b1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -128,7 +128,7 @@ abstract class AbstractBootArchiveTests { assertThat(jarFile.getManifest().getMainAttributes().getValue("Main-Class")).isEqualTo(this.launcherClass); assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")).isEqualTo("com.example.Main"); assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Classes")) - .isEqualTo(this.classesPath); + .isEqualTo(this.classesPath); assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Lib")).isEqualTo(this.libPath); assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Version")).isNotNull(); } @@ -140,10 +140,12 @@ abstract class AbstractBootArchiveTests { this.task.classpath(jarFile("one.jar"), jarFile("two.jar")); executeTask(); try (JarFile jarFile = new JarFile(this.task.getArchiveFile().get().getAsFile())) { - assertThat(jarFile.getEntry(this.libPath + "one.jar")).isNotNull().extracting(ZipEntry::getMethod) - .isEqualTo(ZipEntry.STORED); - assertThat(jarFile.getEntry(this.libPath + "two.jar")).isNotNull().extracting(ZipEntry::getMethod) - .isEqualTo(ZipEntry.STORED); + assertThat(jarFile.getEntry(this.libPath + "one.jar")).isNotNull() + .extracting(ZipEntry::getMethod) + .isEqualTo(ZipEntry.STORED); + assertThat(jarFile.getEntry(this.libPath + "two.jar")).isNotNull() + .extracting(ZipEntry::getMethod) + .isEqualTo(ZipEntry.STORED); } } @@ -277,7 +279,7 @@ abstract class AbstractBootArchiveTests { properties.put("initInfoDescription", this.project.getDescription()); File archiveFile = this.task.getArchiveFile().get().getAsFile(); assertThat(Files.readAllBytes(archiveFile.toPath())) - .startsWith(new DefaultLaunchScript(null, properties).toByteArray()); + .startsWith(new DefaultLaunchScript(null, properties).toByteArray()); try (ZipFile zipFile = new ZipFile(archiveFile)) { assertThat(zipFile.getEntries().hasMoreElements()).isTrue(); } @@ -298,7 +300,7 @@ abstract class AbstractBootArchiveTests { this.task.launchScript((configuration) -> configuration.setScript(customScript)); executeTask(); assertThat(Files.readAllBytes(this.task.getArchiveFile().get().getAsFile().toPath())) - .startsWith("custom script".getBytes()); + .startsWith("custom script".getBytes()); } @Test @@ -324,7 +326,7 @@ abstract class AbstractBootArchiveTests { assertThat(this.task.getArchiveFile().get().getAsFile()).exists(); try (JarFile jarFile = new JarFile(this.task.getArchiveFile().get().getAsFile())) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Main-Class")) - .isEqualTo("com.example.CustomLauncher"); + .isEqualTo("com.example.CustomLauncher"); assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")).isEqualTo("com.example.Main"); assertThat(jarFile.getEntry("org/springframework/boot/loader/LaunchedURLClassLoader.class")).isNull(); } @@ -339,7 +341,7 @@ abstract class AbstractBootArchiveTests { try (JarFile jarFile = new JarFile(this.task.getArchiveFile().get().getAsFile())) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Main-Class")).isEqualTo(this.launcherClass); assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")) - .isEqualTo("com.example.CustomMain"); + .isEqualTo("com.example.CustomMain"); } } @@ -361,7 +363,7 @@ abstract class AbstractBootArchiveTests { @Test void constantTimestampMatchesGradleInternalTimestamp() { assertThat(BootZipCopyAction.CONSTANT_TIME_FOR_ZIP_ENTRIES) - .isEqualTo(ZipCopyAction.CONSTANT_TIME_FOR_ZIP_ENTRIES); + .isEqualTo(ZipCopyAction.CONSTANT_TIME_FOR_ZIP_ENTRIES); } @Test @@ -439,10 +441,10 @@ abstract class AbstractBootArchiveTests { executeTask(); try (JarFile jarFile = new JarFile(this.task.getArchiveFile().get().getAsFile())) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Classes")) - .isEqualTo(this.classesPath); + .isEqualTo(this.classesPath); assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Lib")).isEqualTo(this.libPath); assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Layers-Index")) - .isEqualTo(this.indexPath + "layers.idx"); + .isEqualTo(this.indexPath + "layers.idx"); assertThat(getEntryNames(jarFile)).contains(this.libPath + JarModeLibrary.LAYER_TOOLS.getName()); } } @@ -457,10 +459,10 @@ abstract class AbstractBootArchiveTests { void whenJarIsLayeredThenManifestContainsEntryForLayersIndexInPlaceOfClassesAndLib() throws IOException { try (JarFile jarFile = new JarFile(createLayeredJar())) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Classes")) - .isEqualTo(this.classesPath); + .isEqualTo(this.classesPath); assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Lib")).isEqualTo(this.libPath); assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Layers-Index")) - .isEqualTo(this.indexPath + "layers.idx"); + .isEqualTo(this.indexPath + "layers.idx"); } } @@ -565,7 +567,7 @@ abstract class AbstractBootArchiveTests { List entryNames = getEntryNames( createLayeredJar((configuration) -> configuration.setIncludeLayerTools(false))); assertThat(entryNames) - .doesNotContain(this.indexPath + "layers/dependencies/lib/spring-boot-jarmode-layertools.jar"); + .doesNotContain(this.indexPath + "layers/dependencies/lib/spring-boot-jarmode-layertools.jar"); } protected File jarFile(String name) throws IOException { @@ -655,10 +657,10 @@ abstract class AbstractBootArchiveTests { Set artifacts = new LinkedHashSet<>(); artifacts.add(mockLibraryArtifact("first-library.jar", "com.example", "first-library", "1.0.0")); artifacts.add(mockLibraryArtifact("second-library.jar", "com.example", "second-library", "1.0.0")); - artifacts.add( - mockLibraryArtifact("third-library-SNAPSHOT.jar", "com.example", "third-library", "1.0.0.SNAPSHOT")); artifacts - .add(mockProjectArtifact("first-project-library.jar", "com.example", "first-project-library", "1.0.0")); + .add(mockLibraryArtifact("third-library-SNAPSHOT.jar", "com.example", "third-library", "1.0.0.SNAPSHOT")); + artifacts + .add(mockProjectArtifact("first-project-library.jar", "com.example", "first-project-library", "1.0.0")); artifacts.add(mockProjectArtifact("second-project-library-SNAPSHOT.jar", "com.example", "second-project-library", "1.0.0.SNAPSHOT")); ResolvedConfiguration resolvedConfiguration = mock(ResolvedConfiguration.class); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageIntegrationTests.java index c7d309b86b..7fbcdee652 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -93,7 +93,7 @@ class BootBuildImageIntegrationTests { assertThat(result.getOutput()).contains("---> Test Info buildpack done"); File buildLibs = new File(this.gradleBuild.getProjectDir(), "build/libs"); assertThat(buildLibs.listFiles()) - .containsExactly(new File(buildLibs, this.gradleBuild.getProjectDir().getName() + ".war")); + .containsExactly(new File(buildLibs, this.gradleBuild.getProjectDir().getName() + ".war")); removeImages(projectName); } @@ -109,7 +109,7 @@ class BootBuildImageIntegrationTests { assertThat(result.getOutput()).contains("---> Test Info buildpack done"); File buildLibs = new File(this.gradleBuild.getProjectDir(), "build/libs"); assertThat(buildLibs.listFiles()) - .containsExactly(new File(buildLibs, this.gradleBuild.getProjectDir().getName() + ".war")); + .containsExactly(new File(buildLibs, this.gradleBuild.getProjectDir().getName() + ".war")); removeImages(projectName); } @@ -175,7 +175,7 @@ class BootBuildImageIntegrationTests { assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(result.getOutput()).contains("docker.io/library/" + projectName); assertThat(result.getOutput()).contains("---> Test Info buildpack building") - .contains("---> Test Info buildpack done"); + .contains("---> Test Info buildpack done"); removeImages(projectName); } @@ -217,7 +217,7 @@ class BootBuildImageIntegrationTests { assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(result.getOutput()).contains("docker.io/library/" + projectName); assertThat(result.getOutput()).contains("---> Test Info buildpack building") - .contains("---> Test Info buildpack done"); + .contains("---> Test Info buildpack done"); removeImages(projectName); } @@ -310,7 +310,7 @@ class BootBuildImageIntegrationTests { BuildResult result = this.gradleBuild.buildAndFail("bootBuildImage", "--imageName=example/Invalid-Image-Name"); assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.FAILED); assertThat(result.getOutput()).containsPattern("Unable to parse image reference") - .containsPattern("example/Invalid-Image-Name"); + .containsPattern("example/Invalid-Image-Name"); } @TestTemplate @@ -329,7 +329,7 @@ class BootBuildImageIntegrationTests { BuildResult result = this.gradleBuild.buildAndFail("bootBuildImage", "--pullPolicy=IF_NOT_PRESENT"); assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.FAILED); assertThat(result.getOutput()).containsPattern("Unable to parse image reference") - .containsPattern("example/Invalid-Tag-Name"); + .containsPattern("example/Invalid-Tag-Name"); } @TestTemplate @@ -365,17 +365,18 @@ class BootBuildImageIntegrationTests { private void writeLongNameResource() throws IOException { StringBuilder name = new StringBuilder(); new Random().ints('a', 'z' + 1).limit(128).forEach((i) -> name.append((char) i)); - Path path = this.gradleBuild.getProjectDir().toPath() - .resolve(Paths.get("src", "main", "resources", name.toString())); + Path path = this.gradleBuild.getProjectDir() + .toPath() + .resolve(Paths.get("src", "main", "resources", name.toString())); Files.createDirectories(path.getParent()); Files.createFile(path); } private void writeBuildpackContent() throws IOException { FileAttribute> dirAttribute = PosixFilePermissions - .asFileAttribute(PosixFilePermissions.fromString("rwxr-xr-x")); + .asFileAttribute(PosixFilePermissions.fromString("rwxr-xr-x")); FileAttribute> execFileAttribute = PosixFilePermissions - .asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx")); + .asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx")); File buildpackDir = new File(this.gradleBuild.getProjectDir(), "buildpack/hello-world"); Files.createDirectories(buildpackDir.toPath(), dirAttribute); File binDir = new File(buildpackDir, "bin"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageRegistryIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageRegistryIntegrationTests.java index c37e9b00ca..f3d4c221a2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageRegistryIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageRegistryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ class BootBuildImageRegistryIntegrationTests { @Container static final RegistryContainer registry = new RegistryContainer().withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(3)); + .withStartupTimeout(Duration.ofMinutes(3)); String registryAddress; @@ -72,9 +72,10 @@ class BootBuildImageRegistryIntegrationTests { String imageName = this.registryAddress + "/" + repoName; BuildResult result = this.gradleBuild.build("bootBuildImage", "--imageName=" + imageName); assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(result.getOutput()).contains("Building image").contains("Successfully built image") - .contains("Pushing image '" + imageName + ":latest" + "'") - .contains("Pushed image '" + imageName + ":latest" + "'"); + assertThat(result.getOutput()).contains("Building image") + .contains("Successfully built image") + .contains("Pushing image '" + imageName + ":latest" + "'") + .contains("Pushed image '" + imageName + ":latest" + "'"); ImageReference imageReference = ImageReference.of(imageName); Image pulledImage = new DockerApi().image().pull(imageReference, UpdateListener.none()); assertThat(pulledImage).isNotNull(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageTests.java index f30070bea4..fac6c88156 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -104,8 +104,9 @@ class BootBuildImageTests { void whenIndividualEntriesAreAddedToTheEnvironmentThenTheyAreIncludedInTheRequest() { this.buildImage.environment("ALPHA", "a"); this.buildImage.environment("BRAVO", "b"); - assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a").containsEntry("BRAVO", "b") - .hasSize(2); + assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a") + .containsEntry("BRAVO", "b") + .hasSize(2); } @Test @@ -114,8 +115,9 @@ class BootBuildImageTests { environment.put("ALPHA", "a"); environment.put("BRAVO", "b"); this.buildImage.environment(environment); - assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a").containsEntry("BRAVO", "b") - .hasSize(2); + assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a") + .containsEntry("BRAVO", "b") + .hasSize(2); } @Test @@ -124,8 +126,9 @@ class BootBuildImageTests { environment.put("ALPHA", "a"); environment.put("BRAVO", "b"); this.buildImage.setEnvironment(environment); - assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a").containsEntry("BRAVO", "b") - .hasSize(2); + assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a") + .containsEntry("BRAVO", "b") + .hasSize(2); } @Test @@ -135,8 +138,9 @@ class BootBuildImageTests { environment.put("BRAVO", "b"); this.buildImage.environment("C", "Charlie"); this.buildImage.setEnvironment(environment); - assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a").containsEntry("BRAVO", "b") - .hasSize(2); + assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a") + .containsEntry("BRAVO", "b") + .hasSize(2); } @Test @@ -157,7 +161,8 @@ class BootBuildImageTests { this.buildImage.environment("ALPHA", "a"); this.buildImage.getTargetJavaVersion().set(JavaVersion.VERSION_11); assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a") - .containsEntry("BP_JVM_VERSION", "11.*").hasSize(2); + .containsEntry("BP_JVM_VERSION", "11.*") + .hasSize(2); } @Test @@ -228,23 +233,23 @@ class BootBuildImageTests { @Test void whenBuildpacksAreConfiguredThenRequestHasBuildpacks() { this.buildImage.setBuildpacks(Arrays.asList("example/buildpack1", "example/buildpack2")); - assertThat(this.buildImage.createRequest().getBuildpacks()).containsExactly( - BuildpackReference.of("example/buildpack1"), BuildpackReference.of("example/buildpack2")); + assertThat(this.buildImage.createRequest().getBuildpacks()) + .containsExactly(BuildpackReference.of("example/buildpack1"), BuildpackReference.of("example/buildpack2")); } @Test void whenEntriesAreAddedToBuildpacksThenRequestHasBuildpacks() { this.buildImage.buildpacks(Arrays.asList("example/buildpack1", "example/buildpack2")); - assertThat(this.buildImage.createRequest().getBuildpacks()).containsExactly( - BuildpackReference.of("example/buildpack1"), BuildpackReference.of("example/buildpack2")); + assertThat(this.buildImage.createRequest().getBuildpacks()) + .containsExactly(BuildpackReference.of("example/buildpack1"), BuildpackReference.of("example/buildpack2")); } @Test void whenIndividualEntriesAreAddedToBuildpacksThenRequestHasBuildpacks() { this.buildImage.buildpack("example/buildpack1"); this.buildImage.buildpack("example/buildpack2"); - assertThat(this.buildImage.createRequest().getBuildpacks()).containsExactly( - BuildpackReference.of("example/buildpack1"), BuildpackReference.of("example/buildpack2")); + assertThat(this.buildImage.createRequest().getBuildpacks()) + .containsExactly(BuildpackReference.of("example/buildpack1"), BuildpackReference.of("example/buildpack2")); } @Test @@ -256,14 +261,14 @@ class BootBuildImageTests { void whenBindingsAreConfiguredThenRequestHasBindings() { this.buildImage.setBindings(Arrays.asList("host-src:container-dest:ro", "volume-name:container-dest:rw")); assertThat(this.buildImage.createRequest().getBindings()) - .containsExactly(Binding.of("host-src:container-dest:ro"), Binding.of("volume-name:container-dest:rw")); + .containsExactly(Binding.of("host-src:container-dest:ro"), Binding.of("volume-name:container-dest:rw")); } @Test void whenEntriesAreAddedToBindingsThenRequestHasBindings() { this.buildImage.bindings(Arrays.asList("host-src:container-dest:ro", "volume-name:container-dest:rw")); assertThat(this.buildImage.createRequest().getBindings()) - .containsExactly(Binding.of("host-src:container-dest:ro"), Binding.of("volume-name:container-dest:rw")); + .containsExactly(Binding.of("host-src:container-dest:ro"), Binding.of("volume-name:container-dest:rw")); } @Test @@ -271,7 +276,7 @@ class BootBuildImageTests { this.buildImage.binding("host-src:container-dest:ro"); this.buildImage.binding("volume-name:container-dest:rw"); assertThat(this.buildImage.createRequest().getBindings()) - .containsExactly(Binding.of("host-src:container-dest:ro"), Binding.of("volume-name:container-dest:rw")); + .containsExactly(Binding.of("host-src:container-dest:ro"), Binding.of("volume-name:container-dest:rw")); } @Test @@ -287,8 +292,8 @@ class BootBuildImageTests { @Test void whenTagsAreConfiguredThenRequestHasTags() { - this.buildImage.setTags( - Arrays.asList("my-app:latest", "example.com/my-app:0.0.1-SNAPSHOT", "example.com/my-app:latest")); + this.buildImage + .setTags(Arrays.asList("my-app:latest", "example.com/my-app:0.0.1-SNAPSHOT", "example.com/my-app:latest")); assertThat(this.buildImage.createRequest().getTags()).containsExactly(ImageReference.of("my-app:latest"), ImageReference.of("example.com/my-app:0.0.1-SNAPSHOT"), ImageReference.of("example.com/my-app:latest")); } @@ -296,7 +301,7 @@ class BootBuildImageTests { @Test void whenEntriesAreAddedToTagsThenRequestHasTags() { this.buildImage - .tags(Arrays.asList("my-app:latest", "example.com/my-app:0.0.1-SNAPSHOT", "example.com/my-app:latest")); + .tags(Arrays.asList("my-app:latest", "example.com/my-app:0.0.1-SNAPSHOT", "example.com/my-app:latest")); assertThat(this.buildImage.createRequest().getTags()).containsExactly(ImageReference.of("my-app:latest"), ImageReference.of("example.com/my-app:0.0.1-SNAPSHOT"), ImageReference.of("example.com/my-app:latest")); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarIntegrationTests.java index 3400dd974c..3657a86ad8 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ class BootJarIntegrationTests extends AbstractBootArchiveIntegrationTests { void whenAResolvableCopyOfAnUnresolvableConfigurationIsResolvedThenResolutionSucceeds() { BuildResult build = this.gradleBuild.build("resolveResolvableCopyOfUnresolvableConfiguration"); assertThat(build.task(":resolveResolvableCopyOfUnresolvableConfiguration").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarTests.java index 833ed4c028..fc83e10f7e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,11 +73,11 @@ class BootJarTests extends AbstractBootArchiveTests { assertThat(jarFile.getEntry("BOOT-INF/lib/first-library.jar").getMethod()).isEqualTo(ZipEntry.STORED); assertThat(jarFile.getEntry("BOOT-INF/lib/second-library.jar").getMethod()).isEqualTo(ZipEntry.STORED); assertThat(jarFile.getEntry("BOOT-INF/lib/third-library-SNAPSHOT.jar").getMethod()) - .isEqualTo(ZipEntry.STORED); + .isEqualTo(ZipEntry.STORED); assertThat(jarFile.getEntry("BOOT-INF/lib/first-project-library.jar").getMethod()) - .isEqualTo(ZipEntry.STORED); + .isEqualTo(ZipEntry.STORED); assertThat(jarFile.getEntry("BOOT-INF/lib/second-project-library-SNAPSHOT.jar").getMethod()) - .isEqualTo(ZipEntry.STORED); + .isEqualTo(ZipEntry.STORED); } } @@ -95,7 +95,7 @@ class BootJarTests extends AbstractBootArchiveTests { void classpathIndexPointsToBootInfLibs() throws IOException { try (JarFile jarFile = new JarFile(createPopulatedJar())) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Classpath-Index")) - .isEqualTo("BOOT-INF/classpath.idx"); + .isEqualTo("BOOT-INF/classpath.idx"); assertThat(entryLines(jarFile, "BOOT-INF/classpath.idx")).containsExactly( "- \"BOOT-INF/lib/first-library.jar\"", "- \"BOOT-INF/lib/second-library.jar\"", "- \"BOOT-INF/lib/third-library-SNAPSHOT.jar\"", "- \"BOOT-INF/lib/first-project-library.jar\"", diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootWarTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootWarTests.java index ba240b8572..d37ffb9688 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootWarTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootWarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -107,7 +107,7 @@ class BootWarTests extends AbstractBootArchiveTests { getTask().providedClasspath(jarFile("provided-library.jar")); executeTask(); assertThat(getEntryNames(getTask().getArchiveFile().get().getAsFile())) - .containsSubsequence("WEB-INF/lib/library.jar", "WEB-INF/lib-provided/provided-library.jar"); + .containsSubsequence("WEB-INF/lib/library.jar", "WEB-INF/lib-provided/provided-library.jar"); } @Test @@ -124,7 +124,7 @@ class BootWarTests extends AbstractBootArchiveTests { void classpathIndexPointsToWebInfLibs() throws IOException { try (JarFile jarFile = new JarFile(createPopulatedJar())) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Classpath-Index")) - .isEqualTo("WEB-INF/classpath.idx"); + .isEqualTo("WEB-INF/classpath.idx"); assertThat(entryLines(jarFile, "WEB-INF/classpath.idx")).containsExactly( "- \"WEB-INF/lib/first-library.jar\"", "- \"WEB-INF/lib/second-library.jar\"", "- \"WEB-INF/lib/third-library-SNAPSHOT.jar\"", "- \"WEB-INF/lib/first-project-library.jar\"", diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/DockerSpecTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/DockerSpecTests.java index 2caffd0e12..626e87770d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/DockerSpecTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/DockerSpecTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,10 @@ class DockerSpecTests { assertThat(dockerConfiguration.getHost()).isNull(); assertThat(dockerConfiguration.getBuilderRegistryAuthentication()).isNull(); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"\"").contains("\"password\" : \"\"").contains("\"email\" : \"\"") - .contains("\"serveraddress\" : \"\""); + .contains("\"username\" : \"\"") + .contains("\"password\" : \"\"") + .contains("\"email\" : \"\"") + .contains("\"serveraddress\" : \"\""); } @Test @@ -59,8 +61,10 @@ class DockerSpecTests { assertThat(dockerConfiguration.isBindHostToBuilder()).isFalse(); assertThat(dockerSpec.asDockerConfiguration().getBuilderRegistryAuthentication()).isNull(); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"\"").contains("\"password\" : \"\"").contains("\"email\" : \"\"") - .contains("\"serveraddress\" : \"\""); + .contains("\"username\" : \"\"") + .contains("\"password\" : \"\"") + .contains("\"email\" : \"\"") + .contains("\"serveraddress\" : \"\""); } @Test @@ -75,8 +79,10 @@ class DockerSpecTests { assertThat(dockerConfiguration.isBindHostToBuilder()).isFalse(); assertThat(dockerSpec.asDockerConfiguration().getBuilderRegistryAuthentication()).isNull(); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"\"").contains("\"password\" : \"\"").contains("\"email\" : \"\"") - .contains("\"serveraddress\" : \"\""); + .contains("\"username\" : \"\"") + .contains("\"password\" : \"\"") + .contains("\"email\" : \"\"") + .contains("\"serveraddress\" : \"\""); } @Test @@ -92,8 +98,10 @@ class DockerSpecTests { assertThat(dockerConfiguration.isBindHostToBuilder()).isTrue(); assertThat(dockerSpec.asDockerConfiguration().getBuilderRegistryAuthentication()).isNull(); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"\"").contains("\"password\" : \"\"").contains("\"email\" : \"\"") - .contains("\"serveraddress\" : \"\""); + .contains("\"username\" : \"\"") + .contains("\"password\" : \"\"") + .contains("\"email\" : \"\"") + .contains("\"serveraddress\" : \"\""); } @Test @@ -105,13 +113,15 @@ class DockerSpecTests { "docker2@example.com")); DockerConfiguration dockerConfiguration = dockerSpec.asDockerConfiguration(); assertThat(decoded(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"user1\"").contains("\"password\" : \"secret1\"") - .contains("\"email\" : \"docker1@example.com\"") - .contains("\"serveraddress\" : \"https://docker1.example.com\""); + .contains("\"username\" : \"user1\"") + .contains("\"password\" : \"secret1\"") + .contains("\"email\" : \"docker1@example.com\"") + .contains("\"serveraddress\" : \"https://docker1.example.com\""); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"user2\"").contains("\"password\" : \"secret2\"") - .contains("\"email\" : \"docker2@example.com\"") - .contains("\"serveraddress\" : \"https://docker2.example.com\""); + .contains("\"username\" : \"user2\"") + .contains("\"password\" : \"secret2\"") + .contains("\"email\" : \"docker2@example.com\"") + .contains("\"serveraddress\" : \"https://docker2.example.com\""); assertThat(dockerSpec.asDockerConfiguration().getHost()).isNull(); } @@ -121,7 +131,7 @@ class DockerSpecTests { "https://docker.example.com", "docker@example.com"); DockerSpec dockerSpec = new DockerSpec(builderRegistry, null); assertThatExceptionOfType(GradleException.class).isThrownBy(dockerSpec::asDockerConfiguration) - .withMessageContaining("Invalid Docker builder registry configuration"); + .withMessageContaining("Invalid Docker builder registry configuration"); } @Test @@ -130,7 +140,7 @@ class DockerSpecTests { "https://docker2.example.com", "docker2@example.com"); DockerSpec dockerSpec = new DockerSpec(null, publishRegistry); assertThatExceptionOfType(GradleException.class).isThrownBy(dockerSpec::asDockerConfiguration) - .withMessageContaining("Invalid Docker publish registry configuration"); + .withMessageContaining("Invalid Docker publish registry configuration"); } @Test @@ -139,9 +149,9 @@ class DockerSpecTests { new DockerSpec.DockerRegistrySpec("token2")); DockerConfiguration dockerConfiguration = dockerSpec.asDockerConfiguration(); assertThat(decoded(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())) - .contains("\"identitytoken\" : \"token1\""); + .contains("\"identitytoken\" : \"token1\""); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"identitytoken\" : \"token2\""); + .contains("\"identitytoken\" : \"token2\""); } @Test @@ -152,7 +162,7 @@ class DockerSpecTests { builderRegistry.setToken("token"); DockerSpec dockerSpec = new DockerSpec(builderRegistry, null); assertThatExceptionOfType(GradleException.class).isThrownBy(dockerSpec::asDockerConfiguration) - .withMessageContaining("Invalid Docker builder registry configuration"); + .withMessageContaining("Invalid Docker builder registry configuration"); } String decoded(String value) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenIntegrationTests.java index 09f21ebc12..3e8bceb103 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,22 +43,27 @@ class MavenIntegrationTests { @TestTemplate void bootJarCanBeUploaded() { BuildResult result = this.gradleBuild.expectDeprecationWarningsWithAtLeastVersion("6.0.0") - .build("uploadBootArchives"); + .build("uploadBootArchives"); assertThat(result.task(":uploadBootArchives").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(artifactWithSuffix("jar")).isFile(); assertThat(artifactWithSuffix("pom")).is(pomWith().groupId("com.example") - .artifactId(this.gradleBuild.getProjectDir().getName()).version("1.0").noPackaging().noDependencies()); + .artifactId(this.gradleBuild.getProjectDir().getName()) + .version("1.0") + .noPackaging() + .noDependencies()); } @TestTemplate void bootWarCanBeUploaded() { BuildResult result = this.gradleBuild.expectDeprecationWarningsWithAtLeastVersion("6.0.0") - .build("uploadBootArchives"); + .build("uploadBootArchives"); assertThat(result.task(":uploadBootArchives").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(artifactWithSuffix("war")).isFile(); - assertThat(artifactWithSuffix("pom")) - .is(pomWith().groupId("com.example").artifactId(this.gradleBuild.getProjectDir().getName()) - .version("1.0").packaging("war").noDependencies()); + assertThat(artifactWithSuffix("pom")).is(pomWith().groupId("com.example") + .artifactId(this.gradleBuild.getProjectDir().getName()) + .version("1.0") + .packaging("war") + .noDependencies()); } private File artifactWithSuffix(String suffix) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenPublishingIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenPublishingIntegrationTests.java index f39eafce40..8d03af72af 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenPublishingIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenPublishingIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,10 @@ class MavenPublishingIntegrationTests { assertThat(result.task(":publish").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(artifactWithSuffix("jar")).isFile(); assertThat(artifactWithSuffix("pom")).is(pomWith().groupId("com.example") - .artifactId(this.gradleBuild.getProjectDir().getName()).version("1.0").noPackaging().noDependencies()); + .artifactId(this.gradleBuild.getProjectDir().getName()) + .version("1.0") + .noPackaging() + .noDependencies()); } @TestTemplate @@ -52,9 +55,11 @@ class MavenPublishingIntegrationTests { BuildResult result = this.gradleBuild.build("publish"); assertThat(result.task(":publish").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(artifactWithSuffix("war")).isFile(); - assertThat(artifactWithSuffix("pom")) - .is(pomWith().groupId("com.example").artifactId(this.gradleBuild.getProjectDir().getName()) - .version("1.0").packaging("war").noDependencies()); + assertThat(artifactWithSuffix("pom")).is(pomWith().groupId("com.example") + .artifactId(this.gradleBuild.getProjectDir().getName()) + .version("1.0") + .packaging("war") + .noDependencies()); } private File artifactWithSuffix(String suffix) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/run/BootRunIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/run/BootRunIntegrationTests.java index 85a0865d8d..d8b5d22564 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/run/BootRunIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/run/BootRunIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -88,7 +88,7 @@ class BootRunIntegrationTests { BuildResult result = this.gradleBuild.build("bootRun"); assertThat(result.task(":bootRun").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(result.getOutput()) - .contains("Main class name = com.example.bootrun.classpath.BootRunClasspathApplication"); + .contains("Main class name = com.example.bootrun.classpath.BootRunClasspathApplication"); } @TestTemplate @@ -118,12 +118,15 @@ class BootRunIntegrationTests { BuildResult result = this.gradleBuild.build("bootRun"); assertThat(result.task(":bootRun").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); if (JavaVersion.current().isCompatibleWith(JavaVersion.VERSION_13)) { - assertThat(result.getOutput()).contains("1. -Dcom.bar=baz").contains("2. -Dcom.foo=bar") - .contains("3. -XX:TieredStopAtLevel=1"); + assertThat(result.getOutput()).contains("1. -Dcom.bar=baz") + .contains("2. -Dcom.foo=bar") + .contains("3. -XX:TieredStopAtLevel=1"); } else { - assertThat(result.getOutput()).contains("1. -Dcom.bar=baz").contains("2. -Dcom.foo=bar") - .contains("3. -Xverify:none").contains("4. -XX:TieredStopAtLevel=1"); + assertThat(result.getOutput()).contains("1. -Dcom.bar=baz") + .contains("2. -Dcom.foo=bar") + .contains("3. -Xverify:none") + .contains("4. -XX:TieredStopAtLevel=1"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-test-support/src/main/java/org/springframework/boot/testsupport/gradle/testkit/GradleBuild.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-test-support/src/main/java/org/springframework/boot/testsupport/gradle/testkit/GradleBuild.java index 7268df47aa..65b5a2a3e6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-test-support/src/main/java/org/springframework/boot/testsupport/gradle/testkit/GradleBuild.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-test-support/src/main/java/org/springframework/boot/testsupport/gradle/testkit/GradleBuild.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -213,8 +213,9 @@ public class GradleBuild { if (repository.exists()) { FileSystemUtils.copyRecursively(repository, new File(this.projectDir, "repository")); } - GradleRunner gradleRunner = GradleRunner.create().withProjectDir(this.projectDir) - .withPluginClasspath(pluginClasspath()); + GradleRunner gradleRunner = GradleRunner.create() + .withProjectDir(this.projectDir) + .withPluginClasspath(pluginClasspath()); if (this.dsl != Dsl.KOTLIN && !this.configurationCache) { // see https://github.com/gradle/gradle/issues/6862 gradleRunner.withDebug(true); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/ExtractCommand.java b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/ExtractCommand.java index 2ef17ba199..c9f661facb 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/ExtractCommand.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/ExtractCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -99,7 +99,7 @@ class ExtractCommand extends Command { } try { Files.getFileAttributeView(file.toPath(), BasicFileAttributeView.class) - .setTimes(entry.getLastModifiedTime(), entry.getLastAccessTime(), entry.getCreationTime()); + .setTimes(entry.getLastModifiedTime(), entry.getLastAccessTime(), entry.getCreationTime()); } catch (IOException ex) { // File system does not support setting time attributes. Continue. diff --git a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/IndexedLayers.java b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/IndexedLayers.java index 61826969c1..33e2ae66e0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/IndexedLayers.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/IndexedLayers.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,8 +45,10 @@ class IndexedLayers implements Layers { private final Map> layers = new LinkedHashMap<>(); IndexedLayers(String indexFile) { - String[] lines = Arrays.stream(indexFile.split("\n")).map((line) -> line.replace("\r", "")) - .filter(StringUtils::hasText).toArray(String[]::new); + String[] lines = Arrays.stream(indexFile.split("\n")) + .map((line) -> line.replace("\r", "")) + .filter(StringUtils::hasText) + .toArray(String[]::new); List contents = null; for (String line : lines) { if (line.startsWith("- ")) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/CommandTests.java b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/CommandTests.java index 14fdf76c34..4293af4fa2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/CommandTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/CommandTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -83,14 +83,15 @@ class CommandTests { void runWithUnknownOptionThrowsException() { TestCommand command = new TestCommand("test", VERBOSE_FLAG, LOG_LEVEL_OPTION); assertThatExceptionOfType(UnknownOptionException.class).isThrownBy(() -> run(command, "--invalid")) - .withMessage("--invalid"); + .withMessage("--invalid"); } @Test void runWithOptionMissingRequiredValueThrowsException() { TestCommand command = new TestCommand("test", VERBOSE_FLAG, LOG_LEVEL_OPTION); assertThatExceptionOfType(MissingValueException.class) - .isThrownBy(() -> run(command, "--verbose", "--log-level")).withMessage("--log-level"); + .isThrownBy(() -> run(command, "--verbose", "--log-level")) + .withMessage("--log-level"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ContextTests.java b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ContextTests.java index fc8e320f1c..44c6c5b0a0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ContextTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ class ContextTests { @Test void createWhenSourceIsNullThrowsException() { assertThatIllegalStateException().isThrownBy(() -> new Context(null, this.temp)) - .withMessage("Unable to find source archive"); + .withMessage("Unable to find source archive"); } @Test @@ -47,7 +47,7 @@ class ContextTests { File directory = new File(this.temp, "test"); directory.mkdir(); assertThatIllegalStateException().isThrownBy(() -> new Context(directory, this.temp)) - .withMessage("Unable to find source archive"); + .withMessage("Unable to find source archive"); } @Test @@ -55,7 +55,7 @@ class ContextTests { File zip = new File(this.temp, "test.zip"); Files.createFile(zip.toPath()); assertThatIllegalStateException().isThrownBy(() -> new Context(zip, this.temp)) - .withMessageContaining("test.zip must end with .jar or .war"); + .withMessageContaining("test.zip must end with .jar or .war"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ExtractCommandTests.java b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ExtractCommandTests.java index bc098be1b4..f865a4077b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ExtractCommandTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ExtractCommandTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -103,16 +103,16 @@ class ExtractCommandTests { private void timeAttributes(File file) { try { BasicFileAttributes basicAttributes = Files - .getFileAttributeView(file.toPath(), BasicFileAttributeView.class, new LinkOption[0]) - .readAttributes(); + .getFileAttributeView(file.toPath(), BasicFileAttributeView.class, new LinkOption[0]) + .readAttributes(); assertThat(basicAttributes.lastModifiedTime().to(TimeUnit.SECONDS)) - .isEqualTo(LAST_MODIFIED_TIME.to(TimeUnit.SECONDS)); + .isEqualTo(LAST_MODIFIED_TIME.to(TimeUnit.SECONDS)); assertThat(basicAttributes.creationTime().to(TimeUnit.SECONDS)).satisfiesAnyOf( (creationTime) -> assertThat(creationTime).isEqualTo(CREATION_TIME.to(TimeUnit.SECONDS)), // On macOS (at least) the creation time is the last modified time (creationTime) -> assertThat(creationTime).isEqualTo(LAST_MODIFIED_TIME.to(TimeUnit.SECONDS))); assertThat(basicAttributes.lastAccessTime().to(TimeUnit.SECONDS)) - .isEqualTo(LAST_ACCESS_TIME.to(TimeUnit.SECONDS)); + .isEqualTo(LAST_ACCESS_TIME.to(TimeUnit.SECONDS)); } catch (IOException ex) { throw new RuntimeException(ex); @@ -151,8 +151,8 @@ class ExtractCommandTests { given(this.context.getArchiveFile()).willReturn(file); given(this.context.getWorkingDir()).willReturn(this.extract); assertThatIllegalStateException() - .isThrownBy(() -> this.command.run(Collections.emptyMap(), Collections.emptyList())) - .withMessageContaining("not compatible with layertools"); + .isThrownBy(() -> this.command.run(Collections.emptyMap(), Collections.emptyList())) + .withMessageContaining("not compatible with layertools"); } @Test @@ -168,8 +168,8 @@ class ExtractCommandTests { }); given(this.context.getArchiveFile()).willReturn(this.jarFile); assertThatIllegalStateException() - .isThrownBy(() -> this.command.run(Collections.emptyMap(), Collections.emptyList())) - .withMessageContaining("Entry 'e/../../e.jar' would be written"); + .isThrownBy(() -> this.command.run(Collections.emptyMap(), Collections.emptyList())) + .withMessageContaining("Entry 'e/../../e.jar' would be written"); } private File createJarFile(String name) throws Exception { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/IndexedLayersTests.java b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/IndexedLayersTests.java index 2074dbe605..9b34b4cd30 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/IndexedLayersTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/IndexedLayersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,13 +47,13 @@ class IndexedLayersTests { @Test void createWhenIndexFileIsEmptyThrowsException() { assertThatIllegalStateException().isThrownBy(() -> new IndexedLayers(" \n ")) - .withMessage("Empty layer index file loaded"); + .withMessage("Empty layer index file loaded"); } @Test void createWhenIndexFileIsMalformedThrowsException() { assertThatIllegalStateException().isThrownBy(() -> new IndexedLayers("test")) - .withMessage("Layer index file is malformed"); + .withMessage("Layer index file is malformed"); } @Test @@ -73,7 +73,7 @@ class IndexedLayersTests { void getLayerWhenMatchesNameForMissingLayerThrowsException() throws Exception { IndexedLayers layers = new IndexedLayers(getIndex()); assertThatIllegalStateException().isThrownBy(() -> layers.getLayer(mockEntry("file.jar"))) - .withMessage("No layer defined in index for file " + "'file.jar'"); + .withMessage("No layer defined in index for file " + "'file.jar'"); } @Test 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..12f38e6adb 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,7 @@ public class DefaultLaunchScript implements LaunchScript { private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\{\\{(\\w+)(:.*?)?\\}\\}(?!\\})"); private static final Set FILE_PATH_KEYS = Collections - .unmodifiableSet(Collections.singleton("inlinedConfScript")); + .unmodifiableSet(Collections.singleton("inlinedConfScript")); private final String content; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/AbstractPackagerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/AbstractPackagerTests.java index 25806851a4..d99ddad9c7 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/AbstractPackagerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/AbstractPackagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -104,7 +104,7 @@ abstract class AbstractPackagerTests

{ execute(packager, NO_LIBRARIES); Manifest actualManifest = getPackagedManifest(); assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) - .isEqualTo("org.springframework.boot.loader.JarLauncher"); + .isEqualTo("org.springframework.boot.loader.JarLauncher"); assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C"); assertThat(hasPackagedLauncherClasses()).isTrue(); } @@ -120,7 +120,7 @@ abstract class AbstractPackagerTests

{ execute(packager, NO_LIBRARIES); Manifest actualManifest = getPackagedManifest(); assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) - .isEqualTo("org.springframework.boot.loader.JarLauncher"); + .isEqualTo("org.springframework.boot.loader.JarLauncher"); assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C"); assertThat(hasPackagedLauncherClasses()).isTrue(); } @@ -132,7 +132,7 @@ abstract class AbstractPackagerTests

{ execute(packager, NO_LIBRARIES); Manifest actualManifest = getPackagedManifest(); assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) - .isEqualTo("org.springframework.boot.loader.JarLauncher"); + .isEqualTo("org.springframework.boot.loader.JarLauncher"); assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C"); assertThat(hasPackagedLauncherClasses()).isTrue(); } @@ -142,8 +142,8 @@ abstract class AbstractPackagerTests

{ this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/D.class", ClassWithMainMethod.class); P packager = createPackager(); - assertThatIllegalStateException().isThrownBy(() -> execute(packager, NO_LIBRARIES)).withMessageContaining( - "Unable to find a single main class from the following candidates [a.b.C, a.b.D]"); + assertThatIllegalStateException().isThrownBy(() -> execute(packager, NO_LIBRARIES)) + .withMessageContaining("Unable to find a single main class from the following candidates [a.b.C, a.b.D]"); } @Test @@ -151,7 +151,7 @@ abstract class AbstractPackagerTests

{ this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class); P packager = createPackager(this.testJarFile.getFile()); assertThatIllegalStateException().isThrownBy(() -> execute(packager, NO_LIBRARIES)) - .withMessageContaining("Unable to find main class"); + .withMessageContaining("Unable to find main class"); } @Test @@ -181,7 +181,7 @@ abstract class AbstractPackagerTests

{ this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); P packager = createPackager(); assertThatIllegalArgumentException().isThrownBy(() -> execute(packager, null)) - .withMessageContaining("Libraries must not be null"); + .withMessageContaining("Libraries must not be null"); } @Test @@ -234,7 +234,8 @@ abstract class AbstractPackagerTests

{ String index = getPackagedEntryContent("BOOT-INF/classpath.idx"); String[] libraries = index.split("\\r?\\n"); List expected = Stream.of(libJarFile1, libJarFile2, libJarFile3) - .map((jar) -> "- \"BOOT-INF/lib/" + jar.getName() + "\"").collect(Collectors.toList()); + .map((jar) -> "- \"BOOT-INF/lib/" + jar.getName() + "\"") + .collect(Collectors.toList()); assertThat(Arrays.asList(libraries)).containsExactlyElementsOf(expected); } @@ -265,7 +266,8 @@ abstract class AbstractPackagerTests

{ assertThat(hasPackagedEntry("BOOT-INF/classpath.idx")).isTrue(); String classpathIndex = getPackagedEntryContent("BOOT-INF/classpath.idx"); List expectedClasspathIndex = Stream.of(libJarFile1, libJarFile2, libJarFile3) - .map((file) -> "- \"BOOT-INF/lib/" + file.getName() + "\"").collect(Collectors.toList()); + .map((file) -> "- \"BOOT-INF/lib/" + file.getName() + "\"") + .collect(Collectors.toList()); assertThat(Arrays.asList(classpathIndex.split("\\n"))).containsExactlyElementsOf(expectedClasspathIndex); assertThat(hasPackagedEntry("BOOT-INF/layers.idx")).isTrue(); String layersIndex = getPackagedEntryContent("BOOT-INF/layers.idx"); @@ -283,7 +285,7 @@ abstract class AbstractPackagerTests

{ expectedLayers.add("- '0003':"); expectedLayers.add(" - 'BOOT-INF/lib/" + libJarFile3.getName() + "'"); assertThat(layersIndex.split("\\n")) - .containsExactly(expectedLayers.stream().map((s) -> s.replace('\'', '"')).toArray(String[]::new)); + .containsExactly(expectedLayers.stream().map((s) -> s.replace('\'', '"')).toArray(String[]::new)); } @Test @@ -296,7 +298,7 @@ abstract class AbstractPackagerTests

{ assertThat(hasPackagedEntry("BOOT-INF/classpath.idx")).isTrue(); String classpathIndex = getPackagedEntryContent("BOOT-INF/classpath.idx"); assertThat(Arrays.asList(classpathIndex.split("\\n"))) - .containsExactly("- \"BOOT-INF/lib/spring-boot-jarmode-layertools.jar\""); + .containsExactly("- \"BOOT-INF/lib/spring-boot-jarmode-layertools.jar\""); assertThat(hasPackagedEntry("BOOT-INF/layers.idx")).isTrue(); String layersIndex = getPackagedEntryContent("BOOT-INF/layers.idx"); List expectedLayers = new ArrayList<>(); @@ -305,7 +307,7 @@ abstract class AbstractPackagerTests

{ expectedLayers.add(" - 'META-INF/'"); expectedLayers.add(" - 'org/'"); assertThat(layersIndex.split("\\n")) - .containsExactly(expectedLayers.stream().map((s) -> s.replace('\'', '"')).toArray(String[]::new)); + .containsExactly(expectedLayers.stream().map((s) -> s.replace('\'', '"')).toArray(String[]::new)); } @Test @@ -394,7 +396,7 @@ abstract class AbstractPackagerTests

{ this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class); Packager packager = createPackager(); assertThatIllegalArgumentException().isThrownBy(() -> packager.setLayout(null)) - .withMessageContaining("Layout must not be null"); + .withMessageContaining("Layout must not be null"); } @Test @@ -650,8 +652,10 @@ abstract class AbstractPackagerTests

{ } protected ZipEntry getPackagedEntry(String name) throws IOException { - return getAllPackagedEntries().stream().filter((entry) -> name.equals(entry.getName())).findFirst() - .orElse(null); + return getAllPackagedEntries().stream() + .filter((entry) -> name.equals(entry.getName())) + .findFirst() + .orElse(null); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ImplicitLayerResolverTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ImplicitLayerResolverTests.java index 44350aafb4..558a95cc20 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ImplicitLayerResolverTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ImplicitLayerResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,26 +63,26 @@ class ImplicitLayerResolverTests { @Test void getLayerWhenLoaderClassReturnsLoaderLayer() { assertThat(this.layers.getLayer("org/springframework/boot/loader/Launcher.class")) - .isEqualTo(StandardLayers.SPRING_BOOT_LOADER); + .isEqualTo(StandardLayers.SPRING_BOOT_LOADER); assertThat(this.layers.getLayer("org/springframework/boot/loader/Utils.class")) - .isEqualTo(StandardLayers.SPRING_BOOT_LOADER); + .isEqualTo(StandardLayers.SPRING_BOOT_LOADER); } @Test void getLayerWhenLibraryIsSnapshotReturnsSnapshotLayer() { assertThat(this.layers.getLayer(mockLibrary("spring-boot.2.0.0.BUILD-SNAPSHOT.jar"))) - .isEqualTo(StandardLayers.SNAPSHOT_DEPENDENCIES); + .isEqualTo(StandardLayers.SNAPSHOT_DEPENDENCIES); assertThat(this.layers.getLayer(mockLibrary("spring-boot.2.0.0-SNAPSHOT.jar"))) - .isEqualTo(StandardLayers.SNAPSHOT_DEPENDENCIES); + .isEqualTo(StandardLayers.SNAPSHOT_DEPENDENCIES); assertThat(this.layers.getLayer(mockLibrary("spring-boot.2.0.0.SNAPSHOT.jar"))) - .isEqualTo(StandardLayers.SNAPSHOT_DEPENDENCIES); + .isEqualTo(StandardLayers.SNAPSHOT_DEPENDENCIES); } @Test void getLayerWhenLibraryIsNotSnapshotReturnsDependenciesLayer() { assertThat(this.layers.getLayer(mockLibrary("spring-boot.2.0.0.jar"))).isEqualTo(StandardLayers.DEPENDENCIES); assertThat(this.layers.getLayer(mockLibrary("spring-boot.2.0.0-classified.jar"))) - .isEqualTo(StandardLayers.DEPENDENCIES); + .isEqualTo(StandardLayers.DEPENDENCIES); } private Library mockLibrary(String name) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayerTests.java index 2dddf91b6c..7ca018391a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class LayerTests { @Test void createWhenNameContainsBadCharsThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new Layer("bad!name")) - .withMessage("Malformed layer name 'bad!name'"); + .withMessage("Malformed layer name 'bad!name'"); } @Test @@ -62,11 +62,11 @@ class LayerTests { @Test void createWhenUsingReservedNameThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new Layer("ext")) - .withMessage("Layer name 'ext' is reserved"); + .withMessage("Layer name 'ext' is reserved"); assertThatIllegalArgumentException().isThrownBy(() -> new Layer("ExT")) - .withMessage("Layer name 'ExT' is reserved"); + .withMessage("Layer name 'ExT' is reserved"); assertThatIllegalArgumentException().isThrownBy(() -> new Layer("springbootloader")) - .withMessage("Layer name 'springbootloader' is reserved"); + .withMessage("Layer name 'springbootloader' is reserved"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java index 52ef2e6144..4a074f1c9d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ class LayoutsTests { @Test void unknownFile() { assertThatIllegalStateException().isThrownBy(() -> Layouts.forFile(new File("test.txt"))) - .withMessageContaining("Unable to deduce layout for 'test.txt'"); + .withMessageContaining("Unable to deduce layout for 'test.txt'"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java index f26dabbe2c..bc3fa7f111 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,8 +85,8 @@ class MainClassFinderTests { this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); try (JarFile jarFile = this.testJarFile.getJarFile()) { assertThatIllegalStateException().isThrownBy(() -> MainClassFinder.findSingleMainClass(jarFile, "")) - .withMessageContaining( - "Unable to find a single main class from the following candidates [a.B, a.b.c.E]"); + .withMessageContaining( + "Unable to find a single main class from the following candidates [a.B, a.b.c.E]"); } } @@ -142,9 +142,8 @@ class MainClassFinderTests { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); assertThatIllegalStateException() - .isThrownBy(() -> MainClassFinder.findSingleMainClass(this.testJarFile.getJarSource())) - .withMessageContaining( - "Unable to find a single main class from the following candidates [a.B, a.b.c.E]"); + .isThrownBy(() -> MainClassFinder.findSingleMainClass(this.testJarFile.getJarSource())) + .withMessageContaining("Unable to find a single main class from the following candidates [a.B, a.b.c.E]"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java index a981d86a27..0912ffca20 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,7 +79,7 @@ class RepackagerTests extends AbstractPackagerTests { repackager.repackage(NO_LIBRARIES); Manifest actualManifest = getPackagedManifest(); assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) - .isEqualTo("org.springframework.boot.loader.JarLauncher"); + .isEqualTo("org.springframework.boot.loader.JarLauncher"); assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C"); assertThat(hasPackagedLauncherClasses()).isTrue(); } @@ -121,7 +121,7 @@ class RepackagerTests extends AbstractPackagerTests { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); Repackager repackager = createRepackager(this.testJarFile.getFile(), true); assertThatIllegalArgumentException().isThrownBy(() -> repackager.repackage(null, NO_LIBRARIES)) - .withMessageContaining("Invalid destination"); + .withMessageContaining("Invalid destination"); } @Test @@ -129,7 +129,7 @@ class RepackagerTests extends AbstractPackagerTests { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); Repackager repackager = createRepackager(this.testJarFile.getFile(), true); assertThatIllegalArgumentException().isThrownBy(() -> repackager.repackage(this.tempDir, NO_LIBRARIES)) - .withMessageContaining("Invalid destination"); + .withMessageContaining("Invalid destination"); } @Test @@ -166,7 +166,7 @@ class RepackagerTests extends AbstractPackagerTests { } try { assertThat(Files.getPosixFilePermissions(this.destination.toPath())) - .contains(PosixFilePermission.OWNER_EXECUTE); + .contains(PosixFilePermission.OWNER_EXECUTE); } catch (UnsupportedOperationException ex) { // Probably running the test on Windows @@ -185,8 +185,10 @@ class RepackagerTests extends AbstractPackagerTests { timestamp = entry.getTime(); } else { - assertThat(entry.getTime()).withFailMessage("Expected time %d to be equal to %d for entry %s", - entry.getTime(), timestamp, entry.getName()).isEqualTo(timestamp); + assertThat(entry.getTime()) + .withFailMessage("Expected time %d to be equal to %d for entry %s", entry.getTime(), timestamp, + entry.getName()) + .isEqualTo(timestamp); } } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java index 2b3c73d22a..f90a338818 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,7 +59,7 @@ public class TestJarFile { File file = getFilePath(filename); file.getParentFile().mkdirs(); InputStream inputStream = getClass() - .getResourceAsStream("/" + classToCopy.getName().replace('.', '/') + ".class"); + .getResourceAsStream("/" + classToCopy.getName().replace('.', '/') + ".class"); copyToFile(inputStream, file); if (time != null) { file.setLastModified(time); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/ApplicationContentFilterTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/ApplicationContentFilterTests.java index 36bbec3084..fd2e7838f9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/ApplicationContentFilterTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/ApplicationContentFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,13 +33,13 @@ class ApplicationContentFilterTests { @Test void createWhenPatternIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ApplicationContentFilter(null)) - .withMessage("Pattern must not be empty"); + .withMessage("Pattern must not be empty"); } @Test void createWhenPatternIsEmptyThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ApplicationContentFilter("")) - .withMessage("Pattern must not be empty"); + .withMessage("Pattern must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/IncludeExcludeContentSelectorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/IncludeExcludeContentSelectorTests.java index f5efbfe924..f012acdcab 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/IncludeExcludeContentSelectorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/IncludeExcludeContentSelectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,16 +39,17 @@ class IncludeExcludeContentSelectorTests { @Test void createWhenLayerIsNullThrowsException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new IncludeExcludeContentSelector<>(null, Collections.emptyList(), Collections.emptyList())) - .withMessage("Layer must not be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new IncludeExcludeContentSelector<>(null, Collections.emptyList(), Collections.emptyList())) + .withMessage("Layer must not be null"); } @Test void createWhenFactoryIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new IncludeExcludeContentSelector<>(LAYER, null, null, null)) - .withMessage("FilterFactory must not be null"); + .isThrownBy(() -> new IncludeExcludeContentSelector<>(LAYER, null, null, null)) + .withMessage("FilterFactory must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/LibraryContentFilterTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/LibraryContentFilterTests.java index bcdaf986d2..b6dd41c06c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/LibraryContentFilterTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/LibraryContentFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,13 +38,13 @@ class LibraryContentFilterTests { @Test void createWhenCoordinatesPatternIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new LibraryContentFilter(null)) - .withMessage("CoordinatesPattern must not be empty"); + .withMessage("CoordinatesPattern must not be empty"); } @Test void createWhenCoordinatesPatternIsEmptyThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new LibraryContentFilter("")) - .withMessage("CoordinatesPattern must not be empty"); + .withMessage("CoordinatesPattern must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java index acc05a439f..19c88dda52 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -162,8 +162,10 @@ final class CentralDirectoryFileHeader implements FileHeader { int hour = getChronoValue((datetime >> 11) & 0x1f, ChronoField.HOUR_OF_DAY); int minute = getChronoValue((datetime >> 5) & 0x3f, ChronoField.MINUTE_OF_HOUR); int second = getChronoValue((datetime << 1) & 0x3e, ChronoField.SECOND_OF_MINUTE); - return ZonedDateTime.of(year, month, day, hour, minute, second, 0, ZoneId.systemDefault()).toInstant() - .truncatedTo(ChronoUnit.SECONDS).toEpochMilli(); + return ZonedDateTime.of(year, month, day, hour, minute, second, 0, ZoneId.systemDefault()) + .toInstant() + .truncatedTo(ChronoUnit.SECONDS) + .toEpochMilli(); } long getCrc() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java index d4f1db4984..2766b19ba3 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -98,14 +98,14 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable { private JarEntryCertification[] certifications; private final Map entriesCache = Collections - .synchronizedMap(new LinkedHashMap(16, 0.75f, true) { + .synchronizedMap(new LinkedHashMap(16, 0.75f, true) { - @Override - protected boolean removeEldestEntry(Map.Entry eldest) { - return size() >= ENTRY_CACHE_SIZE; - } + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() >= ENTRY_CACHE_SIZE; + } - }); + }); JarFileEntries(JarFile jarFile, JarEntryFilter filter) { this.jarFile = jarFile; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/ClassPathIndexFileTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/ClassPathIndexFileTests.java index a7e74a6fa5..4cd1b4e8d2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/ClassPathIndexFileTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/ClassPathIndexFileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,8 +44,8 @@ class ClassPathIndexFileTests { @Test void loadIfPossibleWhenRootIsNotFileReturnsNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> ClassPathIndexFile.loadIfPossible(new URL("https://example.com/file"), "test.idx")) - .withMessage("URL does not reference a file"); + .isThrownBy(() -> ClassPathIndexFile.loadIfPossible(new URL("https://example.com/file"), "test.idx")) + .withMessage("URL does not reference a file"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java index d36269c3a4..2b28641f7c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -99,7 +99,7 @@ class PropertiesLauncherTests { @SuppressWarnings("unchecked") private void clearHandlerCache() throws Exception { Map rootFileCache = ((SoftReference>) ReflectionTestUtils - .getField(Handler.class, "rootFileCache")).get(); + .getField(Handler.class, "rootFileCache")).get(); if (rootFileCache != null) { for (JarFile rootJarFile : rootFileCache.values()) { rootJarFile.close(); @@ -127,7 +127,8 @@ class PropertiesLauncherTests { void testNonExistentHome() { System.setProperty("loader.home", "src/test/resources/nonexistent"); assertThatIllegalStateException().isThrownBy(PropertiesLauncher::new) - .withMessageContaining("Invalid source directory").withCauseInstanceOf(IllegalArgumentException.class); + .withMessageContaining("Invalid source directory") + .withCauseInstanceOf(IllegalArgumentException.class); } @Test @@ -194,7 +195,7 @@ class PropertiesLauncherTests { System.setProperty("loader.path", "jar:file:./src/test/resources/nested-jars/app.jar!/"); this.launcher = new PropertiesLauncher(); assertThat(ReflectionTestUtils.getField(this.launcher, "paths").toString()) - .isEqualTo("[jar:file:./src/test/resources/nested-jars/app.jar!/]"); + .isEqualTo("[jar:file:./src/test/resources/nested-jars/app.jar!/]"); List archives = new ArrayList<>(); this.launcher.getClassPathArchivesIterator().forEachRemaining(archives::add); assertThat(archives).areExactly(1, endingWith("foo.jar!/")); @@ -237,7 +238,7 @@ class PropertiesLauncherTests { System.setProperty("loader.main", "demo.Application"); this.launcher = new PropertiesLauncher(); assertThat(ReflectionTestUtils.getField(this.launcher, "paths").toString()) - .isEqualTo("[nested-jars/nested-jar-app.jar!/BOOT-INF/classes/]"); + .isEqualTo("[nested-jars/nested-jar-app.jar!/BOOT-INF/classes/]"); this.launcher.launch(new String[0]); waitFor("Hello World"); } @@ -277,7 +278,7 @@ class PropertiesLauncherTests { System.setProperty("loader.classLoader", URLClassLoader.class.getName()); this.launcher = new PropertiesLauncher(); assertThat(ReflectionTestUtils.getField(this.launcher, "paths").toString()) - .isEqualTo("[more-jars/app.jar, jars/app.jar]"); + .isEqualTo("[more-jars/app.jar, jars/app.jar]"); this.launcher.launch(new String[0]); waitFor("Hello Other World"); } @@ -393,7 +394,7 @@ class PropertiesLauncherTests { catch (Exception ex) { // Expected ClassNotFoundException LaunchedURLClassLoader classLoader = (LaunchedURLClassLoader) Thread.currentThread() - .getContextClassLoader(); + .getContextClassLoader(); classLoader.close(); } URL resource = new URL("jar:" + jarFile.toURI() + "!/nested.jar!/3.dat"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java index 1394af6015..c67cf64425 100755 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -136,7 +136,7 @@ class JarFileArchiveTests { setup(true); try (Archive nestedArchive = this.archive.getNestedArchive(getEntriesMap(this.archive).get("nested.jar")); Archive anotherNestedArchive = this.archive - .getNestedArchive(getEntriesMap(this.archive).get("another-nested.jar"))) { + .getNestedArchive(getEntriesMap(this.archive).get("another-nested.jar"))) { File nested = new File(nestedArchive.getUrl().toURI()); File anotherNested = new File(anotherNestedArchive.getUrl().toURI()); assertThat(nested.getParent()).isEqualTo(anotherNested.getParent()); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java index 28427cd1da..eecc0bf640 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,14 +79,14 @@ class RandomAccessDataFileTests { @Test void fileNotNull() { assertThatIllegalArgumentException().isThrownBy(() -> new RandomAccessDataFile(null)) - .withMessageContaining("File must not be null"); + .withMessageContaining("File must not be null"); } @Test void fileExists() { File file = new File("/does/not/exist"); assertThatIllegalArgumentException().isThrownBy(() -> new RandomAccessDataFile(file)) - .withMessageContaining(String.format("File %s must exist", file.getAbsolutePath())); + .withMessageContaining(String.format("File %s must exist", file.getAbsolutePath())); } @Test @@ -127,13 +127,13 @@ class RandomAccessDataFileTests { @Test void inputStreamReadNullBytes() { assertThatNullPointerException().isThrownBy(() -> this.inputStream.read(null)) - .withMessage("Bytes must not be null"); + .withMessage("Bytes must not be null"); } @Test void inputStreamReadNullBytesWithOffset() { assertThatNullPointerException().isThrownBy(() -> this.inputStream.read(null, 0, 1)) - .withMessage("Bytes must not be null"); + .withMessage("Bytes must not be null"); } @Test @@ -286,7 +286,7 @@ class RandomAccessDataFileTests { for (int i = 0; i < 100; i++) { results.add(executorService.submit(() -> { InputStream subsectionInputStream = RandomAccessDataFileTests.this.file.getSubsection(0, 256) - .getInputStream(); + .getInputStream(); byte[] b = new byte[256]; subsectionInputStream.read(b); return Arrays.equals(b, BYTES); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java index 13950475bc..5105c81365 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -96,32 +96,36 @@ class HandlerTests { @Test void sameFileReturnsFalseForDifferentFileInSameJar() throws MalformedURLException { assertThat(this.handler.sameFile(new URL("jar:file:foo.jar!/the/path/to/the/first/content.txt"), - new URL("jar:file:/foo.jar!/content.txt"))).isFalse(); + new URL("jar:file:/foo.jar!/content.txt"))) + .isFalse(); } @Test void sameFileReturnsFalseForSameFileInDifferentJars() throws MalformedURLException { assertThat(this.handler.sameFile(new URL("jar:file:/the/path/to/the/first.jar!/content.txt"), - new URL("jar:file:/second.jar!/content.txt"))).isFalse(); + new URL("jar:file:/second.jar!/content.txt"))) + .isFalse(); } @Test void sameFileReturnsTrueForSameFileInSameJar() throws MalformedURLException { assertThat(this.handler.sameFile(new URL("jar:file:/the/path/to/the/first.jar!/content.txt"), - new URL("jar:file:/the/path/to/the/first.jar!/content.txt"))).isTrue(); + new URL("jar:file:/the/path/to/the/first.jar!/content.txt"))) + .isTrue(); } @Test void sameFileReturnsTrueForUrlsThatReferenceSameFileViaNestedArchiveAndFromRootOfJar() throws MalformedURLException { assertThat(this.handler.sameFile(new URL("jar:file:/test.jar!/BOOT-INF/classes!/foo.txt"), - new URL("jar:file:/test.jar!/BOOT-INF/classes/foo.txt"))).isTrue(); + new URL("jar:file:/test.jar!/BOOT-INF/classes/foo.txt"))) + .isTrue(); } @Test void hashCodesAreEqualForUrlsThatReferenceSameFileViaNestedArchiveAndFromRootOfJar() throws MalformedURLException { assertThat(this.handler.hashCode(new URL("jar:file:/test.jar!/BOOT-INF/classes!/foo.txt"))) - .isEqualTo(this.handler.hashCode(new URL("jar:file:/test.jar!/BOOT-INF/classes/foo.txt"))); + .isEqualTo(this.handler.hashCode(new URL("jar:file:/test.jar!/BOOT-INF/classes/foo.txt"))); } @Test @@ -157,11 +161,12 @@ class HandlerTests { File testJar = new File(tempDir, "test.jar"); TestJarCreator.createTestJar(testJar); URLConnection connection = new URL(null, "jar:" + testJar.toURI().toURL() + "!/nested.jar!/", this.handler) - .openConnection(); + .openConnection(); assertThat(connection).isInstanceOf(JarURLConnection.class); ((JarURLConnection) connection).getJarFile().close(); URLConnection jdkConnection = new URL(null, "jar:file:" + testJar.toURI().toURL() + "!/nested.jar!/", - this.handler).openConnection(); + this.handler) + .openConnection(); assertThat(jdkConnection).isNotInstanceOf(JarURLConnection.class); assertThat(jdkConnection.getClass().getName()).endsWith(".JarURLConnection"); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java index 4363d5abc5..09458edd5a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -234,7 +234,7 @@ class JarFileTests { void getEntryTime() throws Exception { java.util.jar.JarFile jdkJarFile = new java.util.jar.JarFile(this.rootJarFile); assertThat(this.jarFile.getEntry("META-INF/MANIFEST.MF").getTime()) - .isEqualTo(jdkJarFile.getEntry("META-INF/MANIFEST.MF").getTime()); + .isEqualTo(jdkJarFile.getEntry("META-INF/MANIFEST.MF").getTime()); jdkJarFile.close(); } @@ -280,7 +280,7 @@ class JarFileTests { URL url = new URL(this.jarFile.getUrl(), "missing.dat"); assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/missing.dat"); assertThatExceptionOfType(FileNotFoundException.class) - .isThrownBy(((JarURLConnection) url.openConnection())::getJarEntry); + .isThrownBy(((JarURLConnection) url.openConnection())::getJarEntry); } @Test @@ -375,7 +375,7 @@ class JarFileTests { assertThat(inputStream.read()).isEqualTo(3); assertThat(connection.getURL().toString()).isEqualTo(spec); assertThat(connection.getJarFileURL().toString()) - .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar"); + .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar"); assertThat(connection.getEntryName()).isEqualTo("3.dat"); connection.getJarFile().close(); } @@ -442,9 +442,9 @@ class JarFileTests { StreamUtils.drain(expected.getInputStream(expectedEntry)); if (!actualEntry.getName().equals("META-INF/MANIFEST.MF")) { assertThat(actualEntry.getCertificates()).as(actualEntry.getName()) - .isEqualTo(expectedEntry.getCertificates()); + .isEqualTo(expectedEntry.getCertificates()); assertThat(actualEntry.getCodeSigners()).as(actualEntry.getName()) - .isEqualTo(expectedEntry.getCodeSigners()); + .isEqualTo(expectedEntry.getCodeSigners()); } } assertThat(stopWatch.getTotalTimeSeconds()).isLessThan(3.0); @@ -542,10 +542,11 @@ class JarFileTests { try (JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"))) { URL context = nested.getUrl(); new URL(context, "jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat").openConnection() - .getInputStream().close(); + .getInputStream() + .close(); assertThatExceptionOfType(FileNotFoundException.class) - .isThrownBy(new URL(context, "jar:" + this.rootJarFile.toURI() + "!/no.dat") - .openConnection()::getInputStream); + .isThrownBy(new URL(context, "jar:" + this.rootJarFile.toURI() + "!/no.dat") + .openConnection()::getInputStream); } } finally { @@ -630,7 +631,7 @@ class JarFileTests { } try (JarFile outerJarFile = new JarFile(outer)) { try (JarFile nestedZip64JarFile = outerJarFile - .getNestedJarFile(outerJarFile.getJarEntry("nested-zip64.jar"))) { + .getNestedJarFile(outerJarFile.getJarEntry("nested-zip64.jar"))) { List entries = Collections.list(nestedZip64JarFile.entries()); assertThat(entries).hasSize(65537); for (int i = 0; i < entries.size(); i++) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileWrapperTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileWrapperTests.java index d38f06c01a..8ae25b72e1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileWrapperTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileWrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -148,7 +148,7 @@ class JarFileWrapperTests { // of additional memory being used since cleanup only occurs when the // finalizer thread runs. See gh-22991 assertThatExceptionOfType(NoSuchMethodException.class) - .isThrownBy(() -> JarFileWrapper.class.getDeclaredMethod("close")); + .isThrownBy(() -> JarFileWrapper.class.getDeclaredMethod("close")); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java index c01259c8ba..9ed54d9045 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -174,7 +174,7 @@ class JarURLConnectionTests { URL url = new URL("jar:" + this.rootJarFile.toURI().toURL() + "!/w.jar!/3.dat"); try (JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"))) { assertThatExceptionOfType(FileNotFoundException.class) - .isThrownBy(JarURLConnection.get(url, nested)::getInputStream); + .isThrownBy(JarURLConnection.get(url, nested)::getInputStream); } } @@ -229,7 +229,7 @@ class JarURLConnectionTests { @Test void jarEntryNameWithMixtureOfEncodedAndUnencodedDoubleByteCharacters() { assertThat(new JarEntryName(new StringSequence("%c3%a1/b/\u00c7.class")).toString()) - .isEqualTo("\u00e1/b/\u00c7.class"); + .isEqualTo("\u00e1/b/\u00c7.class"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarUrlProtocolHandler.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarUrlProtocolHandler.java index a99ace59d7..d9e5eb2814 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarUrlProtocolHandler.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarUrlProtocolHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,7 @@ class JarUrlProtocolHandler implements BeforeEachCallback, AfterEachCallback { @SuppressWarnings("unchecked") public void afterEach(ExtensionContext context) throws Exception { Map rootFileCache = ((SoftReference>) ReflectionTestUtils - .getField(Handler.class, "rootFileCache")).get(); + .getField(Handler.class, "rootFileCache")).get(); if (rootFileCache != null) { for (JarFile rootJarFile : rootFileCache.values()) { rootJarFile.close(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java index 9226613c2d..2b853c428a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,25 +32,25 @@ class StringSequenceTests { @Test void createWhenSourceIsNullShouldThrowException() { assertThatNullPointerException().isThrownBy(() -> new StringSequence(null)) - .withMessage("Source must not be null"); + .withMessage("Source must not be null"); } @Test void createWithIndexWhenSourceIsNullShouldThrowException() { assertThatNullPointerException().isThrownBy(() -> new StringSequence(null, 0, 0)) - .withMessage("Source must not be null"); + .withMessage("Source must not be null"); } @Test void createWhenStartIsLessThanZeroShouldThrowException() { assertThatExceptionOfType(StringIndexOutOfBoundsException.class) - .isThrownBy(() -> new StringSequence("x", -1, 0)); + .isThrownBy(() -> new StringSequence("x", -1, 0)); } @Test void createWhenEndIsGreaterThanLengthShouldThrowException() { assertThatExceptionOfType(StringIndexOutOfBoundsException.class) - .isThrownBy(() -> new StringSequence("x", 0, 2)); + .isThrownBy(() -> new StringSequence("x", 0, 2)); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/AbstractArchiveIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/AbstractArchiveIntegrationTests.java index 44ed3dc42b..adbc3402e6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/AbstractArchiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/AbstractArchiveIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -88,7 +88,7 @@ abstract class AbstractArchiveIntegrationTests { } else if (line.startsWith(entryPrefix)) { index.computeIfAbsent(layer, (key) -> new ArrayList<>()) - .add(line.substring(entryPrefix.length() + 1, line.length() - 1)); + .add(line.substring(entryPrefix.length() + 1, line.length() - 1)); } line = reader.readLine(); } @@ -147,7 +147,7 @@ abstract class AbstractArchiveIntegrationTests { withJarFile((jarFile) -> { withEntries(jarFile, (entries) -> { Optional match = entries.filter((entry) -> entry.getName().startsWith(prefix)) - .findFirst(); + .findFirst(); assertThat(match).hasValueSatisfying((entry) -> assertThat(entry.getComment()).isNull()); }); }); @@ -158,9 +158,9 @@ abstract class AbstractArchiveIntegrationTests { withJarFile((jarFile) -> { withEntries(jarFile, (entries) -> { Optional match = entries.filter((entry) -> entry.getName().startsWith(prefix)) - .findFirst(); + .findFirst(); assertThat(match).as("Name starting with %s", prefix) - .hasValueSatisfying((entry) -> assertThat(entry.getComment()).startsWith("UNPACK:")); + .hasValueSatisfying((entry) -> assertThat(entry.getComment()).startsWith("UNPACK:")); }); }); return this; @@ -170,7 +170,7 @@ abstract class AbstractArchiveIntegrationTests { withJarFile((jarFile) -> { withEntries(jarFile, (entries) -> { Optional match = entries.filter((entry) -> entry.getName().startsWith(prefix)) - .findFirst(); + .findFirst(); assertThat(match).isNotPresent(); }); }); @@ -181,8 +181,8 @@ abstract class AbstractArchiveIntegrationTests { List matches = new ArrayList<>(); withJarFile((jarFile) -> withEntries(jarFile, (entries) -> matches.addAll(entries.map(ZipEntry::getName) - .filter((name) -> name.startsWith(path) && name.length() > path.length()) - .collect(Collectors.toList())))); + .filter((name) -> name.startsWith(path) && name.length() > path.length()) + .collect(Collectors.toList())))); return new ListAssert<>(matches); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildImageRegistryIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildImageRegistryIntegrationTests.java index 3a8de6021f..fb0d88aeac 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildImageRegistryIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildImageRegistryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ class BuildImageRegistryIntegrationTests extends AbstractArchiveIntegrationTests @Container static final RegistryContainer registry = new RegistryContainer().withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(3)); + .withStartupTimeout(Duration.ofMinutes(3)); DockerClient dockerClient; @@ -64,17 +64,20 @@ class BuildImageRegistryIntegrationTests extends AbstractArchiveIntegrationTests void whenBuildImageIsInvokedWithPublish(MavenBuild mavenBuild) { String repoName = "test-image"; String imageName = this.registryAddress + "/" + repoName; - mavenBuild.project("build-image-publish").goals("package") - .systemProperty("spring-boot.build-image.imageName", imageName).execute((project) -> { - assertThat(buildLog(project)).contains("Building image").contains("Successfully built image") - .contains("Pushing image '" + imageName + ":latest" + "'") - .contains("Pushed image '" + imageName + ":latest" + "'"); - ImageReference imageReference = ImageReference.of(imageName); - DockerApi.ImageApi imageApi = new DockerApi().image(); - Image pulledImage = imageApi.pull(imageReference, UpdateListener.none()); - assertThat(pulledImage).isNotNull(); - imageApi.remove(imageReference, false); - }); + mavenBuild.project("build-image-publish") + .goals("package") + .systemProperty("spring-boot.build-image.imageName", imageName) + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("Successfully built image") + .contains("Pushing image '" + imageName + ":latest" + "'") + .contains("Pushed image '" + imageName + ":latest" + "'"); + ImageReference imageReference = ImageReference.of(imageName); + DockerApi.ImageApi imageApi = new DockerApi().image(); + Image pulledImage = imageApi.pull(imageReference, UpdateListener.none()); + assertThat(pulledImage).isNotNull(); + imageApi.remove(imageReference, false); + }); } private static class RegistryContainer extends GenericContainer { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildImageTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildImageTests.java index f38272b00f..343e84114c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildImageTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildImageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,316 +49,368 @@ class BuildImageTests extends AbstractArchiveIntegrationTests { @TestTemplate void whenBuildImageIsInvokedWithoutRepackageTheArchiveIsRepackagedOnTheFly(MavenBuild mavenBuild) { - mavenBuild.project("build-image").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .prepare(this::writeLongNameResource).execute((project) -> { - File jar = new File(project, "target/build-image-0.0.1.BUILD-SNAPSHOT.jar"); - assertThat(jar).isFile(); - File original = new File(project, "target/build-image-0.0.1.BUILD-SNAPSHOT.jar.original"); - assertThat(original).doesNotExist(); - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("env: BP_JVM_VERSION=8.*") - .contains("---> Test Info buildpack done").contains("Successfully built image"); - removeImage("build-image", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .prepare(this::writeLongNameResource) + .execute((project) -> { + File jar = new File(project, "target/build-image-0.0.1.BUILD-SNAPSHOT.jar"); + assertThat(jar).isFile(); + File original = new File(project, "target/build-image-0.0.1.BUILD-SNAPSHOT.jar.original"); + assertThat(original).doesNotExist(); + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("env: BP_JVM_VERSION=8.*") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("build-image", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithClassifierWithoutRepackageTheArchiveIsRepackagedOnTheFly(MavenBuild mavenBuild) { - mavenBuild.project("build-image-classifier").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .prepare(this::writeLongNameResource).execute((project) -> { - File jar = new File(project, "target/build-image-classifier-0.0.1.BUILD-SNAPSHOT.jar"); - assertThat(jar).isFile(); - File classifier = new File(project, "target/build-image-classifier-0.0.1.BUILD-SNAPSHOT-test.jar"); - assertThat(classifier).doesNotExist(); - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-classifier:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("env: BP_JVM_VERSION=8.*") - .contains("---> Test Info buildpack done").contains("Successfully built image"); - removeImage("build-image-classifier", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-classifier") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .prepare(this::writeLongNameResource) + .execute((project) -> { + File jar = new File(project, "target/build-image-classifier-0.0.1.BUILD-SNAPSHOT.jar"); + assertThat(jar).isFile(); + File classifier = new File(project, "target/build-image-classifier-0.0.1.BUILD-SNAPSHOT-test.jar"); + assertThat(classifier).doesNotExist(); + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-classifier:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("env: BP_JVM_VERSION=8.*") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("build-image-classifier", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithClassifierSourceWithoutRepackageTheArchiveIsRepackagedOnTheFly( MavenBuild mavenBuild) { - mavenBuild.project("build-image-classifier-source").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .prepare(this::writeLongNameResource).execute((project) -> { - File jar = new File(project, "target/build-image-classifier-source-0.0.1.BUILD-SNAPSHOT-test.jar"); - assertThat(jar).isFile(); - File original = new File(project, - "target/build-image-classifier-source-0.0.1.BUILD-SNAPSHOT-test.jar.original"); - assertThat(original).doesNotExist(); - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-classifier-source:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("build-image-classifier-source", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-classifier-source") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .prepare(this::writeLongNameResource) + .execute((project) -> { + File jar = new File(project, "target/build-image-classifier-source-0.0.1.BUILD-SNAPSHOT-test.jar"); + assertThat(jar).isFile(); + File original = new File(project, + "target/build-image-classifier-source-0.0.1.BUILD-SNAPSHOT-test.jar.original"); + assertThat(original).doesNotExist(); + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-classifier-source:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("build-image-classifier-source", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithRepackageTheExistingArchiveIsUsed(MavenBuild mavenBuild) { - mavenBuild.project("build-image-with-repackage").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .prepare(this::writeLongNameResource).execute((project) -> { - File jar = new File(project, "target/build-image-with-repackage-0.0.1.BUILD-SNAPSHOT.jar"); - assertThat(jar).isFile(); - File original = new File(project, - "target/build-image-with-repackage-0.0.1.BUILD-SNAPSHOT.jar.original"); - assertThat(original).isFile(); - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-with-repackage:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("build-image-with-repackage", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-with-repackage") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .prepare(this::writeLongNameResource) + .execute((project) -> { + File jar = new File(project, "target/build-image-with-repackage-0.0.1.BUILD-SNAPSHOT.jar"); + assertThat(jar).isFile(); + File original = new File(project, + "target/build-image-with-repackage-0.0.1.BUILD-SNAPSHOT.jar.original"); + assertThat(original).isFile(); + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-with-repackage:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("build-image-with-repackage", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithClassifierAndRepackageTheExistingArchiveIsUsed(MavenBuild mavenBuild) { - mavenBuild.project("build-image-classifier-with-repackage").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .prepare(this::writeLongNameResource).execute((project) -> { - File jar = new File(project, - "target/build-image-classifier-with-repackage-0.0.1.BUILD-SNAPSHOT.jar"); - assertThat(jar).isFile(); - File original = new File(project, - "target/build-image-classifier-with-repackage-0.0.1.BUILD-SNAPSHOT-test.jar"); - assertThat(original).isFile(); - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-classifier-with-repackage:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("build-image-classifier-with-repackage", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-classifier-with-repackage") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .prepare(this::writeLongNameResource) + .execute((project) -> { + File jar = new File(project, "target/build-image-classifier-with-repackage-0.0.1.BUILD-SNAPSHOT.jar"); + assertThat(jar).isFile(); + File original = new File(project, + "target/build-image-classifier-with-repackage-0.0.1.BUILD-SNAPSHOT-test.jar"); + assertThat(original).isFile(); + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-classifier-with-repackage:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("build-image-classifier-with-repackage", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithClassifierSourceAndRepackageTheExistingArchiveIsUsed(MavenBuild mavenBuild) { - mavenBuild.project("build-image-classifier-source-with-repackage").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .prepare(this::writeLongNameResource).execute((project) -> { - File jar = new File(project, - "target/build-image-classifier-source-with-repackage-0.0.1.BUILD-SNAPSHOT-test.jar"); - assertThat(jar).isFile(); - File original = new File(project, - "target/build-image-classifier-source-with-repackage-0.0.1.BUILD-SNAPSHOT-test.jar.original"); - assertThat(original).isFile(); - assertThat(buildLog(project)).contains("Building image").contains( - "docker.io/library/build-image-classifier-source-with-repackage:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("build-image-classifier-source-with-repackage", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-classifier-source-with-repackage") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .prepare(this::writeLongNameResource) + .execute((project) -> { + File jar = new File(project, + "target/build-image-classifier-source-with-repackage-0.0.1.BUILD-SNAPSHOT-test.jar"); + assertThat(jar).isFile(); + File original = new File(project, + "target/build-image-classifier-source-with-repackage-0.0.1.BUILD-SNAPSHOT-test.jar.original"); + assertThat(original).isFile(); + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-classifier-source-with-repackage:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("build-image-classifier-source-with-repackage", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithWarPackaging(MavenBuild mavenBuild) { - mavenBuild.project("build-image-war-packaging").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .prepare(this::writeLongNameResource).execute((project) -> { - File war = new File(project, "target/build-image-war-packaging-0.0.1.BUILD-SNAPSHOT.war"); - assertThat(war).isFile(); - File original = new File(project, - "target/build-image-war-packaging-0.0.1.BUILD-SNAPSHOT.war.original"); - assertThat(original).doesNotExist(); - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-war-packaging:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("build-image-war-packaging", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-war-packaging") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .prepare(this::writeLongNameResource) + .execute((project) -> { + File war = new File(project, "target/build-image-war-packaging-0.0.1.BUILD-SNAPSHOT.war"); + assertThat(war).isFile(); + File original = new File(project, "target/build-image-war-packaging-0.0.1.BUILD-SNAPSHOT.war.original"); + assertThat(original).doesNotExist(); + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-war-packaging:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("build-image-war-packaging", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithCustomImageName(MavenBuild mavenBuild) { - mavenBuild.project("build-image-custom-name").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .systemProperty("spring-boot.build-image.imageName", "example.com/test/property-ignored:pom-preferred") - .execute((project) -> { - File jar = new File(project, "target/build-image-custom-name-0.0.1.BUILD-SNAPSHOT.jar"); - assertThat(jar).isFile(); - File original = new File(project, - "target/build-image-custom-name-0.0.1.BUILD-SNAPSHOT.jar.original"); - assertThat(original).doesNotExist(); - assertThat(buildLog(project)).contains("Building image") - .contains("example.com/test/build-image:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("example.com/test/build-image", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-custom-name") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .systemProperty("spring-boot.build-image.imageName", "example.com/test/property-ignored:pom-preferred") + .execute((project) -> { + File jar = new File(project, "target/build-image-custom-name-0.0.1.BUILD-SNAPSHOT.jar"); + assertThat(jar).isFile(); + File original = new File(project, "target/build-image-custom-name-0.0.1.BUILD-SNAPSHOT.jar.original"); + assertThat(original).doesNotExist(); + assertThat(buildLog(project)).contains("Building image") + .contains("example.com/test/build-image:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("example.com/test/build-image", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithCommandLineParameters(MavenBuild mavenBuild) { - mavenBuild.project("build-image").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .systemProperty("spring-boot.build-image.imageName", "example.com/test/cmd-property-name:v1") - .systemProperty("spring-boot.build-image.builder", - "projects.registry.vmware.com/springboot/spring-boot-cnb-builder:0.0.1") - .systemProperty("spring-boot.build-image.runImage", - "projects.registry.vmware.com/springboot/run:tiny-cnb") - .execute((project) -> { - assertThat(buildLog(project)).contains("Building image") - .contains("example.com/test/cmd-property-name:v1") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("example.com/test/cmd-property-name", "v1"); - }); + mavenBuild.project("build-image") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .systemProperty("spring-boot.build-image.imageName", "example.com/test/cmd-property-name:v1") + .systemProperty("spring-boot.build-image.builder", + "projects.registry.vmware.com/springboot/spring-boot-cnb-builder:0.0.1") + .systemProperty("spring-boot.build-image.runImage", "projects.registry.vmware.com/springboot/run:tiny-cnb") + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("example.com/test/cmd-property-name:v1") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("example.com/test/cmd-property-name", "v1"); + }); } @TestTemplate void whenBuildImageIsInvokedWithCustomBuilderImageAndRunImage(MavenBuild mavenBuild) { - mavenBuild.project("build-image-custom-builder").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT").execute((project) -> { - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-v2-builder:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("docker.io/library/build-image-v2-builder", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-custom-builder") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-v2-builder:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("docker.io/library/build-image-v2-builder", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithEmptyEnvEntry(MavenBuild mavenBuild) { - mavenBuild.project("build-image-empty-env-entry").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .prepare(this::writeLongNameResource).execute((project) -> { - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-empty-env-entry:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("build-image-empty-env-entry", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-empty-env-entry") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .prepare(this::writeLongNameResource) + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-empty-env-entry:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("build-image-empty-env-entry", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithZipPackaging(MavenBuild mavenBuild) { - mavenBuild.project("build-image-zip-packaging").goals("package").prepare(this::writeLongNameResource) - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT").execute((project) -> { - File jar = new File(project, "target/build-image-zip-packaging-0.0.1.BUILD-SNAPSHOT.jar"); - assertThat(jar).isFile(); - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-zip-packaging:0.0.1.BUILD-SNAPSHOT") - .contains("Main-Class: org.springframework.boot.loader.PropertiesLauncher") - .contains("Successfully built image"); - removeImage("build-image-zip-packaging", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-zip-packaging") + .goals("package") + .prepare(this::writeLongNameResource) + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .execute((project) -> { + File jar = new File(project, "target/build-image-zip-packaging-0.0.1.BUILD-SNAPSHOT.jar"); + assertThat(jar).isFile(); + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-zip-packaging:0.0.1.BUILD-SNAPSHOT") + .contains("Main-Class: org.springframework.boot.loader.PropertiesLauncher") + .contains("Successfully built image"); + removeImage("build-image-zip-packaging", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithBuildpacks(MavenBuild mavenBuild) { - mavenBuild.project("build-image-custom-buildpacks").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT").execute((project) -> { - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-custom-buildpacks:0.0.1.BUILD-SNAPSHOT") - .contains("Successfully built image"); - removeImage("build-image-custom-buildpacks", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-custom-buildpacks") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-custom-buildpacks:0.0.1.BUILD-SNAPSHOT") + .contains("Successfully built image"); + removeImage("build-image-custom-buildpacks", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithBinding(MavenBuild mavenBuild) { - mavenBuild.project("build-image-bindings").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT").execute((project) -> { - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-bindings:0.0.1.BUILD-SNAPSHOT") - .contains("binding: ca-certificates/type=ca-certificates") - .contains("binding: ca-certificates/test.crt=---certificate one---") - .contains("Successfully built image"); - removeImage("build-image-bindings", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-bindings") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-bindings:0.0.1.BUILD-SNAPSHOT") + .contains("binding: ca-certificates/type=ca-certificates") + .contains("binding: ca-certificates/test.crt=---certificate one---") + .contains("Successfully built image"); + removeImage("build-image-bindings", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithNetworkModeNone(MavenBuild mavenBuild) { - mavenBuild.project("build-image-network").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT").execute((project) -> { - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-network:0.0.1.BUILD-SNAPSHOT") - .contains("Network status: curl failed").contains("Successfully built image"); - removeImage("build-image-network", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-network") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-network:0.0.1.BUILD-SNAPSHOT") + .contains("Network status: curl failed") + .contains("Successfully built image"); + removeImage("build-image-network", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedOnMultiModuleProjectWithPackageGoal(MavenBuild mavenBuild) { - mavenBuild.project("build-image-multi-module").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT").execute((project) -> { - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-multi-module-app:0.0.1.BUILD-SNAPSHOT") - .contains("Successfully built image"); - removeImage("build-image-multi-module-app", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-multi-module") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-multi-module-app:0.0.1.BUILD-SNAPSHOT") + .contains("Successfully built image"); + removeImage("build-image-multi-module-app", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithTags(MavenBuild mavenBuild) { - mavenBuild.project("build-image-tags").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT").execute((project) -> { - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-tags:0.0.1.BUILD-SNAPSHOT") - .contains("Successfully built image").contains("docker.io/library/build-image-tags:latest") - .contains("Successfully created image tag"); - removeImage("build-image-tags", "0.0.1.BUILD-SNAPSHOT"); - removeImage("build-image-tags", "latest"); - }); + mavenBuild.project("build-image-tags") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-tags:0.0.1.BUILD-SNAPSHOT") + .contains("Successfully built image") + .contains("docker.io/library/build-image-tags:latest") + .contains("Successfully created image tag"); + removeImage("build-image-tags", "0.0.1.BUILD-SNAPSHOT"); + removeImage("build-image-tags", "latest"); + }); } @TestTemplate void whenBuildImageIsInvokedWithVolumeCaches(MavenBuild mavenBuild) { String testBuildId = randomString(); - mavenBuild.project("build-image-caches").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .systemProperty("test-build-id", testBuildId).execute((project) -> { - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-caches:0.0.1.BUILD-SNAPSHOT") - .contains("Successfully built image"); - removeImage("build-image-caches", "0.0.1.BUILD-SNAPSHOT"); - deleteVolumes("cache-" + testBuildId + ".build", "cache-" + testBuildId + ".launch"); - }); + mavenBuild.project("build-image-caches") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .systemProperty("test-build-id", testBuildId) + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-caches:0.0.1.BUILD-SNAPSHOT") + .contains("Successfully built image"); + removeImage("build-image-caches", "0.0.1.BUILD-SNAPSHOT"); + deleteVolumes("cache-" + testBuildId + ".build", "cache-" + testBuildId + ".launch"); + }); } @TestTemplate void failsWhenBuildImageIsInvokedOnMultiModuleProjectWithBuildImageGoal(MavenBuild mavenBuild) { - mavenBuild.project("build-image-multi-module").goals("spring-boot:build-image") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT").executeAndFail( - (project) -> assertThat(buildLog(project)).contains("Error packaging archive for image")); + mavenBuild.project("build-image-multi-module") + .goals("spring-boot:build-image") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .executeAndFail((project) -> assertThat(buildLog(project)).contains("Error packaging archive for image")); } @TestTemplate void failsWhenBuilderFails(MavenBuild mavenBuild) { - mavenBuild.project("build-image-builder-error").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .executeAndFail((project) -> assertThat(buildLog(project)).contains("Building image") - .contains("---> Test Info buildpack building").contains("Forced builder failure") - .containsPattern("Builder lifecycle '.*' failed with status code")); + mavenBuild.project("build-image-builder-error") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .executeAndFail((project) -> assertThat(buildLog(project)).contains("Building image") + .contains("---> Test Info buildpack building") + .contains("Forced builder failure") + .containsPattern("Builder lifecycle '.*' failed with status code")); } @TestTemplate void failsWithBuildpackNotInBuilder(MavenBuild mavenBuild) { - mavenBuild.project("build-image-bad-buildpack").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .executeAndFail((project) -> assertThat(buildLog(project)) - .contains("'urn:cnb:builder:example/does-not-exist:0.0.1' not found in builder")); + mavenBuild.project("build-image-bad-buildpack") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .executeAndFail((project) -> assertThat(buildLog(project)) + .contains("'urn:cnb:builder:example/does-not-exist:0.0.1' not found in builder")); } @TestTemplate void failsWhenFinalNameIsMisconfigured(MavenBuild mavenBuild) { - mavenBuild.project("build-image-final-name").goals("package") - .executeAndFail((project) -> assertThat(buildLog(project)).contains("final-name.jar.original") - .contains("is required for building an image")); + mavenBuild.project("build-image-final-name") + .goals("package") + .executeAndFail((project) -> assertThat(buildLog(project)).contains("final-name.jar.original") + .contains("is required for building an image")); } @TestTemplate void failsWhenCachesAreConfiguredTwice(MavenBuild mavenBuild) { - mavenBuild.project("build-image-caches-multiple").goals("package") - .executeAndFail((project) -> assertThat(buildLog(project)) - .contains("Each image building cache can be configured only once")); + mavenBuild.project("build-image-caches-multiple") + .goals("package") + .executeAndFail((project) -> assertThat(buildLog(project)) + .contains("Each image building cache can be configured only once")); } private void writeLongNameResource(File project) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildInfoIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildInfoIntegrationTests.java index 3c648a0d98..5f90ba231b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildInfoIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildInfoIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,67 +42,86 @@ class BuildInfoIntegrationTests { @TestTemplate void buildInfoPropertiesAreGenerated(MavenBuild mavenBuild) { - mavenBuild.project("build-info").execute(buildInfo((buildInfo) -> assertThat(buildInfo) - .hasBuildGroup("org.springframework.boot.maven.it").hasBuildArtifact("build-info") - .hasBuildName("Generate build info").hasBuildVersion("0.0.1.BUILD-SNAPSHOT").containsBuildTime())); + mavenBuild.project("build-info") + .execute(buildInfo((buildInfo) -> assertThat(buildInfo).hasBuildGroup("org.springframework.boot.maven.it") + .hasBuildArtifact("build-info") + .hasBuildName("Generate build info") + .hasBuildVersion("0.0.1.BUILD-SNAPSHOT") + .containsBuildTime())); } @TestTemplate void generatedBuildInfoIncludesAdditionalProperties(MavenBuild mavenBuild) { - mavenBuild.project("build-info-additional-properties").execute(buildInfo((buildInfo) -> assertThat(buildInfo) - .hasBuildGroup("org.springframework.boot.maven.it").hasBuildArtifact("build-info-additional-properties") - .hasBuildName("Generate build info with additional properties").hasBuildVersion("0.0.1.BUILD-SNAPSHOT") - .containsBuildTime().containsEntry("build.foo", "bar").containsEntry("build.encoding", "UTF-8") + mavenBuild.project("build-info-additional-properties") + .execute(buildInfo((buildInfo) -> assertThat(buildInfo).hasBuildGroup("org.springframework.boot.maven.it") + .hasBuildArtifact("build-info-additional-properties") + .hasBuildName("Generate build info with additional properties") + .hasBuildVersion("0.0.1.BUILD-SNAPSHOT") + .containsBuildTime() + .containsEntry("build.foo", "bar") + .containsEntry("build.encoding", "UTF-8") .containsEntry("build.java.source", "1.8"))); } @TestTemplate void generatedBuildInfoUsesCustomBuildTime(MavenBuild mavenBuild) { - mavenBuild.project("build-info-custom-build-time").execute(buildInfo((buildInfo) -> assertThat(buildInfo) - .hasBuildGroup("org.springframework.boot.maven.it").hasBuildArtifact("build-info-custom-build-time") - .hasBuildName("Generate build info with custom build time").hasBuildVersion("0.0.1.BUILD-SNAPSHOT") + mavenBuild.project("build-info-custom-build-time") + .execute(buildInfo((buildInfo) -> assertThat(buildInfo).hasBuildGroup("org.springframework.boot.maven.it") + .hasBuildArtifact("build-info-custom-build-time") + .hasBuildName("Generate build info with custom build time") + .hasBuildVersion("0.0.1.BUILD-SNAPSHOT") .hasBuildTime("2019-07-08T08:00:00Z"))); } @TestTemplate void generatedBuildInfoReproducible(MavenBuild mavenBuild) { mavenBuild.project("build-info-reproducible") - .execute(buildInfo((buildInfo) -> assertThat(buildInfo) - .hasBuildGroup("org.springframework.boot.maven.it").hasBuildArtifact("build-reproducible") - .hasBuildName("Generate build info with build time from project.build.outputTimestamp") - .hasBuildVersion("0.0.1.BUILD-SNAPSHOT").hasBuildTime("2021-04-21T11:22:33Z"))); + .execute(buildInfo((buildInfo) -> assertThat(buildInfo).hasBuildGroup("org.springframework.boot.maven.it") + .hasBuildArtifact("build-reproducible") + .hasBuildName("Generate build info with build time from project.build.outputTimestamp") + .hasBuildVersion("0.0.1.BUILD-SNAPSHOT") + .hasBuildTime("2021-04-21T11:22:33Z"))); } @TestTemplate void buildInfoPropertiesAreGeneratedToCustomOutputLocation(MavenBuild mavenBuild) { mavenBuild.project("build-info-custom-file") - .execute(buildInfo("target/build.info", - (buildInfo) -> assertThat(buildInfo).hasBuildGroup("org.springframework.boot.maven.it") - .hasBuildArtifact("build-info-custom-file").hasBuildName("Generate custom build info") - .hasBuildVersion("0.0.1.BUILD-SNAPSHOT").containsBuildTime())); + .execute(buildInfo("target/build.info", + (buildInfo) -> assertThat(buildInfo).hasBuildGroup("org.springframework.boot.maven.it") + .hasBuildArtifact("build-info-custom-file") + .hasBuildName("Generate custom build info") + .hasBuildVersion("0.0.1.BUILD-SNAPSHOT") + .containsBuildTime())); } @TestTemplate void whenBuildTimeIsDisabledIfDoesNotAppearInGeneratedBuildInfo(MavenBuild mavenBuild) { - mavenBuild.project("build-info-disable-build-time").execute(buildInfo((buildInfo) -> assertThat(buildInfo) - .hasBuildGroup("org.springframework.boot.maven.it").hasBuildArtifact("build-info-disable-build-time") - .hasBuildName("Generate build info with disabled build time").hasBuildVersion("0.0.1.BUILD-SNAPSHOT") + mavenBuild.project("build-info-disable-build-time") + .execute(buildInfo((buildInfo) -> assertThat(buildInfo).hasBuildGroup("org.springframework.boot.maven.it") + .hasBuildArtifact("build-info-disable-build-time") + .hasBuildName("Generate build info with disabled build time") + .hasBuildVersion("0.0.1.BUILD-SNAPSHOT") .doesNotContainBuildTime())); } @TestTemplate void whenBuildTimeIsExcludedIfDoesNotAppearInGeneratedBuildInfo(MavenBuild mavenBuild) { - mavenBuild.project("build-info-exclude-build-time").execute(buildInfo((buildInfo) -> assertThat(buildInfo) - .hasBuildGroup("org.springframework.boot.maven.it").hasBuildArtifact("build-info-exclude-build-time") - .hasBuildName("Generate build info with excluded build time").hasBuildVersion("0.0.1.BUILD-SNAPSHOT") + mavenBuild.project("build-info-exclude-build-time") + .execute(buildInfo((buildInfo) -> assertThat(buildInfo).hasBuildGroup("org.springframework.boot.maven.it") + .hasBuildArtifact("build-info-exclude-build-time") + .hasBuildName("Generate build info with excluded build time") + .hasBuildVersion("0.0.1.BUILD-SNAPSHOT") .doesNotContainBuildTime())); } @TestTemplate void whenBuildPropertiesAreExcludedTheyDoNotAppearInGeneratedBuildInfo(MavenBuild mavenBuild) { - mavenBuild.project("build-info-exclude-build-properties").execute( - buildInfo((buildInfo) -> assertThat(buildInfo).doesNotContainBuildGroup().doesNotContainBuildArtifact() - .doesNotContainBuildName().doesNotContainBuildVersion().containsBuildTime())); + mavenBuild.project("build-info-exclude-build-properties") + .execute(buildInfo((buildInfo) -> assertThat(buildInfo).doesNotContainBuildGroup() + .doesNotContainBuildArtifact() + .doesNotContainBuildName() + .doesNotContainBuildVersion() + .containsBuildTime())); } private ProjectCallback buildInfo(Consumer> buildInfo) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/JarIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/JarIntegrationTests.java index 80b1da2e0e..3f959aa35e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/JarIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/JarIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,14 +60,16 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { manifest.hasMainClass("org.springframework.boot.loader.JarLauncher"); manifest.hasStartClass("some.random.Main"); manifest.hasAttribute("Not-Used", "Foo"); - }).hasEntryWithNameStartingWith("BOOT-INF/lib/spring-context") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-core") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-jcl") - .hasEntryWithNameStartingWith("BOOT-INF/lib/jakarta.servlet-api-4") - .hasEntryWithName("BOOT-INF/classes/org/test/SampleApplication.class") - .hasEntryWithName("org/springframework/boot/loader/JarLauncher.class"); + }) + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-context") + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-core") + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-jcl") + .hasEntryWithNameStartingWith("BOOT-INF/lib/jakarta.servlet-api-4") + .hasEntryWithName("BOOT-INF/classes/org/test/SampleApplication.class") + .hasEntryWithName("org/springframework/boot/loader/JarLauncher.class"); assertThat(buildLog(project)).contains("Replacing main artifact with repackaged archive") - .contains("Installing " + repackaged + " to").doesNotContain("Installing " + original + " to"); + .contains("Installing " + repackaged + " to") + .doesNotContain("Installing " + original + " to"); }); } @@ -79,7 +81,8 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { File main = new File(project, "target/jar-attach-disabled-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(main).isFile(); assertThat(buildLog(project)).contains("Updating main artifact " + main + " to " + original) - .contains("Installing " + original + " to").doesNotContain("Installing " + main + " to"); + .contains("Installing " + original + " to") + .doesNotContain("Installing " + main + " to"); }); } @@ -88,15 +91,16 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { MavenBuild mavenBuild) { mavenBuild.project("jar-classifier-main").goals("install").execute((project) -> { assertThat(new File(project, "target/jar-classifier-main-0.0.1.BUILD-SNAPSHOT.jar.original")) - .doesNotExist(); + .doesNotExist(); File main = new File(project, "target/jar-classifier-main-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(main).isFile(); File repackaged = new File(project, "target/jar-classifier-main-0.0.1.BUILD-SNAPSHOT-test.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/"); assertThat(buildLog(project)) - .contains("Attaching repackaged archive " + repackaged + " with classifier test") - .doesNotContain("Creating repackaged archive " + repackaged + " with classifier test") - .contains("Installing " + main + " to").contains("Installing " + repackaged + " to"); + .contains("Attaching repackaged archive " + repackaged + " with classifier test") + .doesNotContain("Creating repackaged archive " + repackaged + " with classifier test") + .contains("Installing " + main + " to") + .contains("Installing " + repackaged + " to"); }); } @@ -109,7 +113,8 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { File repackaged = new File(project, "target/jar-classifier-source-0.0.1.BUILD-SNAPSHOT-test.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/"); assertThat(buildLog(project)).contains("Replacing artifact with classifier test with repackaged archive") - .doesNotContain("Installing " + original + " to").contains("Installing " + repackaged + " to"); + .doesNotContain("Installing " + original + " to") + .contains("Installing " + repackaged + " to"); }); } @@ -123,9 +128,10 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { "target/jar-classifier-source-attach-disabled-0.0.1.BUILD-SNAPSHOT-test.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/"); assertThat(buildLog(project)) - .doesNotContain("Attaching repackaged archive " + repackaged + " with classifier test") - .contains("Updating artifact with classifier test " + repackaged + " to " + original) - .contains("Installing " + original + " to").doesNotContain("Installing " + repackaged + " to"); + .doesNotContain("Attaching repackaged archive " + repackaged + " with classifier test") + .contains("Updating artifact with classifier test " + repackaged + " to " + original) + .contains("Installing " + original + " to") + .doesNotContain("Installing " + repackaged + " to"); }); } @@ -162,10 +168,10 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-exclude-entry").goals("install").execute((project) -> { File repackaged = new File(project, "target/jar-exclude-entry-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-context") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-core") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-jcl") - .doesNotHaveEntryWithName("BOOT-INF/lib/servlet-api-2.5.jar"); + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-context") + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-core") + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-jcl") + .doesNotHaveEntryWithName("BOOT-INF/lib/servlet-api-2.5.jar"); }); } @@ -174,10 +180,10 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-exclude-group").goals("install").execute((project) -> { File repackaged = new File(project, "target/jar-exclude-group-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-context") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-core") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-jcl") - .doesNotHaveEntryWithName("BOOT-INF/lib/log4j-api-2.4.1.jar"); + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-context") + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-core") + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-jcl") + .doesNotHaveEntryWithName("BOOT-INF/lib/log4j-api-2.4.1.jar"); }); } @@ -187,7 +193,8 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { File repackaged = new File(project, "target/jar-executable-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/"); assertThat(launchScript(repackaged)).contains("Spring Boot Startup Script") - .contains("MyFullyExecutableJarName").contains("MyFullyExecutableJarDesc"); + .contains("MyFullyExecutableJarName") + .contains("MyFullyExecutableJarDesc"); }); } @@ -196,10 +203,9 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-lib-name-conflict").execute((project) -> { File repackaged = new File(project, "test-project/target/test-project-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/") - .hasEntryWithName( - "BOOT-INF/lib/org.springframework.boot.maven.it-acme-lib-0.0.1.BUILD-SNAPSHOT.jar") - .hasEntryWithName( - "BOOT-INF/lib/org.springframework.boot.maven.it.another-acme-lib-0.0.1.BUILD-SNAPSHOT.jar"); + .hasEntryWithName("BOOT-INF/lib/org.springframework.boot.maven.it-acme-lib-0.0.1.BUILD-SNAPSHOT.jar") + .hasEntryWithName( + "BOOT-INF/lib/org.springframework.boot.maven.it.another-acme-lib-0.0.1.BUILD-SNAPSHOT.jar"); }); } @@ -245,7 +251,7 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-test-scope").execute((project) -> { File main = new File(project, "target/jar-test-scope-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(main)).doesNotHaveEntryWithNameStartingWith("BOOT-INF/lib/log4j") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-"); + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-"); }); } @@ -259,14 +265,15 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { @TestTemplate void whenAProjectIsBuiltWithALayoutPropertyTheSpecifiedLayoutIsUsed(MavenBuild mavenBuild) { - mavenBuild.project("jar-with-layout-property").goals("package", "-Dspring-boot.repackage.layout=ZIP") - .execute((project) -> { - File main = new File(project, "target/jar-with-layout-property-0.0.1.BUILD-SNAPSHOT.jar"); - assertThat(jar(main)).manifest( - (manifest) -> manifest.hasMainClass("org.springframework.boot.loader.PropertiesLauncher") - .hasStartClass("org.test.SampleApplication")); - assertThat(buildLog(project)).contains("Layout: ZIP"); - }); + mavenBuild.project("jar-with-layout-property") + .goals("package", "-Dspring-boot.repackage.layout=ZIP") + .execute((project) -> { + File main = new File(project, "target/jar-with-layout-property-0.0.1.BUILD-SNAPSHOT.jar"); + assertThat(jar(main)) + .manifest((manifest) -> manifest.hasMainClass("org.springframework.boot.loader.PropertiesLauncher") + .hasStartClass("org.test.SampleApplication")); + assertThat(buildLog(project)).contains("Layout: ZIP"); + }); } @TestTemplate @@ -274,8 +281,8 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-with-zip-layout").execute((project) -> { File main = new File(project, "target/jar-with-zip-layout-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(main)) - .manifest((manifest) -> manifest.hasMainClass("org.springframework.boot.loader.PropertiesLauncher") - .hasStartClass("org.test.SampleApplication")); + .manifest((manifest) -> manifest.hasMainClass("org.springframework.boot.loader.PropertiesLauncher") + .hasStartClass("org.test.SampleApplication")); assertThat(buildLog(project)).contains("Layout: ZIP"); }); } @@ -285,7 +292,7 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-with-unpack").execute((project) -> { File main = new File(project, "target/jar-with-unpack-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(main)).hasUnpackEntryWithNameStartingWith("BOOT-INF/lib/spring-core-") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-context-"); + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-context-"); }); } @@ -293,9 +300,9 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { void whenJarIsRepackagedWithACustomLayoutTheJarUsesTheLayout(MavenBuild mavenBuild) { mavenBuild.project("jar-custom-layout").execute((project) -> { assertThat(jar(new File(project, "custom/target/custom-0.0.1.BUILD-SNAPSHOT.jar"))) - .hasEntryWithName("custom"); + .hasEntryWithName("custom"); assertThat(jar(new File(project, "default/target/default-0.0.1.BUILD-SNAPSHOT.jar"))) - .hasEntryWithName("sample"); + .hasEntryWithName("sample"); }); } @@ -304,9 +311,10 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-layered").execute((project) -> { File repackaged = new File(project, "jar/target/jar-layered-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/") - .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-release") - .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-snapshot").hasEntryWithNameStartingWith( - "BOOT-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getCoordinates().getArtifactId()); + .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-release") + .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-snapshot") + .hasEntryWithNameStartingWith( + "BOOT-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getCoordinates().getArtifactId()); try (JarFile jarFile = new JarFile(repackaged)) { Map> layerIndex = readLayerIndex(jarFile); assertThat(layerIndex.keySet()).containsExactly("dependencies", "spring-boot-loader", @@ -314,7 +322,7 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { assertThat(layerIndex.get("application")).contains("BOOT-INF/lib/jar-release-0.0.1.RELEASE.jar", "BOOT-INF/lib/jar-snapshot-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(layerIndex.get("dependencies")) - .anyMatch((dependency) -> dependency.startsWith("BOOT-INF/lib/log4j-api-2")); + .anyMatch((dependency) -> dependency.startsWith("BOOT-INF/lib/log4j-api-2")); } catch (IOException ex) { } @@ -326,10 +334,10 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-layered-disabled").execute((project) -> { File repackaged = new File(project, "jar/target/jar-layered-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/") - .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-release") - .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-snapshot") - .doesNotHaveEntryWithName("BOOT-INF/layers.idx") - .doesNotHaveEntryWithNameStartingWith("BOOT-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getName()); + .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-release") + .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-snapshot") + .doesNotHaveEntryWithName("BOOT-INF/layers.idx") + .doesNotHaveEntryWithNameStartingWith("BOOT-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getName()); }); } @@ -338,10 +346,10 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-layered-no-layer-tools").execute((project) -> { File repackaged = new File(project, "jar/target/jar-layered-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/") - .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-release") - .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-snapshot") - .hasEntryWithNameStartingWith("BOOT-INF/layers.idx") - .doesNotHaveEntryWithNameStartingWith("BOOT-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getName()); + .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-release") + .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-snapshot") + .hasEntryWithNameStartingWith("BOOT-INF/layers.idx") + .doesNotHaveEntryWithNameStartingWith("BOOT-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getName()); }); } @@ -350,17 +358,17 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-layered-custom").execute((project) -> { File repackaged = new File(project, "jar/target/jar-layered-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/") - .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-release") - .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-snapshot"); + .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-release") + .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-snapshot"); try (JarFile jarFile = new JarFile(repackaged)) { Map> layerIndex = readLayerIndex(jarFile); assertThat(layerIndex.keySet()).containsExactly("my-dependencies-name", "snapshot-dependencies", "configuration", "application"); assertThat(layerIndex.get("application")) - .contains("BOOT-INF/lib/jar-release-0.0.1.RELEASE.jar", - "BOOT-INF/lib/jar-snapshot-0.0.1.BUILD-SNAPSHOT.jar", - "BOOT-INF/lib/jar-classifier-0.0.1-bravo.jar") - .doesNotContain("BOOT-INF/lib/jar-classifier-0.0.1-alpha.jar"); + .contains("BOOT-INF/lib/jar-release-0.0.1.RELEASE.jar", + "BOOT-INF/lib/jar-snapshot-0.0.1.BUILD-SNAPSHOT.jar", + "BOOT-INF/lib/jar-classifier-0.0.1-bravo.jar") + .doesNotContain("BOOT-INF/lib/jar-classifier-0.0.1-alpha.jar"); } }); } @@ -369,8 +377,8 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { void repackagedJarContainsClasspathIndex(MavenBuild mavenBuild) { mavenBuild.project("jar").execute((project) -> { File repackaged = new File(project, "target/jar-0.0.1.BUILD-SNAPSHOT.jar"); - assertThat(jar(repackaged)).manifest( - (manifest) -> manifest.hasAttribute("Spring-Boot-Classpath-Index", "BOOT-INF/classpath.idx")); + assertThat(jar(repackaged)) + .manifest((manifest) -> manifest.hasAttribute("Spring-Boot-Classpath-Index", "BOOT-INF/classpath.idx")); assertThat(jar(repackaged)).hasEntryWithName("BOOT-INF/classpath.idx"); try (JarFile jarFile = new JarFile(repackaged)) { List index = readClasspathIndex(jarFile, "BOOT-INF/classpath.idx"); @@ -396,9 +404,9 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { assertThat(repackaged.lastModified()).isEqualTo(1584352800000L); try (JarFile jar = new JarFile(repackaged)) { List unreproducibleEntries = jar.stream() - .filter((entry) -> entry.getLastModifiedTime().toMillis() != 1584352800000L) - .map((entry) -> entry.getName() + ": " + entry.getLastModifiedTime()) - .collect(Collectors.toList()); + .filter((entry) -> entry.getLastModifiedTime().toMillis() != 1584352800000L) + .map((entry) -> entry.getName() + ": " + entry.getLastModifiedTime()) + .collect(Collectors.toList()); assertThat(unreproducibleEntries).isEmpty(); jarHash.set(FileUtils.sha1Hash(repackaged)); FileSystemUtils.deleteRecursively(project); @@ -418,8 +426,9 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { "BOOT-INF/lib/spring-beans", "BOOT-INF/lib/spring-boot-jarmode-layertools", "BOOT-INF/lib/spring-context", "BOOT-INF/lib/spring-core", "BOOT-INF/lib/spring-expression", "BOOT-INF/lib/spring-jcl"); - assertThat(jar(repackaged)).entryNamesInPath("BOOT-INF/lib/").zipSatisfy(sortedLibs, - (String jarLib, String expectedLib) -> assertThat(jarLib).startsWith(expectedLib)); + assertThat(jar(repackaged)).entryNamesInPath("BOOT-INF/lib/") + .zipSatisfy(sortedLibs, + (String jarLib, String expectedLib) -> assertThat(jarLib).startsWith(expectedLib)); }); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/MavenBuild.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/MavenBuild.java index ad081136eb..05b620bfb7 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/MavenBuild.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/MavenBuild.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -159,10 +159,8 @@ class MavenBuild { }); String settingsXml = new String(Files.readAllBytes(Paths.get("src", "intTest", "projects", "settings.xml")), StandardCharsets.UTF_8) - .replace("@localCentralUrl@", - new File("build/int-test-maven-repository").toURI().toURL().toString()) - .replace("@localRepositoryPath@", - new File("build/local-maven-repository").getAbsolutePath()); + .replace("@localCentralUrl@", new File("build/int-test-maven-repository").toURI().toURL().toString()) + .replace("@localRepositoryPath@", new File("build/local-maven-repository").getAbsolutePath()); Files.write(destination.resolve("settings.xml"), settingsXml.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE_NEW); request.setBaseDirectory(this.temp); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/RunIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/RunIntegrationTests.java index 823ce6bcbb..770e17413f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/RunIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/RunIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,112 +47,130 @@ class RunIntegrationTests { @TestTemplate @Deprecated void whenForkingIsDisabledAndDevToolsIsPresentDevToolsIsDisabled(MavenBuild mavenBuild) { - mavenBuild.project("run-devtools").goals("spring-boot:run").execute((project) -> assertThat(buildLog(project)) - .contains("I haz been run").contains("Fork mode disabled, devtools will be disabled")); + mavenBuild.project("run-devtools") + .goals("spring-boot:run") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run") + .contains("Fork mode disabled, devtools will be disabled")); } @TestTemplate @Deprecated void whenForkingIsDisabledJvmArgumentsAndWorkingDirectoryAreIgnored(MavenBuild mavenBuild) { - mavenBuild.project("run-disable-fork").goals("spring-boot:run") - .execute((project) -> assertThat(buildLog(project)).contains("I haz been run").contains( - "Fork mode disabled, ignoring JVM argument(s) [-Dproperty1=value1 -Dproperty2 -Dfoo=bar]") - .contains("Fork mode disabled, ignoring working directory configuration")); + mavenBuild.project("run-disable-fork") + .goals("spring-boot:run") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run") + .contains("Fork mode disabled, ignoring JVM argument(s) [-Dproperty1=value1 -Dproperty2 -Dfoo=bar]") + .contains("Fork mode disabled, ignoring working directory configuration")); } @TestTemplate void whenEnvironmentVariablesAreConfiguredTheyAreAvailableToTheApplication(MavenBuild mavenBuild) { - mavenBuild.project("run-envargs").goals("spring-boot:run") - .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); + mavenBuild.project("run-envargs") + .goals("spring-boot:run") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); } @TestTemplate void whenExclusionsAreConfiguredExcludedDependenciesDoNotAppearOnTheClasspath(MavenBuild mavenBuild) { - mavenBuild.project("run-exclude").goals("spring-boot:run") - .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); + mavenBuild.project("run-exclude") + .goals("spring-boot:run") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); } @TestTemplate void whenSystemPropertiesAndJvmArgumentsAreConfiguredTheyAreAvailableToTheApplication(MavenBuild mavenBuild) { - mavenBuild.project("run-jvm-system-props").goals("spring-boot:run") - .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); + mavenBuild.project("run-jvm-system-props") + .goals("spring-boot:run") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); } @TestTemplate void whenJvmArgumentsAreConfiguredTheyAreAvailableToTheApplication(MavenBuild mavenBuild) { - mavenBuild.project("run-jvmargs").goals("spring-boot:run") - .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); + mavenBuild.project("run-jvmargs") + .goals("spring-boot:run") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); } @TestTemplate void whenCommandLineSpecifiesJvmArgumentsTheyAreAvailableToTheApplication(MavenBuild mavenBuild) { - mavenBuild.project("run-jvmargs-commandline").goals("spring-boot:run") - .systemProperty("spring-boot.run.jvmArguments", "-Dfoo=value-from-cmd") - .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); + mavenBuild.project("run-jvmargs-commandline") + .goals("spring-boot:run") + .systemProperty("spring-boot.run.jvmArguments", "-Dfoo=value-from-cmd") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); } @TestTemplate void whenPomAndCommandLineSpecifyJvmArgumentsThenPomOverrides(MavenBuild mavenBuild) { - mavenBuild.project("run-jvmargs").goals("spring-boot:run") - .systemProperty("spring-boot.run.jvmArguments", "-Dfoo=value-from-cmd") - .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); + mavenBuild.project("run-jvmargs") + .goals("spring-boot:run") + .systemProperty("spring-boot.run.jvmArguments", "-Dfoo=value-from-cmd") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); } @TestTemplate void whenProfilesAreConfiguredTheyArePassedToTheApplication(MavenBuild mavenBuild) { - mavenBuild.project("run-profiles").goals("spring-boot:run", "-X").execute( - (project) -> assertThat(buildLog(project)).contains("I haz been run with profile(s) 'foo,bar'")); + mavenBuild.project("run-profiles") + .goals("spring-boot:run", "-X") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run with profile(s) 'foo,bar'")); } @TestTemplate @Deprecated void whenProfilesAreConfiguredAndForkingIsDisabledTheyArePassedToTheApplication(MavenBuild mavenBuild) { - mavenBuild.project("run-profiles-fork-disabled").goals("spring-boot:run").execute( - (project) -> assertThat(buildLog(project)).contains("I haz been run with profile(s) 'foo,bar'")); + mavenBuild.project("run-profiles-fork-disabled") + .goals("spring-boot:run") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run with profile(s) 'foo,bar'")); } @TestTemplate void whenUseTestClasspathIsEnabledTheApplicationHasTestDependenciesOnItsClasspath(MavenBuild mavenBuild) { - mavenBuild.project("run-use-test-classpath").goals("spring-boot:run") - .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); + mavenBuild.project("run-use-test-classpath") + .goals("spring-boot:run") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); } @TestTemplate void whenAWorkingDirectoryIsConfiguredTheApplicationIsRunFromThatDirectory(MavenBuild mavenBuild) { - mavenBuild.project("run-working-directory").goals("spring-boot:run").execute( - (project) -> assertThat(buildLog(project)).containsPattern("I haz been run from.*src.main.java")); + mavenBuild.project("run-working-directory") + .goals("spring-boot:run") + .execute((project) -> assertThat(buildLog(project)).containsPattern("I haz been run from.*src.main.java")); } @TestTemplate @DisabledOnOs(OS.WINDOWS) void whenAToolchainIsConfiguredItIsUsedToRunTheApplication(MavenBuild mavenBuild) { - mavenBuild.project("run-toolchains").goals("verify", "-t", "toolchains.xml") - .execute((project) -> assertThat(buildLog(project)).contains("The Maven Toolchains is awesome!")); + mavenBuild.project("run-toolchains") + .goals("verify", "-t", "toolchains.xml") + .execute((project) -> assertThat(buildLog(project)).contains("The Maven Toolchains is awesome!")); } @TestTemplate void whenPomSpecifiesRunArgumentsContainingCommasTheyArePassedToTheApplicationCorrectly(MavenBuild mavenBuild) { - mavenBuild.project("run-arguments").goals("spring-boot:run").execute((project) -> assertThat(buildLog(project)) + mavenBuild.project("run-arguments") + .goals("spring-boot:run") + .execute((project) -> assertThat(buildLog(project)) .contains("I haz been run with profile(s) 'foo,bar' and endpoint(s) 'prometheus,info'")); } @TestTemplate void whenCommandLineSpecifiesRunArgumentsContainingCommasTheyArePassedToTheApplicationCorrectly( MavenBuild mavenBuild) { - mavenBuild.project("run-arguments-commandline").goals("spring-boot:run").systemProperty( - "spring-boot.run.arguments", - "--management.endpoints.web.exposure.include=prometheus,info,health,metrics --spring.profiles.active=foo,bar") - .execute((project) -> assertThat(buildLog(project)).contains( - "I haz been run with profile(s) 'foo,bar' and endpoint(s) 'prometheus,info,health,metrics'")); + mavenBuild.project("run-arguments-commandline") + .goals("spring-boot:run") + .systemProperty("spring-boot.run.arguments", + "--management.endpoints.web.exposure.include=prometheus,info,health,metrics --spring.profiles.active=foo,bar") + .execute((project) -> assertThat(buildLog(project)) + .contains("I haz been run with profile(s) 'foo,bar' and endpoint(s) 'prometheus,info,health,metrics'")); } @TestTemplate void whenPomAndCommandLineSpecifyRunArgumentsThenPomOverrides(MavenBuild mavenBuild) { - mavenBuild.project("run-arguments").goals("spring-boot:run") - .systemProperty("spring-boot.run.arguments", - "--management.endpoints.web.exposure.include=one,two,three --spring.profiles.active=test") - .execute((project) -> assertThat(buildLog(project)) - .contains("I haz been run with profile(s) 'foo,bar' and endpoint(s) 'prometheus,info'")); + mavenBuild.project("run-arguments") + .goals("spring-boot:run") + .systemProperty("spring-boot.run.arguments", + "--management.endpoints.web.exposure.include=one,two,three --spring.profiles.active=test") + .execute((project) -> assertThat(buildLog(project)) + .contains("I haz been run with profile(s) 'foo,bar' and endpoint(s) 'prometheus,info'")); } private String buildLog(File project) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/StartStopIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/StartStopIntegrationTests.java index 3ef33cdbe0..bafef633c1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/StartStopIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/StartStopIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,20 +35,26 @@ class StartStopIntegrationTests { @TestTemplate @Deprecated void startStopWithForkDisabledWaitsForApplicationToBeReadyAndThenRequestsShutdown(MavenBuild mavenBuild) { - mavenBuild.project("start-stop-fork-disabled").goals("verify").execute( - (project) -> assertThat(buildLog(project)).contains("isReady: true").contains("Shutdown requested")); + mavenBuild.project("start-stop-fork-disabled") + .goals("verify") + .execute((project) -> assertThat(buildLog(project)).contains("isReady: true") + .contains("Shutdown requested")); } @TestTemplate void startStopWaitsForApplicationToBeReadyAndThenRequestsShutdown(MavenBuild mavenBuild) { - mavenBuild.project("start-stop").goals("verify").execute( - (project) -> assertThat(buildLog(project)).contains("isReady: true").contains("Shutdown requested")); + mavenBuild.project("start-stop") + .goals("verify") + .execute((project) -> assertThat(buildLog(project)).contains("isReady: true") + .contains("Shutdown requested")); } @TestTemplate void whenSkipIsTrueStartAndStopAreSkipped(MavenBuild mavenBuild) { - mavenBuild.project("start-stop-skip").goals("verify").execute((project) -> assertThat(buildLog(project)) - .doesNotContain("Ooops, I haz been run").doesNotContain("Stopping application")); + mavenBuild.project("start-stop-skip") + .goals("verify") + .execute((project) -> assertThat(buildLog(project)).doesNotContain("Ooops, I haz been run") + .doesNotContain("Stopping application")); } private String buildLog(File project) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/WarIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/WarIntegrationTests.java index 7e3247e3e8..c3d2af0f83 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/WarIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/WarIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,33 +52,34 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { @TestTemplate void warRepackaging(MavenBuild mavenBuild) { mavenBuild.project("war") - .execute((project) -> assertThat(jar(new File(project, "target/war-0.0.1.BUILD-SNAPSHOT.war"))) - .hasEntryWithNameStartingWith("WEB-INF/lib/spring-context") - .hasEntryWithNameStartingWith("WEB-INF/lib/spring-core") - .hasEntryWithNameStartingWith("WEB-INF/lib/spring-jcl") - .hasEntryWithNameStartingWith("WEB-INF/lib-provided/jakarta.servlet-api-4") - .hasEntryWithName("org/springframework/boot/loader/WarLauncher.class") - .hasEntryWithName("WEB-INF/classes/org/test/SampleApplication.class") - .hasEntryWithName("index.html") - .manifest((manifest) -> manifest.hasMainClass("org.springframework.boot.loader.WarLauncher") - .hasStartClass("org.test.SampleApplication").hasAttribute("Not-Used", "Foo"))); + .execute((project) -> assertThat(jar(new File(project, "target/war-0.0.1.BUILD-SNAPSHOT.war"))) + .hasEntryWithNameStartingWith("WEB-INF/lib/spring-context") + .hasEntryWithNameStartingWith("WEB-INF/lib/spring-core") + .hasEntryWithNameStartingWith("WEB-INF/lib/spring-jcl") + .hasEntryWithNameStartingWith("WEB-INF/lib-provided/jakarta.servlet-api-4") + .hasEntryWithName("org/springframework/boot/loader/WarLauncher.class") + .hasEntryWithName("WEB-INF/classes/org/test/SampleApplication.class") + .hasEntryWithName("index.html") + .manifest((manifest) -> manifest.hasMainClass("org.springframework.boot.loader.WarLauncher") + .hasStartClass("org.test.SampleApplication") + .hasAttribute("Not-Used", "Foo"))); } @TestTemplate void jarDependencyWithCustomFinalNameBuiltInSameReactorIsPackagedUsingArtifactIdAndVersion(MavenBuild mavenBuild) { mavenBuild.project("war-reactor") - .execute(((project) -> assertThat(jar(new File(project, "war/target/war-0.0.1.BUILD-SNAPSHOT.war"))) - .hasEntryWithName("WEB-INF/lib/jar-0.0.1.BUILD-SNAPSHOT.jar") - .doesNotHaveEntryWithName("WEB-INF/lib/jar.jar"))); + .execute(((project) -> assertThat(jar(new File(project, "war/target/war-0.0.1.BUILD-SNAPSHOT.war"))) + .hasEntryWithName("WEB-INF/lib/jar-0.0.1.BUILD-SNAPSHOT.jar") + .doesNotHaveEntryWithName("WEB-INF/lib/jar.jar"))); } @TestTemplate void whenRequiresUnpackConfigurationIsProvidedItIsReflectedInTheRepackagedWar(MavenBuild mavenBuild) { - mavenBuild.project("war-with-unpack").execute( - (project) -> assertThat(jar(new File(project, "target/war-with-unpack-0.0.1.BUILD-SNAPSHOT.war"))) - .hasUnpackEntryWithNameStartingWith("WEB-INF/lib/spring-core-") - .hasEntryWithNameStartingWith("WEB-INF/lib/spring-context-") - .hasEntryWithNameStartingWith("WEB-INF/lib/spring-jcl-")); + mavenBuild.project("war-with-unpack") + .execute((project) -> assertThat(jar(new File(project, "target/war-with-unpack-0.0.1.BUILD-SNAPSHOT.war"))) + .hasUnpackEntryWithNameStartingWith("WEB-INF/lib/spring-core-") + .hasEntryWithNameStartingWith("WEB-INF/lib/spring-context-") + .hasEntryWithNameStartingWith("WEB-INF/lib/spring-jcl-")); } @TestTemplate @@ -98,9 +99,9 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { assertThat(repackaged.lastModified()).isEqualTo(1584352800000L); try (JarFile jar = new JarFile(repackaged)) { List unreproducibleEntries = jar.stream() - .filter((entry) -> entry.getLastModifiedTime().toMillis() != 1584352800000L) - .map((entry) -> entry.getName() + ": " + entry.getLastModifiedTime()) - .collect(Collectors.toList()); + .filter((entry) -> entry.getLastModifiedTime().toMillis() != 1584352800000L) + .map((entry) -> entry.getName() + ": " + entry.getLastModifiedTime()) + .collect(Collectors.toList()); assertThat(unreproducibleEntries).isEmpty(); warHash.set(FileUtils.sha1Hash(repackaged)); FileSystemUtils.deleteRecursively(project); @@ -124,8 +125,9 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { // these libraries are contributed by Spring Boot repackaging, and // sorted separately "WEB-INF/lib/spring-boot-jarmode-layertools"); - assertThat(jar(repackaged)).entryNamesInPath("WEB-INF/lib/").zipSatisfy(sortedLibs, - (String jarLib, String expectedLib) -> assertThat(jarLib).startsWith(expectedLib)); + assertThat(jar(repackaged)).entryNamesInPath("WEB-INF/lib/") + .zipSatisfy(sortedLibs, + (String jarLib, String expectedLib) -> assertThat(jarLib).startsWith(expectedLib)); }); } @@ -143,9 +145,10 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("war-layered").execute((project) -> { File repackaged = new File(project, "war/target/war-layered-0.0.1.BUILD-SNAPSHOT.war"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("WEB-INF/classes/") - .hasEntryWithNameStartingWith("WEB-INF/lib/jar-release") - .hasEntryWithNameStartingWith("WEB-INF/lib/jar-snapshot").hasEntryWithNameStartingWith( - "WEB-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getCoordinates().getArtifactId()); + .hasEntryWithNameStartingWith("WEB-INF/lib/jar-release") + .hasEntryWithNameStartingWith("WEB-INF/lib/jar-snapshot") + .hasEntryWithNameStartingWith( + "WEB-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getCoordinates().getArtifactId()); try (JarFile jarFile = new JarFile(repackaged)) { Map> layerIndex = readLayerIndex(jarFile); assertThat(layerIndex.keySet()).containsExactly("dependencies", "spring-boot-loader", @@ -156,9 +159,9 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { assertThat(layerIndex.get("application")).contains("WEB-INF/lib/jar-release-0.0.1.RELEASE.jar", "WEB-INF/lib/jar-snapshot-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(dependenciesAndSnapshotDependencies) - .anyMatch((dependency) -> dependency.startsWith("WEB-INF/lib/spring-context")); + .anyMatch((dependency) -> dependency.startsWith("WEB-INF/lib/spring-context")); assertThat(layerIndex.get("dependencies")) - .anyMatch((dependency) -> dependency.startsWith("WEB-INF/lib-provided/")); + .anyMatch((dependency) -> dependency.startsWith("WEB-INF/lib-provided/")); } catch (IOException ex) { } @@ -170,10 +173,10 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("war-layered-disabled").execute((project) -> { File repackaged = new File(project, "war/target/war-layered-0.0.1.BUILD-SNAPSHOT.war"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("WEB-INF/classes/") - .hasEntryWithNameStartingWith("WEB-INF/lib/jar-release") - .hasEntryWithNameStartingWith("WEB-INF/lib/jar-snapshot") - .doesNotHaveEntryWithName("WEB-INF/layers.idx") - .doesNotHaveEntryWithNameStartingWith("WEB-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getName()); + .hasEntryWithNameStartingWith("WEB-INF/lib/jar-release") + .hasEntryWithNameStartingWith("WEB-INF/lib/jar-snapshot") + .doesNotHaveEntryWithName("WEB-INF/layers.idx") + .doesNotHaveEntryWithNameStartingWith("WEB-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getName()); }); } @@ -182,10 +185,10 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("war-layered-no-layer-tools").execute((project) -> { File repackaged = new File(project, "war/target/war-layered-0.0.1.BUILD-SNAPSHOT.war"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("WEB-INF/classes/") - .hasEntryWithNameStartingWith("WEB-INF/lib/jar-release") - .hasEntryWithNameStartingWith("WEB-INF/lib/jar-snapshot") - .hasEntryWithNameStartingWith("WEB-INF/layers.idx") - .doesNotHaveEntryWithNameStartingWith("WEB-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getName()); + .hasEntryWithNameStartingWith("WEB-INF/lib/jar-release") + .hasEntryWithNameStartingWith("WEB-INF/lib/jar-snapshot") + .hasEntryWithNameStartingWith("WEB-INF/layers.idx") + .doesNotHaveEntryWithNameStartingWith("WEB-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getName()); }); } @@ -194,17 +197,17 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("war-layered-custom").execute((project) -> { File repackaged = new File(project, "war/target/war-layered-0.0.1.BUILD-SNAPSHOT.war"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("WEB-INF/classes/") - .hasEntryWithNameStartingWith("WEB-INF/lib/jar-release") - .hasEntryWithNameStartingWith("WEB-INF/lib/jar-snapshot"); + .hasEntryWithNameStartingWith("WEB-INF/lib/jar-release") + .hasEntryWithNameStartingWith("WEB-INF/lib/jar-snapshot"); try (JarFile jarFile = new JarFile(repackaged)) { Map> layerIndex = readLayerIndex(jarFile); assertThat(layerIndex.keySet()).containsExactly("my-dependencies-name", "snapshot-dependencies", "configuration", "application"); assertThat(layerIndex.get("application")) - .contains("WEB-INF/lib/jar-release-0.0.1.RELEASE.jar", - "WEB-INF/lib/jar-snapshot-0.0.1.BUILD-SNAPSHOT.jar", - "WEB-INF/lib/jar-classifier-0.0.1-bravo.jar") - .doesNotContain("WEB-INF/lib/jar-classifier-0.0.1-alpha.jar"); + .contains("WEB-INF/lib/jar-release-0.0.1.RELEASE.jar", + "WEB-INF/lib/jar-snapshot-0.0.1.BUILD-SNAPSHOT.jar", + "WEB-INF/lib/jar-classifier-0.0.1-bravo.jar") + .doesNotContain("WEB-INF/lib/jar-classifier-0.0.1-alpha.jar"); } }); } @@ -213,13 +216,13 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { void repackagedWarContainsClasspathIndex(MavenBuild mavenBuild) { mavenBuild.project("war").execute((project) -> { File repackaged = new File(project, "target/war-0.0.1.BUILD-SNAPSHOT.war"); - assertThat(jar(repackaged)).manifest( - (manifest) -> manifest.hasAttribute("Spring-Boot-Classpath-Index", "WEB-INF/classpath.idx")); + assertThat(jar(repackaged)) + .manifest((manifest) -> manifest.hasAttribute("Spring-Boot-Classpath-Index", "WEB-INF/classpath.idx")); assertThat(jar(repackaged)).hasEntryWithName("WEB-INF/classpath.idx"); try (JarFile jarFile = new JarFile(repackaged)) { List index = readClasspathIndex(jarFile, "WEB-INF/classpath.idx"); - assertThat(index).allMatch( - (entry) -> entry.startsWith("WEB-INF/lib/") || entry.startsWith("WEB-INF/lib-provided/")); + assertThat(index) + .allMatch((entry) -> entry.startsWith("WEB-INF/lib/") || entry.startsWith("WEB-INF/lib-provided/")); } }); } @@ -229,7 +232,7 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("war-exclude-entry").execute((project) -> { File war = new File(project, "target/war-exclude-entry-0.0.1.BUILD-SNAPSHOT.war"); assertThat(jar(war)).hasEntryWithNameStartingWith("WEB-INF/lib/spring-context") - .doesNotHaveEntryWithNameStartingWith("WEB-INF/lib/spring-core"); + .doesNotHaveEntryWithNameStartingWith("WEB-INF/lib/spring-core"); }); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java index d6d608c6a9..6ae1e8cd1f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -363,9 +363,10 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { protected RunArguments resolveJvmArguments() { StringBuilder stringBuilder = new StringBuilder(); if (this.systemPropertyVariables != null) { - stringBuilder.append(this.systemPropertyVariables.entrySet().stream() - .map((e) -> SystemPropertyFormatter.format(e.getKey(), e.getValue())) - .collect(Collectors.joining(" "))); + stringBuilder.append(this.systemPropertyVariables.entrySet() + .stream() + .map((e) -> SystemPropertyFormatter.format(e.getKey(), e.getValue())) + .collect(Collectors.joining(" "))); } if (this.jvmArguments != null) { stringBuilder.append(" ").append(this.jvmArguments); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/Image.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/Image.java index 634989c357..7560e355ee 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/Image.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/Image.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -208,7 +208,7 @@ public class Image { } if (!CollectionUtils.isEmpty(this.buildpacks)) { request = request - .withBuildpacks(this.buildpacks.stream().map(BuildpackReference::of).collect(Collectors.toList())); + .withBuildpacks(this.buildpacks.stream().map(BuildpackReference::of).collect(Collectors.toList())); } if (!CollectionUtils.isEmpty(this.bindings)) { request = request.withBindings(this.bindings.stream().map(Binding::of).collect(Collectors.toList())); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/JarTypeFilter.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/JarTypeFilter.java index a05f3f8ada..05f29c1bee 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/JarTypeFilter.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/JarTypeFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ import org.apache.maven.artifact.Artifact; class JarTypeFilter extends DependencyFilter { private static final Set EXCLUDED_JAR_TYPES = Collections - .unmodifiableSet(new HashSet<>(Arrays.asList("annotation-processor", "dependencies-starter"))); + .unmodifiableSet(new HashSet<>(Arrays.asList("annotation-processor", "dependencies-starter"))); JarTypeFilter() { super(Collections.emptyList()); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/LoggingMainClassTimeoutWarningListener.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/LoggingMainClassTimeoutWarningListener.java index 7e2b8d4756..822bff323a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/LoggingMainClassTimeoutWarningListener.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/LoggingMainClassTimeoutWarningListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,9 @@ class LoggingMainClassTimeoutWarningListener implements MainClassTimeoutWarningL @Override public void handleTimeoutWarning(long duration, String mainMethod) { - this.log.get().warn("Searching for the main-class is taking some time, " - + "consider using the mainClass configuration parameter"); + this.log.get() + .warn("Searching for the main-class is taking some time, " + + "consider using the mainClass configuration parameter"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java index 1e4eceed03..e7516a1026 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -143,11 +143,11 @@ class ArtifactsLibrariesTests { given(snapshotArtifact.getArtifactHandler()).willReturn(this.artifactHandler); this.artifacts = Collections.singleton(snapshotArtifact); new ArtifactsLibraries(this.artifacts, Collections.emptyList(), null, mock(Log.class)) - .doWithLibraries((library) -> { - assertThat(library.isIncluded()).isTrue(); - assertThat(library.isLocal()).isFalse(); - assertThat(library.getCoordinates().getVersion()).isEqualTo("1.0-SNAPSHOT"); - }); + .doWithLibraries((library) -> { + assertThat(library.isIncluded()).isTrue(); + assertThat(library.isLocal()).isFalse(); + assertThat(library.getCoordinates().getVersion()).isEqualTo("1.0-SNAPSHOT"); + }); } @Test @@ -162,7 +162,7 @@ class ArtifactsLibrariesTests { given(mavenProject.getArtifact()).willReturn(artifact); this.artifacts = Collections.singleton(artifact); new ArtifactsLibraries(this.artifacts, Collections.singleton(mavenProject), null, mock(Log.class)) - .doWithLibraries((library) -> assertThat(library.isLocal()).isTrue()); + .doWithLibraries((library) -> assertThat(library.isLocal()).isTrue()); } @Test @@ -179,7 +179,7 @@ class ArtifactsLibrariesTests { given(mavenProject.getAttachedArtifacts()).willReturn(Collections.singletonList(attachedArtifact)); this.artifacts = Collections.singleton(attachedArtifact); new ArtifactsLibraries(this.artifacts, Collections.singleton(mavenProject), null, mock(Log.class)) - .doWithLibraries((library) -> assertThat(library.isLocal()).isTrue()); + .doWithLibraries((library) -> assertThat(library.isLocal()).isTrue()); } @Test @@ -194,7 +194,8 @@ class ArtifactsLibrariesTests { given(mavenProject.getArtifact()).willReturn(artifact); this.artifacts = Collections.singleton(artifact); new ArtifactsLibraries(this.artifacts, Collections.emptySet(), Collections.singleton(mavenProject), null, - mock(Log.class)).doWithLibraries((library) -> assertThat(library.isIncluded()).isFalse()); + mock(Log.class)) + .doWithLibraries((library) -> assertThat(library.isIncluded()).isFalse()); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/CustomLayersProviderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/CustomLayersProviderTests.java index e9b9f2bc49..f7383776c9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/CustomLayersProviderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/CustomLayersProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,8 +52,9 @@ class CustomLayersProviderTests { @Test void getLayerResolverWhenDocumentValid() throws Exception { CustomLayers layers = this.customLayersProvider.getLayers(getDocument("layers.xml")); - assertThat(layers).extracting("name").containsExactly("my-deps", "my-dependencies-name", - "snapshot-dependencies", "my-resources", "configuration", "application"); + assertThat(layers).extracting("name") + .containsExactly("my-deps", "my-dependencies-name", "snapshot-dependencies", "my-resources", + "configuration", "application"); Library snapshot = mockLibrary("test-SNAPSHOT.jar", "org.foo", "1.0.0-SNAPSHOT"); Library groupId = mockLibrary("my-library", "com.acme", null); Library otherDependency = mockLibrary("other-library", "org.foo", null); @@ -81,7 +82,7 @@ class CustomLayersProviderTests { Library library = mockLibrary("my-library", "com.acme", null); assertThat(layers.getLayer(library).toString()).isEqualTo("my-deps"); assertThatIllegalStateException().isThrownBy(() -> layers.getLayer("application.yml")) - .withMessageContaining("match any layer"); + .withMessageContaining("match any layer"); } @Test @@ -90,7 +91,7 @@ class CustomLayersProviderTests { Library library = mockLibrary("my-library", "com.acme", null); assertThat(layers.getLayer("application.yml").toString()).isEqualTo("my-layer"); assertThatIllegalStateException().isThrownBy(() -> layers.getLayer(library)) - .withMessageContaining("match any layer"); + .withMessageContaining("match any layer"); } private Document getDocument(String resourceName) throws Exception { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DockerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DockerTests.java index 879af4bea4..5fc6a63cbc 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DockerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DockerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,10 @@ class DockerTests { assertThat(dockerConfiguration.getHost()).isNull(); assertThat(dockerConfiguration.getBuilderRegistryAuthentication()).isNull(); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"\"").contains("\"password\" : \"\"").contains("\"email\" : \"\"") - .contains("\"serveraddress\" : \"\""); + .contains("\"username\" : \"\"") + .contains("\"password\" : \"\"") + .contains("\"email\" : \"\"") + .contains("\"serveraddress\" : \"\""); } @Test @@ -58,8 +60,10 @@ class DockerTests { assertThat(dockerConfiguration.isBindHostToBuilder()).isFalse(); assertThat(docker.asDockerConfiguration().getBuilderRegistryAuthentication()).isNull(); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"\"").contains("\"password\" : \"\"").contains("\"email\" : \"\"") - .contains("\"serveraddress\" : \"\""); + .contains("\"username\" : \"\"") + .contains("\"password\" : \"\"") + .contains("\"email\" : \"\"") + .contains("\"serveraddress\" : \"\""); } @Test @@ -77,8 +81,10 @@ class DockerTests { assertThat(dockerConfiguration.isBindHostToBuilder()).isTrue(); assertThat(docker.asDockerConfiguration().getBuilderRegistryAuthentication()).isNull(); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"\"").contains("\"password\" : \"\"").contains("\"email\" : \"\"") - .contains("\"serveraddress\" : \"\""); + .contains("\"username\" : \"\"") + .contains("\"password\" : \"\"") + .contains("\"email\" : \"\"") + .contains("\"serveraddress\" : \"\""); } @Test @@ -90,13 +96,15 @@ class DockerTests { new Docker.DockerRegistry("user2", "secret2", "https://docker2.example.com", "docker2@example.com")); DockerConfiguration dockerConfiguration = docker.asDockerConfiguration(); assertThat(decoded(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"user1\"").contains("\"password\" : \"secret1\"") - .contains("\"email\" : \"docker1@example.com\"") - .contains("\"serveraddress\" : \"https://docker1.example.com\""); + .contains("\"username\" : \"user1\"") + .contains("\"password\" : \"secret1\"") + .contains("\"email\" : \"docker1@example.com\"") + .contains("\"serveraddress\" : \"https://docker1.example.com\""); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"user2\"").contains("\"password\" : \"secret2\"") - .contains("\"email\" : \"docker2@example.com\"") - .contains("\"serveraddress\" : \"https://docker2.example.com\""); + .contains("\"username\" : \"user2\"") + .contains("\"password\" : \"secret2\"") + .contains("\"email\" : \"docker2@example.com\"") + .contains("\"serveraddress\" : \"https://docker2.example.com\""); } @Test @@ -105,7 +113,7 @@ class DockerTests { docker.setBuilderRegistry( new Docker.DockerRegistry("user", null, "https://docker.example.com", "docker@example.com")); assertThatIllegalArgumentException().isThrownBy(docker::asDockerConfiguration) - .withMessageContaining("Invalid Docker builder registry configuration"); + .withMessageContaining("Invalid Docker builder registry configuration"); } @Test @@ -114,7 +122,7 @@ class DockerTests { docker.setPublishRegistry( new Docker.DockerRegistry("user", null, "https://docker.example.com", "docker@example.com")); assertThatIllegalArgumentException().isThrownBy(docker::asDockerConfiguration) - .withMessageContaining("Invalid Docker publish registry configuration"); + .withMessageContaining("Invalid Docker publish registry configuration"); } @Test @@ -124,9 +132,9 @@ class DockerTests { docker.setPublishRegistry(new Docker.DockerRegistry("token2")); DockerConfiguration dockerConfiguration = docker.asDockerConfiguration(); assertThat(decoded(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())) - .contains("\"identitytoken\" : \"token1\""); + .contains("\"identitytoken\" : \"token1\""); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"identitytoken\" : \"token2\""); + .contains("\"identitytoken\" : \"token2\""); } @Test @@ -138,7 +146,7 @@ class DockerTests { Docker docker = new Docker(); docker.setBuilderRegistry(dockerRegistry); assertThatIllegalArgumentException().isThrownBy(docker::asDockerConfiguration) - .withMessageContaining("Invalid Docker builder registry configuration"); + .withMessageContaining("Invalid Docker builder registry configuration"); } String decoded(String value) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/JavaCompilerPluginConfigurationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/JavaCompilerPluginConfigurationTests.java index 0bcd407642..c8057f6511 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/JavaCompilerPluginConfigurationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/JavaCompilerPluginConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -88,7 +88,7 @@ class JavaCompilerPluginConfigurationTests { private Xpp3Dom buildConfigurationDom(String... properties) throws IOException, XmlPullParserException { return Xpp3DomBuilder - .build(new StringReader("" + Arrays.toString(properties) + "")); + .build(new StringReader("" + Arrays.toString(properties) + "")); } } 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 234bdfdd7b..29e7d1607b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -96,7 +96,8 @@ final class ModifiedClassPathClassLoader extends URLClassLoader { candidates.add(testMethod); candidates.addAll(getAnnotatedElements(arguments.toArray())); List annotatedElements = candidates.stream() - .filter(ModifiedClassPathClassLoader::hasAnnotation).collect(Collectors.toList()); + .filter(ModifiedClassPathClassLoader::hasAnnotation) + .collect(Collectors.toList()); if (annotatedElements.isEmpty()) { return null; } @@ -126,8 +127,8 @@ final class ModifiedClassPathClassLoader extends URLClassLoader { private static ModifiedClassPathClassLoader compute(ClassLoader classLoader, List annotatedClasses) { List annotations = annotatedClasses.stream() - .map((source) -> MergedAnnotations.from(source, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY)) - .collect(Collectors.toList()); + .map((source) -> MergedAnnotations.from(source, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY)) + .collect(Collectors.toList()); return new ModifiedClassPathClassLoader(processUrls(extractUrls(classLoader), annotations), classLoader.getParent(), classLoader); } @@ -150,7 +151,7 @@ final class ModifiedClassPathClassLoader extends URLClassLoader { return Stream.of(((URLClassLoader) classLoader).getURLs()); } return Stream.of(ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) - .map(ModifiedClassPathClassLoader::toURL); + .map(ModifiedClassPathClassLoader::toURL); } private static URL toURL(String entry) { @@ -237,7 +238,8 @@ final class ModifiedClassPathClassLoader extends URLClassLoader { DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); LocalRepository localRepository = new LocalRepository(System.getProperty("user.home") + "/.m2/repository"); RemoteRepository remoteRepository = new RemoteRepository.Builder("central", "default", - "https://repo.maven.apache.org/maven2").build(); + "https://repo.maven.apache.org/maven2") + .build(); session.setLocalRepositoryManager(repositorySystem.newLocalRepositoryManager(session, localRepository)); for (int i = 0; i < MAX_RESOLUTION_ATTEMPTS; i++) { CollectRequest collectRequest = new CollectRequest(null, Arrays.asList(remoteRepository)); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtension.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtension.java index ddac249c72..bb4912acbd 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtension.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -109,7 +109,8 @@ class ModifiedClassPathExtension implements InvocationInterceptor { private void runTest(String testId) throws Throwable { LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() - .selectors(DiscoverySelectors.selectUniqueId(testId)).build(); + .selectors(DiscoverySelectors.selectUniqueId(testId)) + .build(); Launcher launcher = LauncherFactory.create(); TestPlan testPlan = launcher.discover(request); SummaryGeneratingListener listener = new SummaryGeneratingListener(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/junit/DisabledOnOsCondition.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/junit/DisabledOnOsCondition.java index 3968c0ba6a..855bcde7a0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/junit/DisabledOnOsCondition.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/junit/DisabledOnOsCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ class DisabledOnOsCondition implements ExecutionCondition { } } return ConditionEvaluationResult - .enabled(String.format("Enabled on OS = %s, architecture = %s", os, architecture)); + .enabled(String.format("Enabled on OS = %s, architecture = %s", os, architecture)); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java index 7c8d35bd03..a2957848a5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,9 +87,10 @@ public abstract class MockServletWebServer { return null; }).when(this.servletContext).setInitParameter(anyString(), anyString()); given(this.servletContext.getInitParameterNames()) - .willReturn(Collections.enumeration(initParameters.keySet())); - lenient().doAnswer((invocation) -> initParameters.get(invocation.getArgument(0))).when(this.servletContext) - .getInitParameter(anyString()); + .willReturn(Collections.enumeration(initParameters.keySet())); + lenient().doAnswer((invocation) -> initParameters.get(invocation.getArgument(0))) + .when(this.servletContext) + .getInitParameter(anyString()); given(this.servletContext.getAttributeNames()).willReturn(Collections.emptyEnumeration()); for (Initializer initializer : this.initializers) { initializer.onStartup(this.servletContext); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtensionOverridesParameterizedTests.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtensionOverridesParameterizedTests.java index 76000a7182..74dea7879c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtensionOverridesParameterizedTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtensionOverridesParameterizedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ class ModifiedClassPathExtensionOverridesParameterizedTests { @MethodSource("parameter") void classesAreLoadedFromParameter(Class type) { assertThat(ApplicationContext.class.getProtectionDomain().getCodeSource().getLocation().toString()) - .endsWith("spring-context-4.1.0.RELEASE.jar"); + .endsWith("spring-context-4.1.0.RELEASE.jar"); } static Class[] parameter() { @@ -51,7 +51,7 @@ class ModifiedClassPathExtensionOverridesParameterizedTests { @MethodSource("arrayParameter") void classesAreLoadedFromParameterInArray(Object[] types) { assertThat(ApplicationContext.class.getProtectionDomain().getCodeSource().getLocation().toString()) - .endsWith("spring-context-4.1.0.RELEASE.jar"); + .endsWith("spring-context-4.1.0.RELEASE.jar"); } static Stream arrayParameter() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtensionOverridesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtensionOverridesTests.java index b114a1b837..f188f7c965 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtensionOverridesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtensionOverridesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,13 +34,13 @@ class ModifiedClassPathExtensionOverridesTests { @Test void classesAreLoadedFromOverride() { assertThat(ApplicationContext.class.getProtectionDomain().getCodeSource().getLocation().toString()) - .endsWith("spring-context-4.1.0.RELEASE.jar"); + .endsWith("spring-context-4.1.0.RELEASE.jar"); } @Test void classesAreLoadedFromTransitiveDependencyOfOverride() { assertThat(StringUtils.class.getProtectionDomain().getCodeSource().getLocation().toString()) - .endsWith("spring-core-4.1.0.RELEASE.jar"); + .endsWith("spring-core-4.1.0.RELEASE.jar"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServerTests.java index 1c78f11701..ef8d8ee384 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ class MockServletWebServerTests { void servletContextHasSessionCookieConfigConfigured() { MockServletWebServer server = TestMockServletWebServer.create(); assertThat(server.getServletContext().getSessionCookieConfig()).isNotNull() - .isInstanceOf(MockSessionCookieConfig.class); + .isInstanceOf(MockSessionCookieConfig.class); } private static final class TestMockServletWebServer extends MockServletWebServer { 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 0bdf15d6e0..8870475c22 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -275,7 +275,7 @@ class BeanDefinitionLoader { // Attempt to find a class in this package ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(getClass().getClassLoader()); Resource[] resources = resolver - .getResources(ClassUtils.convertClassNameToResourcePath(source.toString()) + "/*.class"); + .getResources(ClassUtils.convertClassNameToResourcePath(source.toString()) + "/*.class"); for (Resource resource : resources) { String className = StringUtils.stripFilenameExtension(resource.getFilename()); load(Class.forName(source.toString() + "." + className)); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BootstrapRegistry.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BootstrapRegistry.java index ae29cbc3ed..b1f247db61 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BootstrapRegistry.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BootstrapRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -164,6 +164,7 @@ public interface BootstrapRegistry { /** * The scope of an instance. + * * @since 2.4.2 */ enum Scope { 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 ef549ee2b8..29760b79d8 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 @@ -355,7 +355,7 @@ public class SpringApplication { private Class deduceEnvironmentClass() { Class environmentType = this.applicationContextFactory - .getEnvironmentType(this.webApplicationType); + .getEnvironmentType(this.webApplicationType); if (environmentType == null && this.applicationContextFactory != ApplicationContextFactory.DEFAULT) { environmentType = ApplicationContextFactory.DEFAULT.getEnvironmentType(this.webApplicationType); } @@ -387,7 +387,7 @@ public class SpringApplication { ((AbstractAutowireCapableBeanFactory) beanFactory).setAllowCircularReferences(this.allowCircularReferences); if (beanFactory instanceof DefaultListableBeanFactory) { ((DefaultListableBeanFactory) beanFactory) - .setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding); + .setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding); } } if (this.lazyInitialization) { @@ -499,8 +499,8 @@ public class SpringApplication { if (sources.contains(name)) { PropertySource source = sources.get(name); CompositePropertySource composite = new CompositePropertySource(name); - composite.addPropertySource( - new SimpleCommandLinePropertySource("springApplicationCommandLineArgs", args)); + composite + .addPropertySource(new SimpleCommandLinePropertySource("springApplicationCommandLineArgs", args)); composite.addPropertySource(source); sources.replace(name, composite); } @@ -573,8 +573,8 @@ public class SpringApplication { */ protected void postProcessApplicationContext(ConfigurableApplicationContext context) { if (this.beanNameGenerator != null) { - context.getBeanFactory().registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, - this.beanNameGenerator); + context.getBeanFactory() + .registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, this.beanNameGenerator); } if (this.resourceLoader != null) { if (context instanceof GenericApplicationContext) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationShutdownHook.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationShutdownHook.java index 23073df514..f1b2ae6dc8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationShutdownHook.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationShutdownHook.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -213,7 +213,7 @@ class SpringApplicationShutdownHook implements Runnable { ApplicationContext applicationContext = event.getApplicationContext(); SpringApplicationShutdownHook.this.contexts.remove(applicationContext); SpringApplicationShutdownHook.this.closedContexts - .add((ConfigurableApplicationContext) applicationContext); + .add((ConfigurableApplicationContext) applicationContext); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/SpringApplicationBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/SpringApplicationBuilder.java index f570df3bb6..49924307e8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/SpringApplicationBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/SpringApplicationBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -208,8 +208,9 @@ public class SpringApplicationBuilder { child.sources(sources); // Copy environment stuff from parent to child - child.properties(this.defaultProperties).environment(this.environment) - .additionalProfiles(this.additionalProfiles); + child.properties(this.defaultProperties) + .environment(this.environment) + .additionalProfiles(this.additionalProfiles); child.parent = this; // It's not possible if embedded web server are enabled to support web contexts as @@ -235,7 +236,8 @@ public class SpringApplicationBuilder { public SpringApplicationBuilder parent(Class... sources) { if (this.parent == null) { this.parent = new SpringApplicationBuilder(sources).web(WebApplicationType.NONE) - .properties(this.defaultProperties).environment(this.environment); + .properties(this.defaultProperties) + .environment(this.environment); } else { this.parent.sources(sources); 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..a0f6b5bd12 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -108,7 +108,7 @@ public enum CloudPlatform { private boolean isAutoDetected(ConfigurableEnvironment environment) { PropertySource environmentPropertySource = environment.getPropertySources() - .get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); + .get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); if (environmentPropertySource != null) { if (environmentPropertySource.containsProperty(KUBERNETES_SERVICE_HOST) && environmentPropertySource.containsProperty(KUBERNETES_SERVICE_PORT)) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializer.java index f9999ad4d6..d97f09f548 100755 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -162,7 +162,7 @@ public class ConfigurationWarningsApplicationContextInitializer private void addComponentScanningPackages(Set packages, AnnotationMetadata metadata) { AnnotationAttributes attributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(ComponentScan.class.getName(), true)); + .fromMap(metadata.getAnnotationAttributes(ComponentScan.class.getName(), true)); if (attributes != null) { addPackages(packages, attributes.getStringArray("value")); addPackages(packages, attributes.getStringArray("basePackages")); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/annotation/Configurations.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/annotation/Configurations.java index 59056d2e8e..7109ae763e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/annotation/Configurations.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/annotation/Configurations.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +57,7 @@ import org.springframework.util.ClassUtils; public abstract class Configurations { private static final Comparator COMPARATOR = OrderComparator.INSTANCE - .thenComparing((other) -> other.getClass().getName()); + .thenComparing((other) -> other.getClass().getName()); private final Set> classes; @@ -119,8 +119,9 @@ public abstract class Configurations { List ordered = new ArrayList<>(configurations); ordered.sort(COMPARATOR); List collated = collate(ordered); - LinkedHashSet> classes = collated.stream().flatMap(Configurations::streamClasses) - .collect(Collectors.toCollection(LinkedHashSet::new)); + LinkedHashSet> classes = collated.stream() + .flatMap(Configurations::streamClasses) + .collect(Collectors.toCollection(LinkedHashSet::new)); return ClassUtils.toClassArray(classes); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/AnsiOutputApplicationListener.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/AnsiOutputApplicationListener.java index 931f021bbe..f17855aaad 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/AnsiOutputApplicationListener.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/AnsiOutputApplicationListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,9 @@ public class AnsiOutputApplicationListener @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); - Binder.get(environment).bind("spring.output.ansi.enabled", AnsiOutput.Enabled.class) - .ifBound(AnsiOutput::setEnabled); + Binder.get(environment) + .bind("spring.output.ansi.enabled", AnsiOutput.Enabled.class) + .ifBound(AnsiOutput::setEnabled); AnsiOutput.setConsoleAvailable(environment.getProperty("spring.output.ansi.console-available", Boolean.class)); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironment.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironment.java index d1f8b6737c..7a1a138483 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironment.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironment.java @@ -95,7 +95,7 @@ class ConfigDataEnvironment { private static final ConfigDataLocation[] EMPTY_LOCATIONS = new ConfigDataLocation[0]; private static final Bindable CONFIG_DATA_LOCATION_ARRAY = Bindable - .of(ConfigDataLocation[].class); + .of(ConfigDataLocation[].class); private static final Bindable> STRING_LIST = Bindable.listOf(String.class); @@ -142,7 +142,7 @@ class ConfigDataEnvironment { this.logFactory = logFactory; this.logger = logFactory.getLog(getClass()); this.notFoundAction = binder.bind(ON_NOT_FOUND_PROPERTY, ConfigDataNotFoundAction.class) - .orElse(ConfigDataNotFoundAction.FAIL); + .orElse(ConfigDataNotFoundAction.FAIL); this.bootstrapContext = bootstrapContext; this.environment = environment; this.resolvers = createConfigDataLocationResolvers(logFactory, bootstrapContext, binder, resourceLoader); @@ -315,8 +315,9 @@ class ConfigDataEnvironment { private void registerBootstrapBinder(ConfigDataEnvironmentContributors contributors, ConfigDataActivationContext activationContext, BinderOption... binderOptions) { - this.bootstrapContext.register(Binder.class, InstanceSupplier - .from(() -> contributors.getBinder(activationContext, binderOptions)).withScope(Scope.PROTOTYPE)); + this.bootstrapContext.register(Binder.class, + InstanceSupplier.from(() -> contributors.getBinder(activationContext, binderOptions)) + .withScope(Scope.PROTOTYPE)); } private void applyToEnvironment(ConfigDataEnvironmentContributors contributors, @@ -342,12 +343,12 @@ class ConfigDataEnvironment { PropertySource propertySource = contributor.getPropertySource(); if (contributor.getKind() == ConfigDataEnvironmentContributor.Kind.BOUND_IMPORT && propertySource != null) { if (!contributor.isActive(activationContext)) { - this.logger.trace( - LogMessage.format("Skipping inactive property source '%s'", propertySource.getName())); + this.logger + .trace(LogMessage.format("Skipping inactive property source '%s'", propertySource.getName())); } else { this.logger - .trace(LogMessage.format("Adding imported property source '%s'", propertySource.getName())); + .trace(LogMessage.format("Adding imported property source '%s'", propertySource.getName())); propertySources.addLast(propertySource); this.environmentUpdateListener.onPropertySourceAdded(propertySource, contributor.getLocation(), contributor.getResource()); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributor.java index c417505730..14c5e65b77 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ import org.springframework.util.CollectionUtils; class ConfigDataEnvironmentContributor implements Iterable { private static final ConfigData.Options EMPTY_LOCATION_OPTIONS = ConfigData.Options - .of(ConfigData.Option.IGNORE_IMPORTS); + .of(ConfigData.Option.IGNORE_IMPORTS); private final ConfigDataLocation location; @@ -305,8 +305,9 @@ class ConfigDataEnvironmentContributor implements Iterable child.hasConfigDataOption(ConfigData.Option.PROFILE_SPECIFIC))) { + if (contributor.getChildren(importPhase) + .stream() + .anyMatch((child) -> child.hasConfigDataOption(ConfigData.Option.PROFILE_SPECIFIC))) { return true; } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorPlaceholdersResolver.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorPlaceholdersResolver.java index 8ddf031706..a3268e0467 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorPlaceholdersResolver.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorPlaceholdersResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -88,7 +88,7 @@ class ConfigDataEnvironmentContributorPlaceholdersResolver implements Placeholde return contributor.isActive(this.activationContext); } return contributor.withBoundProperties(this.contributors, this.activationContext) - .isActive(this.activationContext); + .isActive(this.activationContext); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributors.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributors.java index 480adbd7e7..9b5fb64eab 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributors.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributors.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -221,8 +221,11 @@ class ConfigDataEnvironmentContributors implements Iterable getBinderSources(Predicate filter) { - return this.root.stream().filter(this::hasConfigurationPropertySource).filter(filter) - .map(ConfigDataEnvironmentContributor::getConfigurationPropertySource).iterator(); + return this.root.stream() + .filter(this::hasConfigurationPropertySource) + .filter(filter) + .map(ConfigDataEnvironmentContributor::getConfigurationPropertySource) + .iterator(); } private boolean hasConfigurationPropertySource(ConfigDataEnvironmentContributor contributor) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataLocationBindHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataLocationBindHandler.java index 138f5ef0a7..2ccf982a04 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataLocationBindHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataLocationBindHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,9 @@ class ConfigDataLocationBindHandler extends AbstractBindHandler { return list; } if (result instanceof ConfigDataLocation[]) { - ConfigDataLocation[] locations = Arrays.stream((ConfigDataLocation[]) result).filter(Objects::nonNull) - .toArray(ConfigDataLocation[]::new); + ConfigDataLocation[] locations = Arrays.stream((ConfigDataLocation[]) result) + .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 bfdc0ac5fe..d3ed25f453 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ class ConfigDataLocationResolvers { ConfigDataLocationResolvers(DeferredLogFactory logFactory, ConfigurableBootstrapContext bootstrapContext, Binder binder, ResourceLoader resourceLoader) { this(logFactory, bootstrapContext, binder, resourceLoader, SpringFactoriesLoader - .loadFactoryNames(ConfigDataLocationResolver.class, resourceLoader.getClassLoader())); + .loadFactoryNames(ConfigDataLocationResolver.class, resourceLoader.getClassLoader())); } /** diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataProperties.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataProperties.java index e9337c70f1..31e5820e6a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataProperties.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ class ConfigDataProperties { private static final ConfigurationPropertyName NAME = ConfigurationPropertyName.of("spring.config"); private static final ConfigurationPropertyName LEGACY_PROFILES_NAME = ConfigurationPropertyName - .of("spring.profiles"); + .of("spring.profiles"); private static final Bindable BINDABLE_PROPERTIES = Bindable.of(ConfigDataProperties.class); @@ -103,9 +103,9 @@ class ConfigDataProperties { static ConfigDataProperties get(Binder binder) { LegacyProfilesBindHandler legacyProfilesBindHandler = new LegacyProfilesBindHandler(); String[] legacyProfiles = binder.bind(LEGACY_PROFILES_NAME, BINDABLE_STRING_ARRAY, legacyProfilesBindHandler) - .orElse(null); + .orElse(null); ConfigDataProperties properties = binder.bind(NAME, BINDABLE_PROPERTIES, new ConfigDataLocationBindHandler()) - .orElse(null); + .orElse(null); if (!ObjectUtils.isEmpty(legacyProfiles)) { properties = (properties != null) ? properties.withLegacyProfiles(legacyProfiles, legacyProfilesBindHandler.getProperty()) diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigFileApplicationListener.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigFileApplicationListener.java index 3043285b78..d243b9ad59 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigFileApplicationListener.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigFileApplicationListener.java @@ -371,14 +371,15 @@ public class ConfigFileApplicationListener implements EnvironmentPostProcessor, private String[] getDefaultProfiles(Binder binder) { return binder.bind(AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME, STRING_ARRAY) - .orElseGet(this.environment::getDefaultProfiles); + .orElseGet(this.environment::getDefaultProfiles); } private List getOtherActiveProfiles(Set activatedViaProperty, Set includedViaProperty) { - return Arrays.stream(this.environment.getActiveProfiles()).map(Profile::new).filter( - (profile) -> !activatedViaProperty.contains(profile) && !includedViaProperty.contains(profile)) - .collect(Collectors.toList()); + return Arrays.stream(this.environment.getActiveProfiles()) + .map(Profile::new) + .filter((profile) -> !activatedViaProperty.contains(profile) && !includedViaProperty.contains(profile)) + .collect(Collectors.toList()); } void addActiveProfiles(Set profiles) { @@ -469,7 +470,7 @@ public class ConfigFileApplicationListener implements EnvironmentPostProcessor, private boolean canLoadFileExtension(PropertySourceLoader loader, String name) { return Arrays.stream(loader.getFileExtensions()) - .anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(name, fileExtension)); + .anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(name, fileExtension)); } private void loadForFileExtension(PropertySourceLoader loader, String prefix, String fileExtension, @@ -601,9 +602,12 @@ public class ConfigFileApplicationListener implements EnvironmentPostProcessor, if (files != null) { String fileName = locationReference.substring(locationReference.lastIndexOf("/") + 1); Arrays.sort(files, FILE_COMPARATOR); - return Arrays.stream(files).map((file) -> file.listFiles((dir, name) -> name.equals(fileName))) - .filter(Objects::nonNull).flatMap((Function>) Arrays::stream) - .map(FileSystemResource::new).toArray(Resource[]::new); + return Arrays.stream(files) + .map((file) -> file.listFiles((dir, name) -> name.equals(fileName))) + .filter(Objects::nonNull) + .flatMap((Function>) Arrays::stream) + .map(FileSystemResource::new) + .toArray(Resource[]::new); } return EMPTY_RESOURCES; } @@ -788,8 +792,10 @@ public class ConfigFileApplicationListener implements EnvironmentPostProcessor, activeProfiles.addAll(bindStringList(binder, "spring.profiles.active")); } } - this.processedProfiles.stream().filter(this::isDefaultProfile).map(Profile::getName) - .forEach(activeProfiles::add); + this.processedProfiles.stream() + .filter(this::isDefaultProfile) + .map(Profile::getName) + .forEach(activeProfiles::add); this.environment.setActiveProfiles(activeProfiles.toArray(new String[0])); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/Profiles.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/Profiles.java index ef22da174a..27cfd9fc79 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/Profiles.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/Profiles.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,10 +57,10 @@ public class Profiles implements Iterable { public static final String INCLUDE_PROFILES_PROPERTY_NAME = "spring.profiles.include"; static final ConfigurationPropertyName INCLUDE_PROFILES = ConfigurationPropertyName - .of(Profiles.INCLUDE_PROFILES_PROPERTY_NAME); + .of(Profiles.INCLUDE_PROFILES_PROPERTY_NAME); private static final Bindable> STRING_STRINGS_MAP = Bindable - .of(ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class)); + .of(ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class)); private static final Bindable> STRING_SET = Bindable.setOf(String.class); 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 a10f2d9049..fb7e6e56e1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -285,9 +285,10 @@ public class StandardConfigDataLocationResolver String message = String.format("Config data location '%s' contains no subdirectories", location); throw new ConfigDataLocationNotFoundException(location, message, null); } - return Arrays.stream(subdirectories).filter(Resource::exists) - .map((resource) -> new StandardConfigDataResource(reference, resource, true)) - .collect(Collectors.toCollection(LinkedHashSet::new)); + return Arrays.stream(subdirectories) + .filter(Resource::exists) + .map((resource) -> new StandardConfigDataResource(reference, resource, true)) + .collect(Collectors.toCollection(LinkedHashSet::new)); } private List resolve(StandardConfigDataReference reference) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/UseLegacyConfigProcessingException.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/UseLegacyConfigProcessingException.java index 5fffc16eb1..5ba525558a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/UseLegacyConfigProcessingException.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/UseLegacyConfigProcessingException.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ final class UseLegacyConfigProcessingException extends ConfigDataException { * The property name used to trigger legacy processing. */ static final ConfigurationPropertyName PROPERTY_NAME = ConfigurationPropertyName - .of("spring.config.use-legacy-processing"); + .of("spring.config.use-legacy-processing"); private static final Bindable BOOLEAN = Bindable.of(Boolean.class); 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 9fc26e5d8c..31eb9f965c 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-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,7 +76,7 @@ public class EventPublishingRunListener implements SpringApplicationRunListener, @Override public void starting(ConfigurableBootstrapContext bootstrapContext) { this.initialMulticaster - .multicastEvent(new ApplicationStartingEvent(bootstrapContext, this.application, this.args)); + .multicastEvent(new ApplicationStartingEvent(bootstrapContext, this.application, this.args)); } @Override @@ -89,7 +89,7 @@ public class EventPublishingRunListener implements SpringApplicationRunListener, @Override public void contextPrepared(ConfigurableApplicationContext context) { this.initialMulticaster - .multicastEvent(new ApplicationContextInitializedEvent(this.application, this.args, context)); + .multicastEvent(new ApplicationContextInitializedEvent(this.application, this.args, context)); } @Override @@ -128,7 +128,7 @@ public class EventPublishingRunListener implements SpringApplicationRunListener, // call all the context's listeners instead if (context instanceof AbstractApplicationContext) { for (ApplicationListener listener : ((AbstractApplicationContext) context) - .getApplicationListeners()) { + .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 54a19afd0b..005bd34a05 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -101,7 +101,7 @@ public class LoggingApplicationListener implements GenericApplicationListener { LogLevel.class); private static final Bindable>> STRING_STRINGS_MAP = Bindable - .of(ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class).asMap()); + .of(ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class).asMap()); /** * The default order for the LoggingApplicationListener. @@ -375,7 +375,7 @@ public class LoggingApplicationListener implements GenericApplicationListener { protected void initializeSpringBootLogging(LoggingSystem system, LogLevel springBootLogging) { BiConsumer configurer = getLogLevelConfigurer(system); SPRING_BOOT_LOGGING_LOGGERS.getOrDefault(springBootLogging, Collections.emptyList()) - .forEach((name) -> configureLogLevel(name, springBootLogging, configurer)); + .forEach((name) -> configureLogLevel(name, springBootLogging, configurer)); } /** diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/BoundConfigurationProperties.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/BoundConfigurationProperties.java index fdb806123a..149522f414 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/BoundConfigurationProperties.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/BoundConfigurationProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -82,8 +82,8 @@ public class BoundConfigurationProperties { Assert.notNull(registry, "Registry must not be null"); if (!registry.containsBeanDefinition(BEAN_NAME)) { BeanDefinition definition = BeanDefinitionBuilder - .genericBeanDefinition(BoundConfigurationProperties.class, BoundConfigurationProperties::new) - .getBeanDefinition(); + .genericBeanDefinition(BoundConfigurationProperties.class, BoundConfigurationProperties::new) + .getBeanDefinition(); definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(BEAN_NAME, definition); } 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 5d46d2d6b3..6c65cbefc4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -287,7 +287,7 @@ public final class ConfigurationPropertiesBean { } if (!annotation.isPresent() && AopUtils.isAopProxy(instance)) { annotation = MergedAnnotations.from(AopUtils.getTargetClass(instance), SearchStrategy.TYPE_HIERARCHY) - .get(annotationType); + .get(annotationType); } return annotation.isPresent() ? annotation.synthesize() : null; } 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 51e72231c1..301c3c5b02 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,8 @@ final class ConfigurationPropertiesBeanRegistrar { void register(Class type) { MergedAnnotation annotation = MergedAnnotations - .from(type, SearchStrategy.TYPE_HIERARCHY).get(ConfigurationProperties.class); + .from(type, SearchStrategy.TYPE_HIERARCHY) + .get(ConfigurationProperties.class); register(type, annotation); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindConstructorProvider.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindConstructorProvider.java index 6a22a66ead..5d323d064d 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindConstructorProvider.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindConstructorProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,7 +87,7 @@ class ConfigurationPropertiesBindConstructorProvider implements BindConstructorP private boolean isConstructorBindingAnnotatedType(Class type) { return MergedAnnotations.from(type, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY_AND_ENCLOSING_CLASSES) - .isPresent(ConstructorBinding.class); + .isPresent(ConstructorBinding.class); } private Constructor deduceBindConstructor(Class type) { 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..8566fed6b2 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -158,8 +158,9 @@ class ConfigurationPropertiesBinder { } private List getBindHandlerAdvisors() { - return this.applicationContext.getBeanProvider(ConfigurationPropertiesBindHandlerAdvisor.class).orderedStream() - .collect(Collectors.toList()); + return this.applicationContext.getBeanProvider(ConfigurationPropertiesBindHandlerAdvisor.class) + .orderedStream() + .collect(Collectors.toList()); } private Binder getBinder() { @@ -193,16 +194,18 @@ class ConfigurationPropertiesBinder { static void register(BeanDefinitionRegistry registry) { if (!registry.containsBeanDefinition(FACTORY_BEAN_NAME)) { BeanDefinition definition = BeanDefinitionBuilder - .rootBeanDefinition(ConfigurationPropertiesBinder.Factory.class).getBeanDefinition(); + .rootBeanDefinition(ConfigurationPropertiesBinder.Factory.class) + .getBeanDefinition(); definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(ConfigurationPropertiesBinder.FACTORY_BEAN_NAME, definition); } if (!registry.containsBeanDefinition(BEAN_NAME)) { BeanDefinition definition = BeanDefinitionBuilder - .rootBeanDefinition(ConfigurationPropertiesBinder.class, - () -> ((BeanFactory) registry) - .getBean(FACTORY_BEAN_NAME, ConfigurationPropertiesBinder.Factory.class).create()) - .getBeanDefinition(); + .rootBeanDefinition(ConfigurationPropertiesBinder.class, + () -> ((BeanFactory) registry) + .getBean(FACTORY_BEAN_NAME, ConfigurationPropertiesBinder.Factory.class) + .create()) + .getBeanDefinition(); definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(ConfigurationPropertiesBinder.BEAN_NAME, definition); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessor.java index f6d53b9224..7e3ecb8f52 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -95,7 +95,7 @@ public class ConfigurationPropertiesBindingPostProcessor private boolean hasBoundValueObject(String beanName) { return this.registry.containsBeanDefinition(beanName) && BindMethod.VALUE_OBJECT - .equals(this.registry.getBeanDefinition(beanName).getAttribute(BindMethod.class.getName())); + .equals(this.registry.getBeanDefinition(beanName).getAttribute(BindMethod.class.getName())); } /** @@ -108,7 +108,8 @@ public class ConfigurationPropertiesBindingPostProcessor Assert.notNull(registry, "Registry must not be null"); if (!registry.containsBeanDefinition(BEAN_NAME)) { BeanDefinition definition = BeanDefinitionBuilder - .rootBeanDefinition(ConfigurationPropertiesBindingPostProcessor.class).getBeanDefinition(); + .rootBeanDefinition(ConfigurationPropertiesBindingPostProcessor.class) + .getBeanDefinition(); definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(BEAN_NAME, definition); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrar.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrar.java index 56bb818571..7563db4731 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrar.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrar.java @@ -64,7 +64,7 @@ class ConfigurationPropertiesScanRegistrar implements ImportBeanDefinitionRegist private Set getPackagesToScan(AnnotationMetadata metadata) { AnnotationAttributes attributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(ConfigurationPropertiesScan.class.getName())); + .fromMap(metadata.getAnnotationAttributes(ConfigurationPropertiesScan.class.getName())); String[] basePackages = attributes.getStringArray("basePackages"); Class[] basePackageClasses = attributes.getClassArray("basePackageClasses"); Set packagesToScan = new LinkedHashSet<>(Arrays.asList(basePackages)); 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..81194ab4e6 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,7 @@ class ConversionServiceDeducer { List getConversionServices() { if (hasUserDefinedConfigurationServiceBean()) { return Collections.singletonList(this.applicationContext - .getBean(ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); + .getBean(ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); } if (this.applicationContext instanceof ConfigurableApplicationContext) { return getConversionServices((ConfigurableApplicationContext) this.applicationContext); @@ -74,7 +74,7 @@ class ConversionServiceDeducer { private boolean hasUserDefinedConfigurationServiceBean() { String beanName = ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME; return this.applicationContext.containsBean(beanName) && this.applicationContext.getAutowireCapableBeanFactory() - .isTypeMatch(beanName, ConversionService.class); + .isTypeMatch(beanName, ConversionService.class); } private static class ConverterBeans { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesRegistrar.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesRegistrar.java index 49aa20d1aa..bae5b6de2b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesRegistrar.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ import org.springframework.core.type.AnnotationMetadata; class EnableConfigurationPropertiesRegistrar implements ImportBeanDefinitionRegistrar { private static final String METHOD_VALIDATION_EXCLUDE_FILTER_BEAN_NAME = Conventions - .getQualifiedAttributeName(EnableConfigurationPropertiesRegistrar.class, "methodValidationExcludeFilter"); + .getQualifiedAttributeName(EnableConfigurationPropertiesRegistrar.class, "methodValidationExcludeFilter"); @Override public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { @@ -50,9 +50,11 @@ class EnableConfigurationPropertiesRegistrar implements ImportBeanDefinitionRegi } private Set> getTypes(AnnotationMetadata metadata) { - return metadata.getAnnotations().stream(EnableConfigurationProperties.class) - .flatMap((annotation) -> Arrays.stream(annotation.getClassArray(MergedAnnotation.VALUE))) - .filter((type) -> void.class != type).collect(Collectors.toSet()); + return metadata.getAnnotations() + .stream(EnableConfigurationProperties.class) + .flatMap((annotation) -> Arrays.stream(annotation.getClassArray(MergedAnnotation.VALUE))) + .filter((type) -> void.class != type) + .collect(Collectors.toSet()); } static void registerInfrastructureBeans(BeanDefinitionRegistry registry) { @@ -63,9 +65,10 @@ class EnableConfigurationPropertiesRegistrar implements ImportBeanDefinitionRegi static void registerMethodValidationExcludeFilter(BeanDefinitionRegistry registry) { if (!registry.containsBeanDefinition(METHOD_VALIDATION_EXCLUDE_FILTER_BEAN_NAME)) { BeanDefinition definition = BeanDefinitionBuilder - .genericBeanDefinition(MethodValidationExcludeFilter.class, - () -> MethodValidationExcludeFilter.byAnnotation(ConfigurationProperties.class)) - .setRole(BeanDefinition.ROLE_INFRASTRUCTURE).getBeanDefinition(); + .genericBeanDefinition(MethodValidationExcludeFilter.class, + () -> MethodValidationExcludeFilter.byAnnotation(ConfigurationProperties.class)) + .setRole(BeanDefinition.ROLE_INFRASTRUCTURE) + .getBeanDefinition(); registry.registerBeanDefinition(METHOD_VALIDATION_EXCLUDE_FILTER_BEAN_NAME, definition); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/NotConstructorBoundInjectionFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/NotConstructorBoundInjectionFailureAnalyzer.java index b8166e8ae8..28ad5b6a4a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/NotConstructorBoundInjectionFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/NotConstructorBoundInjectionFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,7 +64,7 @@ class NotConstructorBoundInjectionFailureAnalyzer Constructor constructor = (Constructor) injectionPoint.getMember(); Class declaringClass = constructor.getDeclaringClass(); MergedAnnotation configurationProperties = MergedAnnotations.from(declaringClass) - .get(ConfigurationProperties.class); + .get(ConfigurationProperties.class); return configurationProperties.isPresent() && BindMethod.forType(constructor.getDeclaringClass()) == BindMethod.VALUE_OBJECT; } 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..619210913b 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,7 +58,7 @@ class PropertySourcesDeducer { private PropertySourcesPlaceholderConfigurer getSinglePropertySourcesPlaceholderConfigurer() { // Take care not to cause early instantiation of all FactoryBeans Map beans = this.applicationContext - .getBeansOfType(PropertySourcesPlaceholderConfigurer.class, false, false); + .getBeansOfType(PropertySourcesPlaceholderConfigurer.class, false, false); if (beans.size() == 1) { return beans.values().iterator().next(); } 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..2a03455784 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ import org.springframework.util.Assert; public class Binder { private static final Set> NON_BEAN_CLASSES = Collections - .unmodifiableSet(new HashSet<>(Arrays.asList(Object.class, Class.class))); + .unmodifiableSet(new HashSet<>(Arrays.asList(Object.class, Class.class))); private final Iterable sources; 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..c145169b8a 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -132,8 +132,11 @@ abstract class IndexedElementsBinder extends AggregateBinder { private void assertNoUnboundChildren(ConfigurationPropertySource source, MultiValueMap children) { if (!children.isEmpty()) { - throw new UnboundConfigurationPropertiesException(children.values().stream().flatMap(List::stream) - .map(source::getConfigurationProperty).collect(Collectors.toCollection(TreeSet::new))); + throw new UnboundConfigurationPropertiesException(children.values() + .stream() + .flatMap(List::stream) + .map(source::getConfigurationProperty) + .collect(Collectors.toCollection(TreeSet::new))); } } 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..82e5a8871c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ class MapBinder extends AggregateBinder> { protected Object bindAggregate(ConfigurationPropertyName name, Bindable target, AggregateElementBinder elementBinder) { Map map = CollectionFactory - .createMap((target.getValue() != null) ? Map.class : target.getType().resolve(Object.class), 0); + .createMap((target.getValue() != null) ? Map.class : target.getType().resolve(Object.class), 0); Bindable resolvedTarget = resolveTarget(target); boolean hasDescendants = hasDescendants(name); for (ConfigurationPropertySource source : getContext().getSources()) { 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 c6378d4bd8..665665f2d1 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-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -222,7 +222,7 @@ class ValueObjectBinder implements DataObjectBinder { for (KParameter parameter : parameters) { String name = getParameterName(parameter); ResolvableType parameterType = ResolvableType - .forType(ReflectJvmMapping.getJavaType(parameter.getType()), type); + .forType(ReflectJvmMapping.getJavaType(parameter.getType()), type); Annotation[] annotations = parameter.getAnnotations().toArray(ANNOTATION_ARRAY); result.add(new ConstructorParameter(name, parameterType, annotations)); } @@ -231,7 +231,9 @@ class ValueObjectBinder implements DataObjectBinder { private String getParameterName(KParameter parameter) { return MergedAnnotations.from(parameter, parameter.getAnnotations().toArray(ANNOTATION_ARRAY)) - .get(Name.class).getValue(MergedAnnotation.VALUE, String.class).orElseGet(parameter::getName); + .get(Name.class) + .getValue(MergedAnnotation.VALUE, String.class) + .orElseGet(parameter::getName); } @Override @@ -271,8 +273,10 @@ class ValueObjectBinder implements DataObjectBinder { Parameter[] parameters = constructor.getParameters(); List result = new ArrayList<>(parameters.length); for (int i = 0; i < parameters.length; i++) { - String name = MergedAnnotations.from(parameters[i]).get(Name.class) - .getValue(MergedAnnotation.VALUE, String.class).orElse(names[i]); + String name = MergedAnnotations.from(parameters[i]) + .get(Name.class) + .getValue(MergedAnnotation.VALUE, String.class) + .orElse(names[i]); ResolvableType parameterType = ResolvableType.forMethodParameter(new MethodParameter(constructor, i), type); Annotation[] annotations = parameters[i].getDeclaredAnnotations(); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandler.java index 4789e9434a..26224addd9 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -236,8 +236,8 @@ public class ValidationBindHandler extends AbstractBindHandler { ValidationErrors getValidationErrors() { Set boundProperties = ValidationBindHandler.this.boundProperties.stream() - .filter((property) -> this.name.isAncestorOf(property.getName())) - .collect(Collectors.toCollection(LinkedHashSet::new)); + .filter((property) -> this.name.isAncestorOf(property.getName())) + .collect(Collectors.toCollection(LinkedHashSet::new)); return new ValidationErrors(this.name, boundProperties, getAllErrors()); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationProperty.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationProperty.java index 94dcd536a8..27f4948e1a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationProperty.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationProperty.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -111,8 +111,10 @@ public final class ConfigurationProperty implements OriginProvider, Comparable e.getValue().contains(alias)).map(Map.Entry::getKey) - .findFirst().orElse(null); + return this.aliases.entrySet() + .stream() + .filter((e) -> e.getValue().contains(alias)) + .map(Map.Entry::getKey) + .findFirst() + .orElse(null); } @Override 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..c3e0db9af3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -117,7 +117,7 @@ public final class ConfigurationPropertySources { Assert.isInstanceOf(ConfigurableEnvironment.class, environment); MutablePropertySources sources = ((ConfigurableEnvironment) environment).getPropertySources(); ConfigurationPropertySourcesPropertySource attached = (ConfigurationPropertySourcesPropertySource) sources - .get(ATTACHED_PROPERTY_SOURCE_NAME); + .get(ATTACHED_PROPERTY_SOURCE_NAME); if (attached == null) { return from(sources); } @@ -153,8 +153,9 @@ public final class ConfigurationPropertySources { } private static Stream> streamPropertySources(PropertySources sources) { - return sources.stream().flatMap(ConfigurationPropertySources::flatten) - .filter(ConfigurationPropertySources::isIncluded); + return sources.stream() + .flatMap(ConfigurationPropertySources::flatten) + .filter(ConfigurationPropertySources::isIncluded); } private static Stream> flatten(PropertySource 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..687c7263d0 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -99,7 +99,7 @@ class ConfigurationPropertySourcesPropertyResolver extends AbstractPropertyResol private ConfigurationPropertySourcesPropertySource getAttached() { ConfigurationPropertySourcesPropertySource attached = (ConfigurationPropertySourcesPropertySource) ConfigurationPropertySources - .getAttached(this.propertySources); + .getAttached(this.propertySources); Iterable attachedSource = (attached != null) ? attached.getSource() : null; if ((attachedSource instanceof SpringConfigurationPropertySources) && ((SpringConfigurationPropertySources) attachedSource).isUsingSources(this.propertySources)) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/MutuallyExclusiveConfigurationPropertiesException.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/MutuallyExclusiveConfigurationPropertiesException.java index 97f96cf4b1..3509489087 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/MutuallyExclusiveConfigurationPropertiesException.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/MutuallyExclusiveConfigurationPropertiesException.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -98,8 +98,11 @@ public class MutuallyExclusiveConfigurationPropertiesException extends RuntimeEx public static void throwIfMultipleNonNullValuesIn(Consumer> entries) { Map map = new LinkedHashMap<>(); entries.accept(map); - Set configuredNames = map.entrySet().stream().filter((entry) -> entry.getValue() != null) - .map(Map.Entry::getKey).collect(Collectors.toCollection(LinkedHashSet::new)); + Set configuredNames = map.entrySet() + .stream() + .filter((entry) -> entry.getValue() != null) + .map(Map.Entry::getKey) + .collect(Collectors.toCollection(LinkedHashSet::new)); if (configuredNames.size() > 1) { throw new MutuallyExclusiveConfigurationPropertiesException(configuredNames, map.keySet()); } 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..f616356802 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,7 +69,7 @@ class SpringIterableConfigurationPropertySource extends SpringConfigurationPrope private BiPredicate getAncestorOfCheck( PropertyMapper[] mappers) { BiPredicate ancestorOfCheck = mappers[0] - .getAncestorOfCheck(); + .getAncestorOfCheck(); for (int i = 1; i < mappers.length; i++) { ancestorOfCheck = ancestorOfCheck.or(mappers[i].getAncestorOfCheck()); } @@ -147,7 +147,7 @@ class SpringIterableConfigurationPropertySource extends SpringConfigurationPrope ConfigurationPropertyName[] configurationPropertyNames = this.configurationPropertyNames; if (configurationPropertyNames == null) { configurationPropertyNames = getMappings() - .getConfigurationPropertyNames(getPropertySource().getPropertyNames()); + .getConfigurationPropertyNames(getPropertySource().getPropertyNames()); this.configurationPropertyNames = configurationPropertyNames; } return configurationPropertyNames; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/UnboundElementsSourceFilter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/UnboundElementsSourceFilter.java index dcc8b705ae..754a7c328a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/UnboundElementsSourceFilter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/UnboundElementsSourceFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,8 @@ import org.springframework.core.env.StandardEnvironment; public class UnboundElementsSourceFilter implements Function { private static final Set BENIGN_PROPERTY_SOURCE_NAMES = Collections - .unmodifiableSet(new HashSet<>(Arrays.asList(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, - StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME))); + .unmodifiableSet(new HashSet<>(Arrays.asList(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, + StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME))); @Override public Boolean apply(ConfigurationPropertySource configurationPropertySource) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/CollectionToDelimitedStringConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/CollectionToDelimitedStringConverter.java index 66bb03612a..0346fd8ea2 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/CollectionToDelimitedStringConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/CollectionToDelimitedStringConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,8 +66,9 @@ final class CollectionToDelimitedStringConverter implements ConditionalGenericCo if (source.isEmpty()) { return ""; } - return source.stream().map((element) -> convertElement(element, sourceType, targetType)) - .collect(Collectors.joining(getDelimiter(sourceType))); + return source.stream() + .map((element) -> convertElement(element, sourceType, targetType)) + .collect(Collectors.joining(getDelimiter(sourceType))); } private CharSequence getDelimiter(TypeDescriptor sourceType) { @@ -76,8 +77,8 @@ final class CollectionToDelimitedStringConverter implements ConditionalGenericCo } private String convertElement(Object element, TypeDescriptor sourceType, TypeDescriptor targetType) { - return String.valueOf( - this.conversionService.convert(element, sourceType.elementTypeDescriptor(element), targetType)); + return String + .valueOf(this.conversionService.convert(element, sourceType.elementTypeDescriptor(element), targetType)); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationStyle.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationStyle.java index cd282e2395..1db30449ed 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationStyle.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationStyle.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ public enum DurationStyle { Assert.state(matcher.matches(), "Does not match simple duration pattern"); String suffix = matcher.group(2); return (StringUtils.hasLength(suffix) ? Unit.fromSuffix(suffix) : Unit.fromChronoUnit(unit)) - .parse(matcher.group(1)); + .parse(matcher.group(1)); } catch (Exception ex) { throw new IllegalArgumentException("'" + value + "' is not a valid simple duration", ex); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationToNumberConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationToNumberConverter.java index abf2bae3f1..5db8f13f8e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationToNumberConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationToNumberConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,7 +56,7 @@ final class DurationToNumberConverter implements GenericConverter { private Object convert(Duration source, ChronoUnit unit, Class type) { try { return type.getConstructor(String.class) - .newInstance(String.valueOf(DurationStyle.Unit.fromChronoUnit(unit).longValue(source))); + .newInstance(String.valueOf(DurationStyle.Unit.fromChronoUnit(unit).longValue(source))); } catch (Exception ex) { ReflectionUtils.rethrowRuntimeException(ex); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/LenientObjectToEnumConverterFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/LenientObjectToEnumConverterFactory.java index 4a1d3e21ea..2989dbb77b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/LenientObjectToEnumConverterFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/LenientObjectToEnumConverterFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -95,8 +95,10 @@ abstract class LenientObjectToEnumConverterFactory implements ConverterFactor private String getCanonicalName(String name) { StringBuilder canonicalName = new StringBuilder(name.length()); - name.chars().filter(Character::isLetterOrDigit).map(Character::toLowerCase) - .forEach((c) -> canonicalName.append((char) c)); + name.chars() + .filter(Character::isLetterOrDigit) + .map(Character::toLowerCase) + .forEach((c) -> canonicalName.append((char) c)); return canonicalName.toString(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/FailureAnalyzers.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/FailureAnalyzers.java index d493c47894..8955b012e9 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/FailureAnalyzers.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/FailureAnalyzers.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -84,11 +84,12 @@ final class FailureAnalyzers implements SpringBootExceptionReporter { private List handleAwareAnalyzers(List analyzers, ConfigurableApplicationContext context) { List awareAnalyzers = analyzers.stream() - .filter((analyzer) -> analyzer instanceof BeanFactoryAware || analyzer instanceof EnvironmentAware) - .collect(Collectors.toList()); + .filter((analyzer) -> analyzer instanceof BeanFactoryAware || analyzer instanceof EnvironmentAware) + .collect(Collectors.toList()); if (!awareAnalyzers.isEmpty()) { String awareAnalyzerNames = StringUtils.collectionToCommaDelimitedString(awareAnalyzers.stream() - .map((analyzer) -> analyzer.getClass().getName()).collect(Collectors.toList())); + .map((analyzer) -> analyzer.getClass().getName()) + .collect(Collectors.toList())); logger.warn(LogMessage.format( "FailureAnalyzers [%s] implement BeanFactoryAware or EnvironmentAware. " + "Support for these interfaces on FailureAnalyzers is deprecated, " @@ -97,8 +98,9 @@ final class FailureAnalyzers implements SpringBootExceptionReporter { awareAnalyzerNames)); if (context == null) { logger.trace(LogMessage.format("Skipping [%s] due to missing context", awareAnalyzerNames)); - return analyzers.stream().filter((analyzer) -> !awareAnalyzers.contains(analyzer)) - .collect(Collectors.toList()); + return analyzers.stream() + .filter((analyzer) -> !awareAnalyzers.contains(analyzer)) + .collect(Collectors.toList()); } awareAnalyzers.forEach((analyzer) -> { if (analyzer instanceof BeanFactoryAware) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzer.java index 7f1cff0090..0356d4c326 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,15 +63,17 @@ class InvalidConfigurationPropertyValueFailureAnalyzer private List getDescriptors(String propertyName) { return getPropertySources().filter((source) -> source.containsProperty(propertyName)) - .map((source) -> Descriptor.get(source, propertyName)).collect(Collectors.toList()); + .map((source) -> Descriptor.get(source, propertyName)) + .collect(Collectors.toList()); } private Stream> getPropertySources() { if (this.environment == null) { return Stream.empty(); } - return this.environment.getPropertySources().stream() - .filter((source) -> !ConfigurationPropertySources.isAttachedConfigurationPropertySource(source)); + return this.environment.getPropertySources() + .stream() + .filter((source) -> !ConfigurationPropertySources.isAttachedConfigurationPropertySource(source)); } private void appendDetails(StringBuilder message, InvalidConfigurationPropertyValueException cause, @@ -96,9 +98,9 @@ class InvalidConfigurationPropertyValueFailureAnalyzer private void appendAdditionalProperties(StringBuilder message, List descriptors) { List others = descriptors.subList(1, descriptors.size()); if (!others.isEmpty()) { - message.append( - String.format("%n%nAdditionally, this property is also set in the following property %s:%n%n", - (others.size() > 1) ? "sources" : "source")); + message + .append(String.format("%n%nAdditionally, this property is also set in the following property %s:%n%n", + (others.size() > 1) ? "sources" : "source")); for (Descriptor other : others) { message.append("\t- In '").append(other.getPropertySource()).append("'"); message.append(" with the value '").append(other.getValue()).append("'"); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/MutuallyExclusiveConfigurationPropertiesFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/MutuallyExclusiveConfigurationPropertiesFailureAnalyzer.java index 56bac16c92..3c52a98173 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/MutuallyExclusiveConfigurationPropertiesFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/MutuallyExclusiveConfigurationPropertiesFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,15 +71,17 @@ class MutuallyExclusiveConfigurationPropertiesFailureAnalyzer private List getDescriptors(String propertyName) { return getPropertySources().filter((source) -> source.containsProperty(propertyName)) - .map((source) -> Descriptor.get(source, propertyName)).collect(Collectors.toList()); + .map((source) -> Descriptor.get(source, propertyName)) + .collect(Collectors.toList()); } private Stream> getPropertySources() { if (this.environment == null) { return Stream.empty(); } - return this.environment.getPropertySources().stream() - .filter((source) -> !ConfigurationPropertySources.isAttachedConfigurationPropertySource(source)); + return this.environment.getPropertySources() + .stream() + .filter((source) -> !ConfigurationPropertySources.isAttachedConfigurationPropertySource(source)); } private void appendDetails(StringBuilder message, MutuallyExclusiveConfigurationPropertiesException cause, @@ -87,7 +89,7 @@ class MutuallyExclusiveConfigurationPropertiesFailureAnalyzer descriptors.sort((d1, d2) -> d1.propertyName.compareTo(d2.propertyName)); message.append(String.format("The following configuration properties are mutually exclusive:%n%n")); sortedStrings(cause.getMutuallyExclusiveNames()) - .forEach((name) -> message.append(String.format("\t%s%n", name))); + .forEach((name) -> message.append(String.format("\t%s%n", name))); message.append(String.format("%n")); message.append( String.format("However, more than one of those properties has been configured at the same time:%n%n")); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzer.java index 1b0214beba..16ea0e5d36 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -116,7 +116,7 @@ class NoSuchMethodFailureAnalyzer extends AbstractFailureAnalyzer findCandidates(String className) { try { return Collections.list(NoSuchMethodFailureAnalyzer.class.getClassLoader() - .getResources(ClassUtils.convertClassNameToResourcePath(className) + ".class")); + .getResources(ClassUtils.convertClassNameToResourcePath(className) + ".class")); } catch (Throwable ex) { return null; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/ConfigTreePropertySource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/ConfigTreePropertySource.java index 1a263ae783..76d5fb927e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/ConfigTreePropertySource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/ConfigTreePropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -205,15 +205,15 @@ public class ConfigTreePropertySource extends EnumerablePropertySource imp try { Map propertyFiles = new TreeMap<>(); Files.find(sourceDirectory, MAX_DEPTH, PropertyFile::isPropertyFile, FileVisitOption.FOLLOW_LINKS) - .forEach((path) -> { - String name = getName(sourceDirectory.relativize(path)); - if (StringUtils.hasText(name)) { - if (options.contains(Option.USE_LOWERCASE_NAMES)) { - name = name.toLowerCase(); - } - propertyFiles.put(name, new PropertyFile(path, options)); + .forEach((path) -> { + String name = getName(sourceDirectory.relativize(path)); + if (StringUtils.hasText(name)) { + if (options.contains(Option.USE_LOWERCASE_NAMES)) { + name = name.toLowerCase(); } - }); + propertyFiles.put(name, new PropertyFile(path, options)); + } + }); return Collections.unmodifiableMap(propertyFiles); } catch (IOException ex) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessor.java index ba10642b13..dbe0d6d29f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -93,8 +93,11 @@ public class SpringApplicationJsonEnvironmentPostProcessor implements Environmen @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { MutablePropertySources propertySources = environment.getPropertySources(); - propertySources.stream().map(JsonPropertyValue::get).filter(Objects::nonNull).findFirst() - .ifPresent((v) -> processJson(environment, v)); + propertySources.stream() + .map(JsonPropertyValue::get) + .filter(Objects::nonNull) + .findFirst() + .ifPresent((v) -> processJson(environment, v)); } private void processJson(ConfigurableEnvironment environment, JsonPropertyValue propertyValue) { @@ -160,8 +163,9 @@ public class SpringApplicationJsonEnvironmentPostProcessor implements Environmen private String findPropertySource(MutablePropertySources sources) { if (ClassUtils.isPresent(SERVLET_ENVIRONMENT_CLASS, null)) { PropertySource servletPropertySource = sources.stream() - .filter((source) -> SERVLET_ENVIRONMENT_PROPERTY_SOURCES.contains(source.getName())).findFirst() - .orElse(null); + .filter((source) -> SERVLET_ENVIRONMENT_PROPERTY_SOURCES.contains(source.getName())) + .findFirst() + .orElse(null); if (servletPropertySource != null) { return servletPropertySource.getName(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/info/BuildProperties.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/info/BuildProperties.java index 76ec3485aa..7084978b60 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/info/BuildProperties.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/info/BuildProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -91,7 +91,7 @@ public class BuildProperties extends InfoProperties { if (value != null) { try { String updatedValue = String - .valueOf(DateTimeFormatter.ISO_INSTANT.parse(value, Instant::from).toEpochMilli()); + .valueOf(DateTimeFormatter.ISO_INSTANT.parse(value, Instant::from).toEpochMilli()); properties.setProperty(key, updatedValue); } catch (DateTimeException ex) { 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..90693f5563 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -84,7 +84,8 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar private void addJsonBean(Object bean) { MergedAnnotation annotation = MergedAnnotations - .from(bean.getClass(), SearchStrategy.TYPE_HIERARCHY).get(JsonComponent.class); + .from(bean.getClass(), SearchStrategy.TYPE_HIERARCHY) + .get(JsonComponent.class); Class[] types = annotation.getClassArray("type"); Scope scope = annotation.getEnum("scope", JsonComponent.Scope.class); addJsonBean(bean, types, scope); @@ -117,7 +118,7 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar @SuppressWarnings("unchecked") private void addJsonSerializerBean(JsonSerializer serializer, JsonComponent.Scope scope, Class[] types) { Class baseType = (Class) ResolvableType.forClass(JsonSerializer.class, serializer.getClass()) - .resolveGeneric(); + .resolveGeneric(); addBeanToModule(serializer, baseType, types, (scope == Scope.VALUES) ? this::addSerializer : this::addKeySerializer); @@ -126,7 +127,7 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar @SuppressWarnings("unchecked") private void addJsonDeserializerBean(JsonDeserializer deserializer, Class[] types) { Class baseType = (Class) ResolvableType.forClass(JsonDeserializer.class, deserializer.getClass()) - .resolveGeneric(); + .resolveGeneric(); addBeanToModule(deserializer, baseType, types, this::addDeserializer); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonMixinModule.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonMixinModule.java index 2285683384..e2ccda947c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonMixinModule.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonMixinModule.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,7 +79,8 @@ public class JsonMixinModule extends SimpleModule implements InitializingBean { private void addJsonMixin(Class mixinClass) { MergedAnnotation annotation = MergedAnnotations - .from(mixinClass, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY).get(JsonMixin.class); + .from(mixinClass, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY) + .get(JsonMixin.class); for (Class targetType : annotation.getClassArray("type")) { setMixInAnnotation(targetType, mixinClass); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceBuilder.java index 62d85ccc05..227b4c1a28 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -329,7 +329,7 @@ public final class DataSourceBuilder { @SuppressWarnings("unchecked") MappedDataSourceProperties() { this.dataSourceType = (Class) ResolvableType.forClass(MappedDataSourceProperties.class, getClass()) - .resolveGeneric(); + .resolveGeneric(); } @Override diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnection.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnection.java index 66d46ee1ac..c1fd41dc03 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnection.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnection.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -147,8 +147,10 @@ public enum EmbeddedDatabaseConnection { } private static EmbeddedDatabaseConnection getEmbeddedDatabaseConnection(String driverClass) { - return Stream.of(H2, HSQLDB, DERBY).filter((connection) -> connection.isDriverCompatible(driverClass)) - .findFirst().orElse(NONE); + return Stream.of(H2, HSQLDB, DERBY) + .filter((connection) -> connection.isDriverCompatible(driverClass)) + .findFirst() + .orElse(NONE); } /** diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/YamlJsonParser.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/YamlJsonParser.java index 255c467007..f3dfb0f85f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/YamlJsonParser.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/YamlJsonParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,8 +59,9 @@ public class YamlJsonParser extends AbstractJsonParser { Set> supportedTypes = new LinkedHashSet<>(); supportedTypes.add(List.class); supportedTypes.add(Map.class); - SUPPORTED_TYPES = supportedTypes.stream().map(Class::getName) - .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); + SUPPORTED_TYPES = supportedTypes.stream() + .map(Class::getName) + .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); } @Override diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java index fdeba0ba80..13671b169a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -103,7 +103,7 @@ public class JavaLoggingSystem extends AbstractLoggingSystem { Assert.notNull(location, "Location must not be null"); try { String configuration = FileCopyUtils - .copyToString(new InputStreamReader(ResourceUtils.getURL(location).openStream())); + .copyToString(new InputStreamReader(ResourceUtils.getURL(location).openStream())); if (logFile != null) { configuration = configuration.replace("${LOG_FILE}", StringUtils.cleanPath(logFile.toString())); } 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 6242ace3ca..d3ed675c88 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -182,7 +182,7 @@ public class Log4J2LoggingSystem extends Slf4JLoggingSystem { private List getOverrides(LoggingInitializationContext initializationContext) { BindResult> overrides = Binder.get(initializationContext.getEnvironment()) - .bind("logging.log4j2.config.override", Bindable.listOf(String.class)); + .bind("logging.log4j2.config.override", Bindable.listOf(String.class)); return overrides.orElse(Collections.emptyList()); } @@ -311,8 +311,8 @@ public class Log4J2LoggingSystem extends Slf4JLoggingSystem { private void setLogLevel(String loggerName, LoggerConfig logger, Level level) { if (logger == null) { - getLoggerContext().getConfiguration().addLogger(loggerName, - new LevelSetLoggerConfig(loggerName, level, true)); + getLoggerContext().getConfiguration() + .addLogger(loggerName, new LevelSetLoggerConfig(loggerName, level, true)); } else { logger.setLevel(level); @@ -420,7 +420,7 @@ public class Log4J2LoggingSystem extends Slf4JLoggingSystem { public static class Factory implements LoggingSystemFactory { private static final boolean PRESENT = ClassUtils - .isPresent("org.apache.logging.log4j.core.impl.Log4jContextFactory", Factory.class.getClassLoader()); + .isPresent("org.apache.logging.log4j.core.impl.Log4jContextFactory", Factory.class.getClassLoader()); @Override public LoggingSystem getLoggingSystem(ClassLoader classLoader) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringBootPropertySource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringBootPropertySource.java index a597fe874e..625c525a82 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringBootPropertySource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringBootPropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ public class SpringBootPropertySource implements PropertySource { private static final String PREFIX = "log4j."; private final Map properties = Collections - .singletonMap(ShutdownCallbackRegistry.SHUTDOWN_HOOK_ENABLED, "false"); + .singletonMap(ShutdownCallbackRegistry.SHUTDOWN_HOOK_ENABLED, "false"); @Override public void forEach(BiConsumer action) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java index 0d6d7fe454..397636821b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,18 +67,20 @@ class DefaultLogbackConfiguration { config.conversionRule("clr", ColorConverter.class); config.conversionRule("wex", WhitespaceThrowableProxyConverter.class); config.conversionRule("wEx", ExtendedWhitespaceThrowableProxyConverter.class); - config.getContext().putProperty("CONSOLE_LOG_PATTERN", resolve(config, "${CONSOLE_LOG_PATTERN:-" - + "%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) " - + "%clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} " - + "%clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}")); + config.getContext() + .putProperty("CONSOLE_LOG_PATTERN", resolve(config, "${CONSOLE_LOG_PATTERN:-" + + "%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) " + + "%clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} " + + "%clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}")); String defaultCharset = Charset.defaultCharset().name(); - config.getContext().putProperty("CONSOLE_LOG_CHARSET", - resolve(config, "${CONSOLE_LOG_CHARSET:-" + defaultCharset + "}")); - config.getContext().putProperty("FILE_LOG_PATTERN", resolve(config, "${FILE_LOG_PATTERN:-" - + "%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] " - + "%-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}")); - config.getContext().putProperty("FILE_LOG_CHARSET", - resolve(config, "${FILE_LOG_CHARSET:-" + defaultCharset + "}")); + config.getContext() + .putProperty("CONSOLE_LOG_CHARSET", resolve(config, "${CONSOLE_LOG_CHARSET:-" + defaultCharset + "}")); + config.getContext() + .putProperty("FILE_LOG_PATTERN", resolve(config, "${FILE_LOG_PATTERN:-" + + "%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] " + + "%-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}")); + config.getContext() + .putProperty("FILE_LOG_CHARSET", resolve(config, "${FILE_LOG_CHARSET:-" + defaultCharset + "}")); config.logger("org.apache.catalina.startup.DigesterFactory", Level.ERROR); config.logger("org.apache.catalina.util.LifecycleBase", Level.ERROR); config.logger("org.apache.coyote.http11.Http11NioProtocol", Level.WARN); @@ -118,8 +120,8 @@ class DefaultLogbackConfiguration { rollingPolicy.setContext(config.getContext()); rollingPolicy.setFileNamePattern( resolve(config, "${LOGBACK_ROLLINGPOLICY_FILE_NAME_PATTERN:-${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz}")); - rollingPolicy.setCleanHistoryOnStart( - resolveBoolean(config, "${LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_START:-false}")); + rollingPolicy + .setCleanHistoryOnStart(resolveBoolean(config, "${LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_START:-false}")); rollingPolicy.setMaxFileSize(resolveFileSize(config, "${LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZE:-10MB}")); rollingPolicy.setTotalSizeCap(resolveFileSize(config, "${LOGBACK_ROLLINGPOLICY_TOTAL_SIZE_CAP:-0}")); rollingPolicy.setMaxHistory(resolveInt(config, "${LOGBACK_ROLLINGPOLICY_MAX_HISTORY:-7}")); 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..85a8f7a24c 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,7 +58,7 @@ class LogbackConfigurator { Assert.hasLength(conversionWord, "Conversion word must not be empty"); Assert.notNull(converterClass, "Converter class must not be null"); Map registry = (Map) this.context - .getObject(CoreConstants.PATTERN_RULE_REGISTRY); + .getObject(CoreConstants.PATTERN_RULE_REGISTRY); if (registry == null) { registry = new HashMap<>(); this.context.putObject(CoreConstants.PATTERN_RULE_REGISTRY, registry); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringProfileAction.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringProfileAction.java index a9a1e0a51b..7479c9657e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringProfileAction.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringProfileAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,7 +71,7 @@ class SpringProfileAction extends Action implements InPlayListener { return false; } String[] profileNames = StringUtils - .trimArrayElements(StringUtils.commaDelimitedListToStringArray(attributes.getValue(NAME_ATTRIBUTE))); + .trimArrayElements(StringUtils.commaDelimitedListToStringArray(attributes.getValue(NAME_ATTRIBUTE))); if (profileNames.length == 0) { return false; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder.java index edde2446d0..ff5696f7b9 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -220,7 +220,7 @@ public class EntityManagerFactoryBuilder { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); if (EntityManagerFactoryBuilder.this.persistenceUnitManager != null) { entityManagerFactoryBean - .setPersistenceUnitManager(EntityManagerFactoryBuilder.this.persistenceUnitManager); + .setPersistenceUnitManager(EntityManagerFactoryBuilder.this.persistenceUnitManager); } if (this.persistenceUnit != null) { entityManagerFactoryBean.setPersistenceUnitName(this.persistenceUnit); @@ -247,8 +247,8 @@ public class EntityManagerFactoryBuilder { entityManagerFactoryBean.setBootstrapExecutor(EntityManagerFactoryBuilder.this.bootstrapExecutor); } if (EntityManagerFactoryBuilder.this.persistenceUnitPostProcessors != null) { - entityManagerFactoryBean.setPersistenceUnitPostProcessors( - EntityManagerFactoryBuilder.this.persistenceUnitPostProcessors); + entityManagerFactoryBean + .setPersistenceUnitPostProcessors(EntityManagerFactoryBuilder.this.persistenceUnitPostProcessors); } return entityManagerFactoryBean; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/JpaDatabaseInitializerDetector.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/JpaDatabaseInitializerDetector.java index 81da74c6a1..a91de42a90 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/JpaDatabaseInitializerDetector.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/JpaDatabaseInitializerDetector.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,7 +64,7 @@ class JpaDatabaseInitializerDetector extends AbstractBeansOfTypeDatabaseInitiali String initializerName = iterator.next(); BeanDefinition initializerDefinition = beanFactory.getBeanDefinition(initializerName); if (JpaDatabaseInitializerDetector.class.getName() - .equals(initializerDefinition.getAttribute(DatabaseInitializerDetector.class.getName()))) { + .equals(initializerDefinition.getAttribute(DatabaseInitializerDetector.class.getName()))) { iterator.remove(); jpaInitializers.add(initializerName); } 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 716839a444..f52d3b0b20 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -218,9 +218,11 @@ public final class ConnectionFactoryBuilder { String[] protocols = protocol.split(COLON, 2); String driverDelegate = protocols[0]; String protocolDelegate = (protocols.length != 2) ? "" : protocols[1]; - return ConnectionFactoryOptions.builder().from(options) - .option(ConnectionFactoryOptions.DRIVER, driverDelegate) - .option(ConnectionFactoryOptions.PROTOCOL, protocolDelegate).build(); + return ConnectionFactoryOptions.builder() + .from(options) + .option(ConnectionFactoryOptions.DRIVER, driverDelegate) + .option(ConnectionFactoryOptions.PROTOCOL, protocolDelegate) + .build(); } @SuppressWarnings("unchecked") @@ -229,36 +231,51 @@ public final class ConnectionFactoryBuilder { ConnectionPoolConfiguration.Builder builder = ConnectionPoolConfiguration.builder(connectionFactory); PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(options.getValue(PoolingConnectionFactoryProvider.BACKGROUND_EVICTION_INTERVAL)) - .as(this::toDuration).to(builder::backgroundEvictionInterval); - map.from(options.getValue(PoolingConnectionFactoryProvider.INITIAL_SIZE)).as(this::toInteger) - .to(builder::initialSize); - map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_SIZE)).as(this::toInteger) - .to(builder::maxSize); - map.from(options.getValue(PoolingConnectionFactoryProvider.ACQUIRE_RETRY)).as(this::toInteger) - .to(builder::acquireRetry); - map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_LIFE_TIME)).as(this::toDuration) - .to(builder::maxLifeTime); - map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_ACQUIRE_TIME)).as(this::toDuration) - .to(builder::maxAcquireTime); - map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_IDLE_TIME)).as(this::toDuration) - .to(builder::maxIdleTime); - map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_CREATE_CONNECTION_TIME)).as(this::toDuration) - .to(builder::maxCreateConnectionTime); - map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_VALIDATION_TIME)).as(this::toDuration) - .to(builder::maxValidationTime); - map.from(options.getValue(PoolingConnectionFactoryProvider.MIN_IDLE)).as(this::toInteger) - .to(builder::minIdle); + .as(this::toDuration) + .to(builder::backgroundEvictionInterval); + map.from(options.getValue(PoolingConnectionFactoryProvider.INITIAL_SIZE)) + .as(this::toInteger) + .to(builder::initialSize); + map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_SIZE)) + .as(this::toInteger) + .to(builder::maxSize); + map.from(options.getValue(PoolingConnectionFactoryProvider.ACQUIRE_RETRY)) + .as(this::toInteger) + .to(builder::acquireRetry); + map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_LIFE_TIME)) + .as(this::toDuration) + .to(builder::maxLifeTime); + map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_ACQUIRE_TIME)) + .as(this::toDuration) + .to(builder::maxAcquireTime); + map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_IDLE_TIME)) + .as(this::toDuration) + .to(builder::maxIdleTime); + map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_CREATE_CONNECTION_TIME)) + .as(this::toDuration) + .to(builder::maxCreateConnectionTime); + map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_VALIDATION_TIME)) + .as(this::toDuration) + .to(builder::maxValidationTime); + map.from(options.getValue(PoolingConnectionFactoryProvider.MIN_IDLE)) + .as(this::toInteger) + .to(builder::minIdle); map.from(options.getValue(PoolingConnectionFactoryProvider.POOL_NAME)).as(this::toString).to(builder::name); - map.from(options.getValue(PoolingConnectionFactoryProvider.PRE_RELEASE)).to((function) -> builder + map.from(options.getValue(PoolingConnectionFactoryProvider.PRE_RELEASE)) + .to((function) -> builder .preRelease((Function>) function)); - map.from(options.getValue(PoolingConnectionFactoryProvider.POST_ALLOCATE)).to((function) -> builder + map.from(options.getValue(PoolingConnectionFactoryProvider.POST_ALLOCATE)) + .to((function) -> builder .postAllocate((Function>) function)); - map.from(options.getValue(PoolingConnectionFactoryProvider.REGISTER_JMX)).as(this::toBoolean) - .to(builder::registerJmx); - map.from(options.getValue(PoolingConnectionFactoryProvider.VALIDATION_QUERY)).as(this::toString) - .to(builder::validationQuery); - map.from(options.getValue(PoolingConnectionFactoryProvider.VALIDATION_DEPTH)).as(this::toValidationDepth) - .to(builder::validationDepth); + map.from(options.getValue(PoolingConnectionFactoryProvider.REGISTER_JMX)) + .as(this::toBoolean) + .to(builder::registerJmx); + map.from(options.getValue(PoolingConnectionFactoryProvider.VALIDATION_QUERY)) + .as(this::toString) + .to(builder::validationQuery); + map.from(options.getValue(PoolingConnectionFactoryProvider.VALIDATION_DEPTH)) + .as(this::toValidationDepth) + .to(builder::validationDepth); return builder.build(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcher.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcher.java index a56626e873..1e7fbe44b1 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcher.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,7 +55,7 @@ public abstract class ApplicationContextRequestMatcher implements RequestMatc @Override public final boolean matches(HttpServletRequest request) { WebApplicationContext webApplicationContext = WebApplicationContextUtils - .getRequiredWebApplicationContext(request.getServletContext()); + .getRequiredWebApplicationContext(request.getServletContext()); if (ignoreApplicationContext(webApplicationContext)) { return false; } 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 ecaa8f8f27..60f1ebd4c2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,7 +69,7 @@ public class DatabaseInitializationDependencyConfigurer implements ImportBeanDef String name = DependsOnDatabaseInitializationPostProcessor.class.getName(); if (!registry.containsBeanDefinition(name)) { BeanDefinitionBuilder builder = BeanDefinitionBuilder - .rootBeanDefinition(DependsOnDatabaseInitializationPostProcessor.class); + .rootBeanDefinition(DependsOnDatabaseInitializationPostProcessor.class); registry.registerBeanDefinition(name, builder.getBeanDefinition()); } } @@ -104,7 +104,7 @@ public class DatabaseInitializationDependencyConfigurer implements ImportBeanDef for (String initializerBeanName : initializerBeanNamesBatch) { BeanDefinition beanDefinition = getBeanDefinition(initializerBeanName, beanFactory); beanDefinition - .setDependsOn(merge(beanDefinition.getDependsOn(), previousInitializerBeanNamesBatch)); + .setDependsOn(merge(beanDefinition.getDependsOn(), previousInitializerBeanNamesBatch)); } previousInitializerBeanNamesBatch = initializerBeanNamesBatch; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/Instantiator.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/Instantiator.java index a6d2ca1bfe..13410d81f1 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/Instantiator.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/Instantiator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,8 @@ import org.springframework.util.ReflectionUtils; public class Instantiator { private static final Comparator> CONSTRUCTOR_COMPARATOR = Comparator - .>comparingInt(Constructor::getParameterCount).reversed(); + .>comparingInt(Constructor::getParameterCount) + .reversed(); private static final FailureHandler throwingFailureHandler = (type, implementationName, failure) -> { throw new IllegalArgumentException("Unable to instantiate " + implementationName + " [" + type.getName() + "]", diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/LambdaSafe.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/LambdaSafe.java index 872204b3b2..21ec25238c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/LambdaSafe.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/LambdaSafe.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -299,8 +299,10 @@ public final class LambdaSafe { public Stream invokeAnd(Function invoker) { Function> mapper = (callbackInstance) -> invoke(callbackInstance, () -> invoker.apply(callbackInstance)); - return this.callbackInstances.stream().map(mapper).filter(InvocationResult::hasResult) - .map(InvocationResult::get); + return this.callbackInstances.stream() + .map(mapper) + .filter(InvocationResult::hasResult) + .map(InvocationResult::get); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java index 8bf50005f8..7b5e72aa04 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -663,8 +663,9 @@ public class RestTemplateBuilder { if (this.basicAuthentication == null && this.defaultHeaders.isEmpty() && this.requestCustomizers.isEmpty()) { return; } - restTemplate.getClientHttpRequestInitializers().add(new RestTemplateBuilderClientHttpRequestInitializer( - this.basicAuthentication, this.defaultHeaders, this.requestCustomizers)); + restTemplate.getClientHttpRequestInitializers() + .add(new RestTemplateBuilderClientHttpRequestInitializer(this.basicAuthentication, this.defaultHeaders, + this.requestCustomizers)); } @SuppressWarnings("unchecked") diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilderClientHttpRequestInitializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilderClientHttpRequestInitializer.java index 849f384b6d..596c2fab4b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilderClientHttpRequestInitializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilderClientHttpRequestInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +57,7 @@ class RestTemplateBuilderClientHttpRequestInitializer implements ClientHttpReque } this.defaultHeaders.forEach(headers::putIfAbsent); LambdaSafe.callbacks(RestTemplateRequestCustomizer.class, this.requestCustomizers, request) - .invoke((customizer) -> customizer.customize(request)); + .invoke((customizer) -> customizer.customize(request)); } } 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..61ba6d3b38 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,7 +55,7 @@ public interface WebServerApplicationContext extends ApplicationContext { */ static boolean hasServerNamespace(ApplicationContext context, String serverNamespace) { return (context instanceof WebServerApplicationContext) && ObjectUtils - .nullSafeEquals(((WebServerApplicationContext) context).getServerNamespace(), serverNamespace); + .nullSafeEquals(((WebServerApplicationContext) context).getServerNamespace(), serverNamespace); } /** diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/ForwardHeadersCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/ForwardHeadersCustomizer.java index a3c60ba856..0eeee2f537 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/ForwardHeadersCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/ForwardHeadersCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ class ForwardHeadersCustomizer implements JettyServerCustomizer { for (ConnectionFactory connectionFactory : connector.getConnectionFactories()) { if (connectionFactory instanceof HttpConfiguration.ConnectionFactory) { ((HttpConfiguration.ConnectionFactory) connectionFactory).getHttpConfiguration() - .addCustomizer(customizer); + .addCustomizer(customizer); } } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactory.java index 129f504fde..da5614a132 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -280,7 +280,7 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor private void addLocaleMappings(WebAppContext context) { getLocaleCharsetMappings() - .forEach((locale, charset) -> context.addLocaleEncoding(locale.toString(), charset.toString())); + .forEach((locale, charset) -> context.addLocaleEncoding(locale.toString(), charset.toString())); } private File getTempDirectory() { 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..f9217a38a7 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -200,8 +200,11 @@ public class JettyWebServer implements WebServer { } private String getContextPath() { - return Arrays.stream(this.server.getHandlers()).map(this::findContextHandler).filter(Objects::nonNull) - .map(ContextHandler::getContextPath).collect(Collectors.joining(" ")); + return Arrays.stream(this.server.getHandlers()) + .map(this::findContextHandler) + .filter(Objects::nonNull) + .map(ContextHandler::getContextPath) + .collect(Collectors.joining(" ")); } private ContextHandler findContextHandler(Handler handler) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizer.java index 16b53d44a0..9ce9b4012b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -121,7 +121,7 @@ class SslServerCustomizer implements JettyServerCustomizer { // Jetty 10 try { return SslConnectionFactory.class.getConstructor(SslContextFactory.Server.class, String.class) - .newInstance(sslContextFactory, protocol); + .newInstance(sslContextFactory, protocol); } catch (Exception ex2) { throw new RuntimeException(ex2); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/CompressionCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/CompressionCustomizer.java index 667276423f..70fcb4d8bf 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/CompressionCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/CompressionCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,8 +67,9 @@ final class CompressionCustomizer implements NettyServerCustomizer { if (ObjectUtils.isEmpty(mimeTypeValues)) { return ALWAYS_COMPRESS; } - List mimeTypes = Arrays.stream(mimeTypeValues).map(MimeTypeUtils::parseMimeType) - .collect(Collectors.toList()); + List mimeTypes = Arrays.stream(mimeTypeValues) + .map(MimeTypeUtils::parseMimeType) + .collect(Collectors.toList()); return (request, response) -> { String contentType = response.responseHeaders().get(HttpHeaderNames.CONTENT_TYPE); if (!StringUtils.hasLength(contentType)) { @@ -91,7 +92,7 @@ final class CompressionCustomizer implements NettyServerCustomizer { return (request, response) -> { HttpHeaders headers = request.requestHeaders(); return Arrays.stream(excludedUserAgents) - .noneMatch((candidate) -> headers.contains(HttpHeaderNames.USER_AGENT, candidate, true)); + .noneMatch((candidate) -> headers.contains(HttpHeaderNames.USER_AGENT, candidate, true)); }; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/SslServerCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/SslServerCustomizer.java index 5fe36066db..9ef421bc57 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/SslServerCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/SslServerCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -142,7 +142,7 @@ public class SslServerCustomizer implements NettyServerCustomizer { try { KeyStore store = getTrustStore(ssl, sslStoreProvider); TrustManagerFactory trustManagerFactory = TrustManagerFactory - .getInstance(TrustManagerFactory.getDefaultAlgorithm()); + .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(store); return trustManagerFactory; } @@ -240,8 +240,11 @@ public class SslServerCustomizer implements NettyServerCustomizer { @Override protected KeyManager[] engineGetKeyManagers() { - return Arrays.stream(this.delegate.getKeyManagers()).filter(X509ExtendedKeyManager.class::isInstance) - .map(X509ExtendedKeyManager.class::cast).map(this::wrap).toArray(KeyManager[]::new); + return Arrays.stream(this.delegate.getKeyManagers()) + .filter(X509ExtendedKeyManager.class::isInstance) + .map(X509ExtendedKeyManager.class::cast) + .map(this::wrap) + .toArray(KeyManager[]::new); } private ConfigurableAliasKeyManager wrap(X509ExtendedKeyManager keyManager) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactory.java index 6a76e0be7b..9d9e78e777 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -210,8 +210,9 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac @SuppressWarnings("unchecked") private void invokeProtocolHandlerCustomizers(ProtocolHandler protocolHandler) { - LambdaSafe.callbacks(TomcatProtocolHandlerCustomizer.class, this.tomcatProtocolHandlerCustomizers, - protocolHandler).invoke((customizer) -> customizer.customize(protocolHandler)); + LambdaSafe + .callbacks(TomcatProtocolHandlerCustomizer.class, this.tomcatProtocolHandlerCustomizers, protocolHandler) + .invoke((customizer) -> customizer.customize(protocolHandler)); } private void customizeProtocol(AbstractProtocol protocol) { 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 e1a23f5935..56bf1cc335 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -310,8 +310,9 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto private void addJasperInitializer(TomcatEmbeddedContext context) { try { ServletContainerInitializer initializer = (ServletContainerInitializer) ClassUtils - .forName("org.apache.jasper.servlet.JasperInitializer", null).getDeclaredConstructor() - .newInstance(); + .forName("org.apache.jasper.servlet.JasperInitializer", null) + .getDeclaredConstructor() + .newInstance(); context.addServletContainerInitializer(initializer, null); } catch (Exception ex) { @@ -356,8 +357,9 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto @SuppressWarnings("unchecked") private void invokeProtocolHandlerCustomizers(ProtocolHandler protocolHandler) { - LambdaSafe.callbacks(TomcatProtocolHandlerCustomizer.class, this.tomcatProtocolHandlerCustomizers, - protocolHandler).invoke((customizer) -> customizer.customize(protocolHandler)); + LambdaSafe + .callbacks(TomcatProtocolHandlerCustomizer.class, this.tomcatProtocolHandlerCustomizers, protocolHandler) + .invoke((customizer) -> customizer.customize(protocolHandler)); } private void customizeSsl(Connector connector) { @@ -429,7 +431,7 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto List suppliers = new ArrayList<>(); if (sessionSameSite != null) { suppliers.add(CookieSameSiteSupplier.of(sessionSameSite) - .whenHasName(() -> SessionConfig.getSessionCookieName(context))); + .whenHasName(() -> SessionConfig.getSessionCookieName(context))); } if (!CollectionUtils.isEmpty(getCookieSameSiteSuppliers())) { suppliers.addAll(getCookieSameSiteSuppliers()); @@ -860,9 +862,10 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto @Override public Set listWebAppPaths(String path) { - return this.delegate.listWebAppPaths(path).stream() - .filter((webAppPath) -> !webAppPath.startsWith("/org/springframework/boot")) - .collect(Collectors.toSet()); + return this.delegate.listWebAppPaths(path) + .stream() + .filter((webAppPath) -> !webAppPath.startsWith("/org/springframework/boot")) + .collect(Collectors.toSet()); } @Override 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..ada699327f 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -368,9 +368,11 @@ public class TomcatWebServer implements WebServer { } private String getContextPath() { - return Arrays.stream(this.tomcat.getHost().findChildren()).filter(TomcatEmbeddedContext.class::isInstance) - .map(TomcatEmbeddedContext.class::cast).map(TomcatEmbeddedContext::getPath) - .collect(Collectors.joining(" ")); + return Arrays.stream(this.tomcat.getHost().findChildren()) + .filter(TomcatEmbeddedContext.class::isInstance) + .map(TomcatEmbeddedContext.class::cast) + .map(TomcatEmbeddedContext::getPath) + .collect(Collectors.joining(" ")); } /** diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizer.java index d8615085b4..6060827395 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -112,7 +112,7 @@ class SslBuilderCustomizer implements UndertowBuilderCustomizer { KeyStore keyStore = getKeyStore(ssl, sslStoreProvider); SslConfigurationValidator.validateKeyAlias(keyStore, ssl.getKeyAlias()); KeyManagerFactory keyManagerFactory = KeyManagerFactory - .getInstance(KeyManagerFactory.getDefaultAlgorithm()); + .getInstance(KeyManagerFactory.getDefaultAlgorithm()); String keyPassword = (sslStoreProvider != null) ? sslStoreProvider.getKeyPassword() : null; if (keyPassword == null) { keyPassword = (ssl.getKeyPassword() != null) ? ssl.getKeyPassword() : ssl.getKeyStorePassword(); @@ -150,7 +150,7 @@ class SslBuilderCustomizer implements UndertowBuilderCustomizer { try { KeyStore store = getTrustStore(ssl, sslStoreProvider); TrustManagerFactory trustManagerFactory = TrustManagerFactory - .getInstance(TrustManagerFactory.getDefaultAlgorithm()); + .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(store); return trustManagerFactory.getTrustManagers(); } 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 f60c40b486..f35601bd0e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -359,8 +359,8 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac } private void addLocaleMappings(DeploymentInfo deployment) { - getLocaleCharsetMappings().forEach( - (locale, charset) -> deployment.addLocaleCharsetMapping(locale.toString(), charset.toString())); + getLocaleCharsetMappings() + .forEach((locale, charset) -> deployment.addLocaleCharsetMapping(locale.toString(), charset.toString())); } private void registerServletContainerInitializerToDriveServletContextInitializers(DeploymentInfo deployment, diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServerFactoryDelegate.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServerFactoryDelegate.java index dc7482d486..084dbde662 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServerFactoryDelegate.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServerFactoryDelegate.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -164,7 +164,7 @@ class UndertowWebServerFactoryDelegate { } if (ssl != null && ssl.isEnabled()) { new SslBuilderCustomizer(factory.getPort(), address, ssl, factory.getOrCreateSslStoreProvider()) - .customize(builder); + .customize(builder); } else { builder.addHttpListener(port, (address != null) ? address.getHostAddress() : "0.0.0.0"); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/WebServerManager.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/WebServerManager.java index 76c300250e..b8b99552f3 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/WebServerManager.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/WebServerManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ class WebServerManager { this.handler.initializeHandler(); this.webServer.start(); this.applicationContext - .publishEvent(new ReactiveWebServerInitializedEvent(this.webServer, this.applicationContext)); + .publishEvent(new ReactiveWebServerInitializedEvent(this.webServer, this.applicationContext)); } void shutDownGracefully(GracefulShutdownCallback callback) { 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 9e825504d0..ff652ded83 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -88,7 +88,8 @@ public class DefaultErrorAttributes implements ErrorAttributes { errorAttributes.put("path", request.path()); Throwable error = getError(request); MergedAnnotation responseStatusAnnotation = MergedAnnotations - .from(error.getClass(), SearchStrategy.TYPE_HIERARCHY).get(ResponseStatus.class); + .from(error.getClass(), SearchStrategy.TYPE_HIERARCHY) + .get(ResponseStatus.class); HttpStatus errorStatus = determineHttpStatus(error, responseStatusAnnotation); errorAttributes.put("status", errorStatus.value()); errorAttributes.put("error", errorStatus.getReasonPhrase()); @@ -151,7 +152,7 @@ public class DefaultErrorAttributes implements ErrorAttributes { Optional error = request.attribute(ERROR_INTERNAL_ATTRIBUTE); error.ifPresent((value) -> request.attributes().putIfAbsent(ErrorAttributes.ERROR_ATTRIBUTE, value)); return (Throwable) error - .orElseThrow(() -> new IllegalStateException("Missing exception attribute in ServerWebExchange")); + .orElseThrow(() -> new IllegalStateException("Missing exception attribute in ServerWebExchange")); } @Override diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/result/view/MustacheView.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/result/view/MustacheView.java index cdd0b26770..34d2346ee8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/result/view/MustacheView.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/result/view/MustacheView.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,7 +79,7 @@ public class MustacheView extends AbstractUrlBasedView { Resource resource = resolveResource(); if (resource == null) { return Mono - .error(new IllegalStateException("Could not find Mustache template with URL [" + getUrl() + "]")); + .error(new IllegalStateException("Could not find Mustache template with URL [" + getUrl() + "]")); } DataBuffer dataBuffer = exchange.getResponse().bufferFactory().allocateBuffer(); try (Reader reader = getReader(resource)) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/LocalServerPort.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/LocalServerPort.java index c694be7f69..484b93d792 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/LocalServerPort.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/LocalServerPort.java @@ -28,9 +28,9 @@ import org.springframework.beans.factory.annotation.Value; * Annotation at the field or method/constructor parameter level that injects the HTTP * port that got allocated at runtime. Provides a convenient alternative for * @Value("${local.server.port}"). + * * @deprecated since 2.7.0 for removal in 3.0.0 in favor of * {@code org.springframework.boot.test.web.server.LocalServerPort} - * * @author Anand Shah * @author Stephane Nicoll * @since 2.0.0 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..be6b2e5851 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-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,8 +68,8 @@ public class WebServerFactoryCustomizerBeanPostProcessor implements BeanPostProc @SuppressWarnings("unchecked") private void postProcessBeforeInitialization(WebServerFactory webServerFactory) { LambdaSafe.callbacks(WebServerFactoryCustomizer.class, getCustomizers(), webServerFactory) - .withLogger(WebServerFactoryCustomizerBeanPostProcessor.class) - .invoke((customizer) -> customizer.customize(webServerFactory)); + .withLogger(WebServerFactoryCustomizerBeanPostProcessor.class) + .invoke((customizer) -> customizer.customize(webServerFactory)); } private Collection> getCustomizers() { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentHandler.java index d981571d04..ace35a20c8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentHandler.java @@ -70,7 +70,7 @@ abstract class ServletComponentHandler { void handle(AnnotatedBeanDefinition beanDefinition, BeanDefinitionRegistry registry) { Map attributes = beanDefinition.getMetadata() - .getAnnotationAttributes(this.annotationType.getName()); + .getAnnotationAttributes(this.annotationType.getName()); if (attributes != null) { doHandle(attributes, beanDefinition, registry); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrar.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrar.java index accda1edaa..75a38d622d 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrar.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ class ServletComponentScanRegistrar implements ImportBeanDefinitionRegistrar { private void updatePostProcessor(BeanDefinitionRegistry registry, Set packagesToScan) { ServletComponentRegisteringPostProcessorBeanDefinition definition = (ServletComponentRegisteringPostProcessorBeanDefinition) registry - .getBeanDefinition(BEAN_NAME); + .getBeanDefinition(BEAN_NAME); definition.addPackageNames(packagesToScan); } @@ -66,7 +66,7 @@ class ServletComponentScanRegistrar implements ImportBeanDefinitionRegistrar { private Set getPackagesToScan(AnnotationMetadata metadata) { AnnotationAttributes attributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(ServletComponentScan.class.getName())); + .fromMap(metadata.getAnnotationAttributes(ServletComponentScan.class.getName())); String[] basePackages = attributes.getStringArray("basePackages"); Class[] basePackageClasses = attributes.getClassArray("basePackageClasses"); Set packagesToScan = new LinkedHashSet<>(Arrays.asList(basePackages)); 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 bd0cc2645e..d1e1050157 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,9 +85,10 @@ public class ServletContextInitializerBeans extends AbstractCollection sortedInitializers = this.initializers.values().stream() - .flatMap((value) -> value.stream().sorted(AnnotationAwareOrderComparator.INSTANCE)) - .collect(Collectors.toList()); + List sortedInitializers = this.initializers.values() + .stream() + .flatMap((value) -> value.stream().sorted(AnnotationAwareOrderComparator.INSTANCE)) + .collect(Collectors.toList()); this.sortedList = Collections.unmodifiableList(sortedInitializers); logMappings(this.initializers); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebListenerHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebListenerHandler.java index 00463e4401..894be535de 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebListenerHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebListenerHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ class WebListenerHandler extends ServletComponentHandler { protected void doHandle(Map attributes, AnnotatedBeanDefinition beanDefinition, BeanDefinitionRegistry registry) { BeanDefinitionBuilder builder = BeanDefinitionBuilder - .rootBeanDefinition(ServletComponentWebListenerRegistrar.class); + .rootBeanDefinition(ServletComponentWebListenerRegistrar.class); builder.addConstructorArgValue(beanDefinition.getBeanClassName()); registry.registerBeanDefinition(beanDefinition.getBeanClassName() + "Registrar", builder.getBeanDefinition()); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebServletHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebServletHandler.java index 815e57344f..ea6fd83e1b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebServletHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebServletHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,7 +61,7 @@ class WebServletHandler extends ServletComponentHandler { private MultipartConfigElement determineMultipartConfig(AnnotatedBeanDefinition beanDefinition) { Map attributes = beanDefinition.getMetadata() - .getAnnotationAttributes(MultipartConfig.class.getName()); + .getAnnotationAttributes(MultipartConfig.class.getName()); if (attributes == null) { return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/WebServerStartStopLifecycle.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/WebServerStartStopLifecycle.java index c5c07627be..cd4d0568b0 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/WebServerStartStopLifecycle.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/WebServerStartStopLifecycle.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ class WebServerStartStopLifecycle implements SmartLifecycle { this.webServer.start(); this.running = true; this.applicationContext - .publishEvent(new ServletWebServerInitializedEvent(this.webServer, this.applicationContext)); + .publishEvent(new ServletWebServerInitializedEvent(this.webServer, this.applicationContext)); } @Override diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/StaticResourceJars.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/StaticResourceJars.java index d6f8438a32..53001b48d9 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/StaticResourceJars.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/StaticResourceJars.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,8 @@ class StaticResourceJars { } else { return getUrlsFrom(Stream.of(ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) - .map(this::toUrl).toArray(URL[]::new)); + .map(this::toUrl) + .toArray(URL[]::new)); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilder.java index 4c6a3981fd..f01cc773a6 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -487,7 +487,7 @@ public class WebServiceTemplateBuilder { } else if (!CollectionUtils.isEmpty(this.messageSenders.getMessageSenders())) { webServiceTemplate - .setMessageSenders(this.messageSenders.getMessageSenders().toArray(new WebServiceMessageSender[0])); + .setMessageSenders(this.messageSenders.getMessageSenders().toArray(new WebServiceMessageSender[0])); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/AbstractApplicationEnvironmentTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/AbstractApplicationEnvironmentTests.java index 14bc3dedf4..a338f4a915 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/AbstractApplicationEnvironmentTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/AbstractApplicationEnvironmentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,8 @@ public abstract class AbstractApplicationEnvironmentTests { void getActiveProfilesDoesNotResolveProperty() { StandardEnvironment environment = createEnvironment(); new MockPropertySource().withProperty("", ""); - environment.getPropertySources().addFirst( - new MockPropertySource().withProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "test")); + environment.getPropertySources() + .addFirst(new MockPropertySource().withProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "test")); assertThat(environment.getActiveProfiles()).isEmpty(); } @@ -48,8 +48,9 @@ public abstract class AbstractApplicationEnvironmentTests { void getDefaultProfilesDoesNotResolveProperty() { StandardEnvironment environment = createEnvironment(); new MockPropertySource().withProperty("", ""); - environment.getPropertySources().addFirst( - new MockPropertySource().withProperty(AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME, "test")); + environment.getPropertySources() + .addFirst( + new MockPropertySource().withProperty(AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME, "test")); assertThat(environment.getDefaultProfiles()).containsExactly("default"); } @@ -57,7 +58,7 @@ public abstract class AbstractApplicationEnvironmentTests { void propertyResolverIsOptimizedForConfigurationProperties() { StandardEnvironment environment = createEnvironment(); ConfigurablePropertyResolver expected = ConfigurationPropertySources - .createPropertyResolver(new MutablePropertySources()); + .createPropertyResolver(new MutablePropertySources()); assertThat(environment).extracting("propertyResolver").hasSameClassAs(expected); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BannerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BannerTests.java index 4c39c3f8da..8ab5fa2b7e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BannerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BannerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -98,12 +98,12 @@ class BannerTests { this.context = application.run(); Banner printedBanner = (Banner) this.context.getBean("springBootBanner"); assertThat(printedBanner).hasFieldOrPropertyWithValue("banner", banner); - then(banner).should().printBanner(any(Environment.class), this.sourceClassCaptor.capture(), - any(PrintStream.class)); + then(banner).should() + .printBanner(any(Environment.class), this.sourceClassCaptor.capture(), any(PrintStream.class)); reset(banner); printedBanner.printBanner(this.context.getEnvironment(), null, System.out); - then(banner).should().printBanner(any(Environment.class), eq(this.sourceClassCaptor.getValue()), - any(PrintStream.class)); + then(banner).should() + .printBanner(any(Environment.class), eq(this.sourceClassCaptor.getValue()), any(PrintStream.class)); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java index 31b5b892ec..c69e27f9c8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ class DefaultApplicationArgumentsTests { @Test void argumentsMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new DefaultApplicationArguments((String[]) null)) - .withMessageContaining("Args must not be null"); + .withMessageContaining("Args must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultBootstrapContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultBootstrapContextTests.java index 05dff44cac..d111446e3a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultBootstrapContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultBootstrapContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,13 +51,13 @@ class DefaultBootstrapContextTests { @Test void registerWhenTypeIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.context.register(null, InstanceSupplier.of(1))) - .withMessage("Type must not be null"); + .withMessage("Type must not be null"); } @Test void registerWhenRegistrationIsNullThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.context.register(Integer.class, null)) - .withMessage("InstanceSupplier must not be null"); + .withMessage("InstanceSupplier must not be null"); } @Test @@ -80,8 +80,8 @@ class DefaultBootstrapContextTests { this.context.register(Integer.class, InstanceSupplier.from(this.counter::getAndIncrement)); this.context.get(Integer.class); assertThatIllegalStateException() - .isThrownBy(() -> this.context.register(Integer.class, InstanceSupplier.of(100))) - .withMessage("java.lang.Integer has already been created"); + .isThrownBy(() -> this.context.register(Integer.class, InstanceSupplier.of(100))) + .withMessage("java.lang.Integer has already been created"); } @Test @@ -98,8 +98,8 @@ class DefaultBootstrapContextTests { this.context.register(Integer.class, InstanceSupplier.from(this.counter::getAndIncrement)); this.context.get(Integer.class); assertThatIllegalStateException() - .isThrownBy(() -> this.context.register(Integer.class, InstanceSupplier.of(100))) - .withMessage("java.lang.Integer has already been created"); + .isThrownBy(() -> this.context.register(Integer.class, InstanceSupplier.of(100))) + .withMessage("java.lang.Integer has already been created"); } @Test @@ -155,7 +155,7 @@ class DefaultBootstrapContextTests { void getWhenNoRegistrationThrowsIllegalStateException() { this.context.register(Number.class, InstanceSupplier.of(1)); assertThatIllegalStateException().isThrownBy(() -> this.context.get(Long.class)) - .withMessageContaining("has not been registered"); + .withMessageContaining("has not been registered"); } @Test @@ -247,8 +247,9 @@ class DefaultBootstrapContextTests { this.context.addCloseListener(listener); assertThat(listener).wasNotCalled(); this.context.close(this.applicationContext); - assertThat(listener).wasCalledOnlyOnce().hasBootstrapContextSameAs(this.context) - .hasApplicationContextSameAs(this.applicationContext); + assertThat(listener).wasCalledOnlyOnce() + .hasBootstrapContextSameAs(this.context) + .hasApplicationContextSameAs(this.applicationContext); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java index 0e418995a6..725396f8db 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ class EnvironmentConverterTests { AbstractEnvironment originalEnvironment = new MockEnvironment(); originalEnvironment.setActiveProfiles("activeProfile1", "activeProfile2"); ConfigurableEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(originalEnvironment, StandardEnvironment.class); + .convertEnvironmentIfNecessary(originalEnvironment, StandardEnvironment.class); assertThat(convertedEnvironment.getActiveProfiles()).containsExactly("activeProfile1", "activeProfile2"); } @@ -58,7 +58,7 @@ class EnvironmentConverterTests { ConfigurableConversionService conversionService = mock(ConfigurableConversionService.class); originalEnvironment.setConversionService(conversionService); ConfigurableEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(originalEnvironment, StandardEnvironment.class); + .convertEnvironmentIfNecessary(originalEnvironment, StandardEnvironment.class); assertThat(convertedEnvironment.getConversionService()).isEqualTo(conversionService); } @@ -66,7 +66,7 @@ class EnvironmentConverterTests { void envClassSameShouldReturnEnvironmentUnconverted() { StandardEnvironment standardEnvironment = new StandardEnvironment(); ConfigurableEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(standardEnvironment, StandardEnvironment.class); + .convertEnvironmentIfNecessary(standardEnvironment, StandardEnvironment.class); assertThat(convertedEnvironment).isSameAs(standardEnvironment); } @@ -74,7 +74,7 @@ class EnvironmentConverterTests { void standardServletEnvironmentIsConverted() { StandardServletEnvironment standardServletEnvironment = new StandardServletEnvironment(); ConfigurableEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(standardServletEnvironment, StandardEnvironment.class); + .convertEnvironmentIfNecessary(standardServletEnvironment, StandardEnvironment.class); assertThat(convertedEnvironment).isNotSameAs(standardServletEnvironment); } @@ -82,7 +82,7 @@ class EnvironmentConverterTests { void servletPropertySourcesAreNotCopiedOverIfNotWebEnvironment() { StandardServletEnvironment standardServletEnvironment = new StandardServletEnvironment(); ConfigurableEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(standardServletEnvironment, StandardEnvironment.class); + .convertEnvironmentIfNecessary(standardServletEnvironment, StandardEnvironment.class); assertThat(convertedEnvironment).isNotSameAs(standardServletEnvironment); Set names = new HashSet<>(); for (PropertySource propertySource : convertedEnvironment.getPropertySources()) { @@ -97,7 +97,7 @@ class EnvironmentConverterTests { void envClassSameShouldReturnEnvironmentUnconvertedEvenForWeb() { StandardServletEnvironment standardServletEnvironment = new StandardServletEnvironment(); ConfigurableEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(standardServletEnvironment, StandardServletEnvironment.class); + .convertEnvironmentIfNecessary(standardServletEnvironment, StandardServletEnvironment.class); assertThat(convertedEnvironment).isSameAs(standardServletEnvironment); } @@ -105,7 +105,7 @@ class EnvironmentConverterTests { void servletPropertySourcesArePresentWhenTypeToConvertIsWeb() { StandardEnvironment standardEnvironment = new StandardEnvironment(); ConfigurableEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(standardEnvironment, StandardServletEnvironment.class); + .convertEnvironmentIfNecessary(standardEnvironment, StandardServletEnvironment.class); assertThat(convertedEnvironment).isNotSameAs(standardEnvironment); Set names = new HashSet<>(); for (PropertySource propertySource : convertedEnvironment.getPropertySources()) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java index 0512785283..388e442059 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ class ExitCodeGeneratorsTests { @Test void addWhenGeneratorIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ExitCodeGenerators().add(null)) - .withMessageContaining("Generator must not be null"); + .withMessageContaining("Generator must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/IgnoringXmlBeanDefinitionLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/IgnoringXmlBeanDefinitionLoaderTests.java index 4713977792..33ce10a8cf 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/IgnoringXmlBeanDefinitionLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/IgnoringXmlBeanDefinitionLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,9 +42,10 @@ class IgnoringXmlBeanDefinitionLoaderTests { @Test void whenXmlSupportIsDisabledXmlSourcesAreRejected() { assertThatExceptionOfType(BeanDefinitionStoreException.class) - .isThrownBy(() -> new BeanDefinitionLoader(new StaticApplicationContext(), - "classpath:org/springframework/boot/sample-beans.xml").load()) - .withMessage("Cannot load XML bean definitions when XML support is disabled"); + .isThrownBy(() -> new BeanDefinitionLoader(new StaticApplicationContext(), + "classpath:org/springframework/boot/sample-beans.xml") + .load()) + .withMessage("Cannot load XML bean definitions when XML support is disabled"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationNoWebTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationNoWebTests.java index aa2d1bff30..5e8a430303 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationNoWebTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationNoWebTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ class SpringApplicationNoWebTests { void specificApplicationContextClass() { SpringApplication application = new SpringApplication(ExampleConfig.class); application - .setApplicationContextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)); + .setApplicationContextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)); ConfigurableApplicationContext context = application.run(); assertThat(context).isInstanceOf(StaticApplicationContext.class); context.close(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationShutdownHookInstance.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationShutdownHookInstance.java index 1c3f068ff1..c08862bf7c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationShutdownHookInstance.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationShutdownHookInstance.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,7 +77,7 @@ public final class SpringApplicationShutdownHookInstance implements AssertProvid private AbstractBooleanAssert assertThatIsApplicationContextRegistered( ConfigurableApplicationContext context) { return Assertions.assertThat(this.actual.isApplicationContextRegistered(context)) - .as("ApplicationContext registered with shutdown hook"); + .as("ApplicationContext registered with shutdown hook"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationShutdownHookTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationShutdownHookTests.java index 42b8eac002..133f5acab8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationShutdownHookTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationShutdownHookTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -128,7 +128,7 @@ class SpringApplicationShutdownHookTests { void addHandlerActionWhenNullThrowsException() { TestSpringApplicationShutdownHook shutdownHook = new TestSpringApplicationShutdownHook(); assertThatIllegalArgumentException().isThrownBy(() -> shutdownHook.getHandlers().add(null)) - .withMessage("Action must not be null"); + .withMessage("Action must not be null"); } @Test @@ -137,14 +137,14 @@ class SpringApplicationShutdownHookTests { shutdownHook.run(); Runnable handlerAction = new TestHandlerAction(new ArrayList<>()); assertThatIllegalStateException().isThrownBy(() -> shutdownHook.getHandlers().add(handlerAction)) - .withMessage("Shutdown in progress"); + .withMessage("Shutdown in progress"); } @Test void removeHandlerActionWhenNullThrowsException() { TestSpringApplicationShutdownHook shutdownHook = new TestSpringApplicationShutdownHook(); assertThatIllegalArgumentException().isThrownBy(() -> shutdownHook.getHandlers().remove(null)) - .withMessage("Action must not be null"); + .withMessage("Action must not be null"); } @Test @@ -154,7 +154,7 @@ class SpringApplicationShutdownHookTests { shutdownHook.getHandlers().add(handlerAction); shutdownHook.run(); assertThatIllegalStateException().isThrownBy(() -> shutdownHook.getHandlers().remove(handlerAction)) - .withMessage("Shutdown in progress"); + .withMessage("Shutdown in progress"); } @Test @@ -164,7 +164,7 @@ class SpringApplicationShutdownHookTests { shutdownHook.registerApplicationContext(context); context.refresh(); assertThatThrownBy(() -> shutdownHook.deregisterFailedApplicationContext(context)) - .isInstanceOf(IllegalStateException.class); + .isInstanceOf(IllegalStateException.class); assertThat(shutdownHook.isApplicationContextRegistered(context)).isTrue(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java index 7036811127..72ffcc9f42 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -198,20 +198,20 @@ class SpringApplicationTests { @Test void sourcesMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new SpringApplication((Class[]) null).run()) - .withMessageContaining("PrimarySources must not be null"); + .withMessageContaining("PrimarySources must not be null"); } @Test void sourcesMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new SpringApplication().run()) - .withMessageContaining("Sources must not be empty"); + .withMessageContaining("Sources must not be empty"); } @Test void sourcesMustBeAccessible() { assertThatIllegalArgumentException() - .isThrownBy(() -> new SpringApplication(InaccessibleConfiguration.class).run()) - .withMessageContaining("No visible constructors"); + .isThrownBy(() -> new SpringApplication(InaccessibleConfiguration.class).run()) + .withMessageContaining("No visible constructors"); } @Test @@ -271,7 +271,7 @@ class SpringApplicationTests { application.setEnvironment(environment); this.context = application.run(); assertThat(output) - .contains("No active profile set, falling back to 2 default profiles: \"p0,p1\", \"default\""); + .contains("No active profile set, falling back to 2 default profiles: \"p0,p1\", \"default\""); } @Test @@ -365,7 +365,7 @@ class SpringApplicationTests { void specificApplicationContextFactory() { SpringApplication application = new SpringApplication(ExampleConfig.class); application - .setApplicationContextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)); + .setApplicationContextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)); this.context = application.run(); assertThat(this.context).isInstanceOf(StaticApplicationContext.class); } @@ -376,7 +376,7 @@ class SpringApplicationTests { application.setWebApplicationType(WebApplicationType.NONE); final AtomicReference reference = new AtomicReference<>(); application.setInitializers(Collections - .singletonList((ApplicationContextInitializer) reference::set)); + .singletonList((ApplicationContextInitializer) reference::set)); this.context = application.run("--foo=bar"); assertThat(this.context).isSameAs(reference.get()); // Custom initializers do not switch off the defaults @@ -419,10 +419,10 @@ class SpringApplicationTests { then(listener).should(inOrder).onApplicationEvent(isA(ContextRefreshedEvent.class)); then(listener).should(inOrder).onApplicationEvent(isA(ApplicationStartedEvent.class)); then(listener).should(inOrder) - .onApplicationEvent(argThat(isAvailabilityChangeEventWithState(LivenessState.CORRECT))); + .onApplicationEvent(argThat(isAvailabilityChangeEventWithState(LivenessState.CORRECT))); then(listener).should(inOrder).onApplicationEvent(isA(ApplicationReadyEvent.class)); then(listener).should(inOrder) - .onApplicationEvent(argThat(isAvailabilityChangeEventWithState(ReadinessState.ACCEPTING_TRAFFIC))); + .onApplicationEvent(argThat(isAvailabilityChangeEventWithState(ReadinessState.ACCEPTING_TRAFFIC))); inOrder.verifyNoMoreInteractions(); } @@ -553,7 +553,7 @@ class SpringApplicationTests { application.setWebApplicationType(WebApplicationType.NONE); ConfigurableEnvironment environment = new StandardEnvironment(); environment.getPropertySources() - .addFirst(new MapPropertySource("commandLineArgs", Collections.singletonMap("foo", "original"))); + .addFirst(new MapPropertySource("commandLineArgs", Collections.singletonMap("foo", "original"))); application.setEnvironment(environment); this.context = application.run("--foo=bar", "--bar=foo"); assertThat(environment).has(matchingPropertySource(CompositePropertySource.class, "commandLineArgs")); @@ -561,13 +561,13 @@ class SpringApplicationTests { // New command line properties take precedence assertThat(environment.getProperty("foo")).isEqualTo("bar"); CompositePropertySource composite = (CompositePropertySource) environment.getPropertySources() - .get("commandLineArgs"); + .get("commandLineArgs"); assertThat(composite.getPropertySources()).hasSize(2); - assertThat(composite.getPropertySources()).first().matches( - (source) -> source.getName().equals("springApplicationCommandLineArgs"), - "is named springApplicationCommandLineArgs"); + assertThat(composite.getPropertySources()).first() + .matches((source) -> source.getName().equals("springApplicationCommandLineArgs"), + "is named springApplicationCommandLineArgs"); assertThat(composite.getPropertySources()).element(1) - .matches((source) -> source.getName().equals("commandLineArgs"), "is named commandLineArgs"); + .matches((source) -> source.getName().equals("commandLineArgs"), "is named commandLineArgs"); } @Test @@ -641,9 +641,9 @@ class SpringApplicationTests { application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); assertThat(this.context.getBeanFactory().getConversionService()) - .isInstanceOf(ApplicationConversionService.class); + .isInstanceOf(ApplicationConversionService.class); assertThat(this.context.getEnvironment().getConversionService()) - .isInstanceOf(ApplicationConversionService.class); + .isInstanceOf(ApplicationConversionService.class); } @Test @@ -654,7 +654,7 @@ class SpringApplicationTests { this.context = application.run(); assertThat(this.context.getBeanFactory().getConversionService()).isNull(); assertThat(this.context.getEnvironment().getConversionService()) - .isNotInstanceOf(ApplicationConversionService.class); + .isNotInstanceOf(ApplicationConversionService.class); } @Test @@ -890,10 +890,13 @@ class SpringApplicationTests { @Test void defaultPropertiesShouldBeMerged() { MockEnvironment environment = new MockEnvironment(); - environment.getPropertySources().addFirst( - new MapPropertySource(DefaultPropertiesPropertySource.NAME, Collections.singletonMap("bar", "foo"))); + environment.getPropertySources() + .addFirst(new MapPropertySource(DefaultPropertiesPropertySource.NAME, + Collections.singletonMap("bar", "foo"))); SpringApplication application = new SpringApplicationBuilder(ExampleConfig.class).environment(environment) - .properties("baz=bing").web(WebApplicationType.NONE).build(); + .properties("baz=bing") + .web(WebApplicationType.NONE) + .build(); this.context = application.run(); assertThat(getEnvironment().getProperty("bar")).isEqualTo("foo"); assertThat(getEnvironment().getProperty("baz")).isEqualTo("bing"); @@ -957,10 +960,10 @@ class SpringApplicationTests { then(listener).should(inOrder).onApplicationEvent(isA(ContextRefreshedEvent.class)); then(listener).should(inOrder).onApplicationEvent(isA(ApplicationStartedEvent.class)); then(listener).should(inOrder) - .onApplicationEvent(argThat(isAvailabilityChangeEventWithState(LivenessState.CORRECT))); + .onApplicationEvent(argThat(isAvailabilityChangeEventWithState(LivenessState.CORRECT))); then(listener).should(inOrder).onApplicationEvent(isA(ApplicationReadyEvent.class)); then(listener).should(inOrder) - .onApplicationEvent(argThat(isAvailabilityChangeEventWithState(ReadinessState.ACCEPTING_TRAFFIC))); + .onApplicationEvent(argThat(isAvailabilityChangeEventWithState(ReadinessState.ACCEPTING_TRAFFIC))); inOrder.verifyNoMoreInteractions(); } @@ -1068,13 +1071,13 @@ class SpringApplicationTests { Iterator> iterator = this.context.getEnvironment().getPropertySources().iterator(); assertThat(iterator.next().getName()).isEqualTo("configurationProperties"); assertThat(iterator.next().getName()) - .isEqualTo(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); + .isEqualTo(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); } @Test void nonWebApplicationConfiguredViaAPropertyHasTheCorrectTypeOfContextAndEnvironment() { ConfigurableApplicationContext context = new SpringApplication(ExampleConfig.class) - .run("--spring.main.web-application-type=none"); + .run("--spring.main.web-application-type=none"); assertThat(context).isNotInstanceOfAny(WebApplicationContext.class, ReactiveWebApplicationContext.class); assertThat(context.getEnvironment()).isNotInstanceOfAny(ConfigurableWebEnvironment.class); } @@ -1082,7 +1085,7 @@ class SpringApplicationTests { @Test void webApplicationConfiguredViaAPropertyHasTheCorrectTypeOfContextAndEnvironment() { ConfigurableApplicationContext context = new SpringApplication(ExampleWebConfig.class) - .run("--spring.main.web-application-type=servlet"); + .run("--spring.main.web-application-type=servlet"); assertThat(context).isInstanceOf(WebApplicationContext.class); assertThat(context.getEnvironment()).isInstanceOf(StandardServletEnvironment.class); assertThat(context.getEnvironment().getClass().getName()).endsWith("ApplicationServletEnvironment"); @@ -1091,7 +1094,7 @@ class SpringApplicationTests { @Test void reactiveApplicationConfiguredViaAPropertyHasTheCorrectTypeOfContextAndEnvironment() { ConfigurableApplicationContext context = new SpringApplication(ExampleReactiveWebConfig.class) - .run("--spring.main.web-application-type=reactive"); + .run("--spring.main.web-application-type=reactive"); assertThat(context).isInstanceOf(ReactiveWebApplicationContext.class); assertThat(context.getEnvironment()).isInstanceOf(StandardReactiveWebEnvironment.class); assertThat(context.getEnvironment().getClass().getName()).endsWith("ApplicationReactiveWebEnvironment"); @@ -1100,7 +1103,7 @@ class SpringApplicationTests { @Test void environmentIsConvertedIfTypeDoesNotMatch() { ConfigurableApplicationContext context = new SpringApplication(ExampleReactiveWebConfig.class) - .run("--spring.profiles.active=withwebapplicationtype"); + .run("--spring.profiles.active=withwebapplicationtype"); assertThat(context).isInstanceOf(ReactiveWebApplicationContext.class); assertThat(context.getEnvironment()).isInstanceOf(StandardReactiveWebEnvironment.class); assertThat(context.getEnvironment().getClass().getName()).endsWith("ApplicationReactiveWebEnvironment"); @@ -1127,29 +1130,30 @@ class SpringApplicationTests { @Test void beanDefinitionOverridingIsDisabledByDefault() { assertThatExceptionOfType(BeanDefinitionOverrideException.class) - .isThrownBy(() -> new SpringApplication(ExampleConfig.class, OverrideConfig.class).run()); + .isThrownBy(() -> new SpringApplication(ExampleConfig.class, OverrideConfig.class).run()); } @Test void beanDefinitionOverridingCanBeEnabled() { assertThat(new SpringApplication(ExampleConfig.class, OverrideConfig.class) - .run("--spring.main.allow-bean-definition-overriding=true", "--spring.main.web-application-type=none") - .getBean("someBean")).isEqualTo("override"); + .run("--spring.main.allow-bean-definition-overriding=true", "--spring.main.web-application-type=none") + .getBean("someBean")).isEqualTo("override"); } @Test void circularReferencesAreDisabledByDefault() { assertThatExceptionOfType(UnsatisfiedDependencyException.class) - .isThrownBy(() -> new SpringApplication(ExampleProducerConfiguration.class, - ExampleConsumerConfiguration.class).run("--spring.main.web-application-type=none")) - .withRootCauseInstanceOf(BeanCurrentlyInCreationException.class); + .isThrownBy( + () -> new SpringApplication(ExampleProducerConfiguration.class, ExampleConsumerConfiguration.class) + .run("--spring.main.web-application-type=none")) + .withRootCauseInstanceOf(BeanCurrentlyInCreationException.class); } @Test void circularReferencesCanBeEnabled() { assertThatNoException().isThrownBy( - () -> new SpringApplication(ExampleProducerConfiguration.class, ExampleConsumerConfiguration.class).run( - "--spring.main.web-application-type=none", "--spring.main.allow-circular-references=true")); + () -> new SpringApplication(ExampleProducerConfiguration.class, ExampleConsumerConfiguration.class) + .run("--spring.main.web-application-type=none", "--spring.main.allow-circular-references=true")); } @Test @@ -1163,28 +1167,28 @@ class SpringApplicationTests { @Test void lazyInitializationIsDisabledByDefault() { assertThat(new SpringApplication(LazyInitializationConfig.class).run("--spring.main.web-application-type=none") - .getBean(AtomicInteger.class)).hasValue(1); + .getBean(AtomicInteger.class)).hasValue(1); } @Test void lazyInitializationCanBeEnabled() { assertThat(new SpringApplication(LazyInitializationConfig.class) - .run("--spring.main.web-application-type=none", "--spring.main.lazy-initialization=true") - .getBean(AtomicInteger.class)).hasValue(0); + .run("--spring.main.web-application-type=none", "--spring.main.lazy-initialization=true") + .getBean(AtomicInteger.class)).hasValue(0); } @Test void lazyInitializationIgnoresBeansThatAreExplicitlyNotLazy() { assertThat(new SpringApplication(NotLazyInitializationConfig.class) - .run("--spring.main.web-application-type=none", "--spring.main.lazy-initialization=true") - .getBean(AtomicInteger.class)).hasValue(1); + .run("--spring.main.web-application-type=none", "--spring.main.lazy-initialization=true") + .getBean(AtomicInteger.class)).hasValue(1); } @Test void lazyInitializationIgnoresLazyInitializationExcludeFilteredBeans() { assertThat(new SpringApplication(LazyInitializationExcludeFilterConfig.class) - .run("--spring.main.web-application-type=none", "--spring.main.lazy-initialization=true") - .getBean(AtomicInteger.class)).hasValue(1); + .run("--spring.main.web-application-type=none", "--spring.main.lazy-initialization=true") + .getBean(AtomicInteger.class)).hasValue(1); } @Test @@ -1205,10 +1209,14 @@ class SpringApplicationTests { then(applicationStartup).should().start("spring.boot.application.context-loaded"); then(applicationStartup).should().start("spring.boot.application.started"); then(applicationStartup).should().start("spring.boot.application.ready"); - long startCount = mockingDetails(applicationStartup).getInvocations().stream() - .filter((invocation) -> invocation.getMethod().toString().contains("start(")).count(); - long endCount = mockingDetails(startupStep).getInvocations().stream() - .filter((invocation) -> invocation.getMethod().toString().contains("end(")).count(); + long startCount = mockingDetails(applicationStartup).getInvocations() + .stream() + .filter((invocation) -> invocation.getMethod().toString().contains("start(")) + .count(); + long endCount = mockingDetails(startupStep).getInvocations() + .stream() + .filter((invocation) -> invocation.getMethod().toString().contains("end(")) + .count(); assertThat(startCount).isEqualTo(endCount); } @@ -1226,10 +1234,14 @@ class SpringApplicationTests { then(applicationStartup).should().start("spring.boot.application.starting"); then(applicationStartup).should().start("spring.boot.application.environment-prepared"); then(applicationStartup).should().start("spring.boot.application.failed"); - long startCount = mockingDetails(applicationStartup).getInvocations().stream() - .filter((invocation) -> invocation.getMethod().toString().contains("start(")).count(); - long endCount = mockingDetails(startupStep).getInvocations().stream() - .filter((invocation) -> invocation.getMethod().toString().contains("end(")).count(); + long startCount = mockingDetails(applicationStartup).getInvocations() + .stream() + .filter((invocation) -> invocation.getMethod().toString().contains("start(")) + .count(); + long endCount = mockingDetails(startupStep).getInvocations() + .stream() + .filter((invocation) -> invocation.getMethod().toString().contains("end(")) + .count(); assertThat(startCount).isEqualTo(endCount); } @@ -1245,7 +1257,7 @@ class SpringApplicationTests { ApplicationStartingEvent startingEvent = listener.getEvent(ApplicationStartingEvent.class); assertThat(startingEvent.getBootstrapContext().get(String.class)).isEqualTo("boot"); ApplicationEnvironmentPreparedEvent environmentPreparedEvent = listener - .getEvent(ApplicationEnvironmentPreparedEvent.class); + .getEvent(ApplicationEnvironmentPreparedEvent.class); assertThat(environmentPreparedEvent.getBootstrapContext().get(String.class)).isEqualTo("boot"); } @@ -1255,8 +1267,9 @@ class SpringApplicationTests { application.setWebApplicationType(WebApplicationType.NONE); application.addBootstrapRegistryInitializer((bootstrapContext) -> { bootstrapContext.register(String.class, InstanceSupplier.of("boot")); - bootstrapContext.addCloseListener((event) -> event.getApplicationContext().getBeanFactory() - .registerSingleton("test", event.getBootstrapContext().get(String.class))); + bootstrapContext.addCloseListener((event) -> event.getApplicationContext() + .getBeanFactory() + .registerSingleton("test", event.getBootstrapContext().get(String.class))); }); ConfigurableApplicationContext applicationContext = application.run(); assertThat(applicationContext.getBean("test")).isEqualTo("boot"); @@ -1265,7 +1278,7 @@ class SpringApplicationTests { @Test void settingEnvironmentPrefixViaPropertiesThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> new SpringApplication().run("--spring.main.environment-prefix=my")); + .isThrownBy(() -> new SpringApplication().run("--spring.main.environment-prefix=my")); } @Test @@ -1284,7 +1297,7 @@ class SpringApplicationTests { application.setDefaultProperties(Collections.singletonMap("test.name", "test")); this.context = application.run(); assertThat(this.context.getEnvironment().getProperty("test.name")) - .isEqualTo("spring-application-config-property-source"); + .isEqualTo("spring-application-config-property-source"); } @Test @@ -1295,10 +1308,13 @@ class SpringApplicationTests { application.setWebApplicationType(WebApplicationType.NONE); assertThatExceptionOfType(BeanCreationException.class).isThrownBy(application::run); assertThat(events).hasAtLeastOneElementOfType(ApplicationFailedEvent.class); - ApplicationFailedEvent failure = events.stream().filter((event) -> event instanceof ApplicationFailedEvent) - .map(ApplicationFailedEvent.class::cast).findFirst().get(); + ApplicationFailedEvent failure = events.stream() + .filter((event) -> event instanceof ApplicationFailedEvent) + .map(ApplicationFailedEvent.class::cast) + .findFirst() + .get(); assertThat(SpringApplicationShutdownHookInstance.get()) - .didNotRegisterApplicationContext(failure.getApplicationContext()); + .didNotRegisterApplicationContext(failure.getApplicationContext()); } private ArgumentMatcher isAvailabilityChangeEventWithState( diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootConfigurationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootConfigurationTests.java index b4ff5f017b..f1a6e82b8f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootConfigurationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,14 +34,14 @@ class SpringBootConfigurationTests { @Test void proxyBeanMethodsIsEnabledByDefault() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(DefaultSpringBootConfiguration.class, Configuration.class); + .getMergedAnnotationAttributes(DefaultSpringBootConfiguration.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(true); } @Test void proxyBeanMethodsCanBeDisabled() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(NoBeanMethodProxyingSpringBootConfiguration.class, Configuration.class); + .getMergedAnnotationAttributes(NoBeanMethodProxyingSpringBootConfiguration.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(false); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootVersionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootVersionTests.java index 887413c25c..02cfa6cda4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootVersionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootVersionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ class SpringBootVersionTests { @Test void getVersionShouldReturnVersionMatchingGradleProperties() throws IOException { String expectedVersion = PropertiesLoaderUtils.loadProperties(new FileSystemResource(findGradleProperties())) - .getProperty("version"); + .getProperty("version"); assertThat(SpringBootVersion.getVersion()).isEqualTo(expectedVersion); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java index cc18ba2561..07510abcc2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -122,7 +122,7 @@ class SpringApplicationAdminMXBeanRegistrarTests { assertThat(this.context.isRunning()).isFalse(); // JMX cleanup assertThatExceptionOfType(InstanceNotFoundException.class) - .isThrownBy(() -> this.mBeanServer.getObjectInstance(objectName)); + .isThrownBy(() -> this.mBeanServer.getObjectInstance(objectName)); } private Boolean isApplicationReady(ObjectName objectName) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/Ansi8BitColorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/Ansi8BitColorTests.java index e793ba4a44..0e93c650ac 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/Ansi8BitColorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/Ansi8BitColorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,17 +42,17 @@ class Ansi8BitColorTests { @Test void foregroundWhenOutsideBoundsThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Ansi8BitColor.foreground(-1)) - .withMessage("Code must be between 0 and 255"); + .withMessage("Code must be between 0 and 255"); assertThatIllegalArgumentException().isThrownBy(() -> Ansi8BitColor.foreground(256)) - .withMessage("Code must be between 0 and 255"); + .withMessage("Code must be between 0 and 255"); } @Test void backgroundWhenOutsideBoundsThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Ansi8BitColor.background(-1)) - .withMessage("Code must be between 0 and 255"); + .withMessage("Code must be between 0 and 255"); assertThatIllegalArgumentException().isThrownBy(() -> Ansi8BitColor.background(256)) - .withMessage("Code must be between 0 and 255"); + .withMessage("Code must be between 0 and 255"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/availability/ApplicationAvailabilityBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/availability/ApplicationAvailabilityBeanTests.java index fec136367f..4f22ff574c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/availability/ApplicationAvailabilityBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/availability/ApplicationAvailabilityBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -107,7 +107,7 @@ class ApplicationAvailabilityBeanTests { assertThat(this.log.getLogged()).contains("Application availability state LivenessState changed to CORRECT"); AvailabilityChangeEvent.publish(this.context, LivenessState.BROKEN); assertThat(this.log.getLogged()) - .contains("Application availability state LivenessState changed from CORRECT to BROKEN"); + .contains("Application availability state LivenessState changed from CORRECT to BROKEN"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/availability/AvailabilityChangeEventTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/availability/AvailabilityChangeEventTests.java index f1527bfcbe..bf1c47aa57 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/availability/AvailabilityChangeEventTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/availability/AvailabilityChangeEventTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ class AvailabilityChangeEventTests { @Test void createWhenStateIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new AvailabilityChangeEvent<>(this.source, null)) - .withMessage("Payload must not be null"); + .withMessage("Payload must not be null"); } @Test 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..afeee17b71 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,8 +74,9 @@ class SpringApplicationBuilderTests { @Test void profileAndProperties() { SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)) - .profiles("foo").properties("foo=bar"); + .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)) + .profiles("foo") + .properties("foo=bar"); this.context = application.run(); assertThat(this.context).isInstanceOf(StaticApplicationContext.class); assertThat(this.context.getEnvironment().getProperty("foo")).isEqualTo("bucket"); @@ -85,8 +86,8 @@ class SpringApplicationBuilderTests { @Test void propertiesAsMap() { SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)) - .properties(Collections.singletonMap("bar", "foo")); + .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)) + .properties(Collections.singletonMap("bar", "foo")); this.context = application.run(); assertThat(this.context.getEnvironment().getProperty("bar")).isEqualTo("foo"); } @@ -94,8 +95,8 @@ class SpringApplicationBuilderTests { @Test void propertiesAsProperties() { SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)) - .properties(StringUtils.splitArrayElementsIntoProperties(new String[] { "bar=foo" }, "=")); + .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)) + .properties(StringUtils.splitArrayElementsIntoProperties(new String[] { "bar=foo" }, "=")); this.context = application.run(); assertThat(this.context.getEnvironment().getProperty("bar")).isEqualTo("foo"); } @@ -103,8 +104,8 @@ class SpringApplicationBuilderTests { @Test void propertiesWithRepeatSeparator() { SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)) - .properties("one=c:\\logging.file.name", "two=a:b", "three:c:\\logging.file.name", "four:a:b"); + .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)) + .properties("one=c:\\logging.file.name", "two=a:b", "three:c:\\logging.file.name", "four:a:b"); this.context = application.run(); ConfigurableEnvironment environment = this.context.getEnvironment(); assertThat(environment.getProperty("one")).isEqualTo("c:\\logging.file.name"); @@ -116,7 +117,7 @@ class SpringApplicationBuilderTests { @Test void specificApplicationContextFactory() { SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)); + .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)); this.context = application.run(); assertThat(this.context).isInstanceOf(StaticApplicationContext.class); } @@ -124,25 +125,25 @@ class SpringApplicationBuilderTests { @Test void parentContextCreationThatIsRunDirectly() { SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); + .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); application.parent(ExampleConfig.class); this.context = application.run("foo.bar=baz"); then(((SpyApplicationContext) this.context).getApplicationContext()).should() - .setParent(any(ApplicationContext.class)); + .setParent(any(ApplicationContext.class)); assertThat(SpringApplicationShutdownHookInstance.get()).didNotRegisterApplicationContext(this.context); assertThat(this.context.getParent().getBean(ApplicationArguments.class).getNonOptionArgs()) - .contains("foo.bar=baz"); + .contains("foo.bar=baz"); assertThat(this.context.getBean(ApplicationArguments.class).getNonOptionArgs()).contains("foo.bar=baz"); } @Test void parentContextCreationThatIsBuiltThenRun() { SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); + .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); application.parent(ExampleConfig.class); this.context = application.build("a=alpha").run("b=bravo"); then(((SpyApplicationContext) this.context).getApplicationContext()).should() - .setParent(any(ApplicationContext.class)); + .setParent(any(ApplicationContext.class)); assertThat(SpringApplicationShutdownHookInstance.get()).didNotRegisterApplicationContext(this.context); assertThat(this.context.getParent().getBean(ApplicationArguments.class).getNonOptionArgs()).contains("a=alpha"); assertThat(this.context.getBean(ApplicationArguments.class).getNonOptionArgs()).contains("b=bravo"); @@ -151,19 +152,19 @@ class SpringApplicationBuilderTests { @Test void parentContextCreationWithChildShutdown() { SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)) - .registerShutdownHook(true); + .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)) + .registerShutdownHook(true); application.parent(ExampleConfig.class); this.context = application.run(); then(((SpyApplicationContext) this.context).getApplicationContext()).should() - .setParent(any(ApplicationContext.class)); + .setParent(any(ApplicationContext.class)); assertThat(SpringApplicationShutdownHookInstance.get()).registeredApplicationContext(this.context); } @Test void contextWithClassLoader() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); + .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); ClassLoader classLoader = new URLClassLoader(new URL[0], getClass().getClassLoader()); application.resourceLoader(new DefaultResourceLoader(classLoader)); this.context = application.run(); @@ -173,7 +174,7 @@ class SpringApplicationBuilderTests { @Test void parentContextWithClassLoader() { SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); + .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); ClassLoader classLoader = new URLClassLoader(new URL[0], getClass().getClassLoader()); application.resourceLoader(new DefaultResourceLoader(classLoader)); application.parent(ExampleConfig.class); @@ -184,18 +185,20 @@ class SpringApplicationBuilderTests { @Test void parentFirstCreation() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) - .child(ChildConfig.class); + .child(ChildConfig.class); application.contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); this.context = application.run(); then(((SpyApplicationContext) this.context).getApplicationContext()).should() - .setParent(any(ApplicationContext.class)); + .setParent(any(ApplicationContext.class)); assertThat(SpringApplicationShutdownHookInstance.get()).didNotRegisterApplicationContext(this.context); } @Test void parentFirstCreationWithProfileAndDefaultArgs() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class).profiles("node") - .properties("transport=redis").child(ChildConfig.class).web(WebApplicationType.NONE); + .properties("transport=redis") + .child(ChildConfig.class) + .web(WebApplicationType.NONE); this.context = application.run(); assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("node"))).isTrue(); assertThat(this.context.getEnvironment().getProperty("transport")).isEqualTo("redis"); @@ -208,7 +211,10 @@ class SpringApplicationBuilderTests { @Test void parentFirstWithDifferentProfile() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class).profiles("node") - .properties("transport=redis").child(ChildConfig.class).profiles("admin").web(WebApplicationType.NONE); + .properties("transport=redis") + .child(ChildConfig.class) + .profiles("admin") + .web(WebApplicationType.NONE); this.context = application.run(); assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("node", "admin"))).isTrue(); assertThat(this.context.getParent().getEnvironment().acceptsProfiles(Profiles.of("admin"))).isFalse(); @@ -217,9 +223,10 @@ class SpringApplicationBuilderTests { @Test void parentWithDifferentProfile() { SpringApplicationBuilder shared = new SpringApplicationBuilder(ExampleConfig.class).profiles("node") - .properties("transport=redis"); - SpringApplicationBuilder application = shared.child(ChildConfig.class).profiles("admin") - .web(WebApplicationType.NONE); + .properties("transport=redis"); + SpringApplicationBuilder application = shared.child(ChildConfig.class) + .profiles("admin") + .web(WebApplicationType.NONE); shared.profiles("parent"); this.context = application.run(); assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("node", "admin"))).isTrue(); @@ -230,8 +237,12 @@ class SpringApplicationBuilderTests { @Test void parentFirstWithDifferentProfileAndExplicitEnvironment() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) - .environment(new StandardEnvironment()).profiles("node").properties("transport=redis") - .child(ChildConfig.class).profiles("admin").web(WebApplicationType.NONE); + .environment(new StandardEnvironment()) + .profiles("node") + .properties("transport=redis") + .child(ChildConfig.class) + .profiles("admin") + .web(WebApplicationType.NONE); this.context = application.run(); assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("node", "admin"))).isTrue(); // Now they share an Environment explicitly so there's no way to keep the profiles @@ -246,13 +257,13 @@ class SpringApplicationBuilderTests { application.contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); this.context = application.run(); then(((SpyApplicationContext) this.context).getApplicationContext()).should() - .setParent(any(ApplicationContext.class)); + .setParent(any(ApplicationContext.class)); } @Test void initializersCreatedOnce() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) - .web(WebApplicationType.NONE); + .web(WebApplicationType.NONE); this.context = application.run(); assertThat(application.application().getInitializers()).hasSize(5); } @@ -260,7 +271,8 @@ class SpringApplicationBuilderTests { @Test void initializersCreatedOnceForChild() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) - .child(ChildConfig.class).web(WebApplicationType.NONE); + .child(ChildConfig.class) + .web(WebApplicationType.NONE); this.context = application.run(); assertThat(application.application().getInitializers()).hasSize(6); } @@ -268,8 +280,9 @@ class SpringApplicationBuilderTests { @Test void initializersIncludeDefaults() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) - .web(WebApplicationType.NONE).initializers((ConfigurableApplicationContext applicationContext) -> { - }); + .web(WebApplicationType.NONE) + .initializers((ConfigurableApplicationContext applicationContext) -> { + }); this.context = application.run(); assertThat(application.application().getInitializers()).hasSize(6); } @@ -277,7 +290,8 @@ class SpringApplicationBuilderTests { @Test void sourcesWithBoundSources() { SpringApplicationBuilder application = new SpringApplicationBuilder().web(WebApplicationType.NONE) - .sources(ExampleConfig.class).properties("spring.main.sources=" + ChildConfig.class.getName()); + .sources(ExampleConfig.class) + .properties("spring.main.sources=" + ChildConfig.class.getName()); this.context = application.run(); this.context.getBean(ExampleConfig.class); this.context.getBean(ChildConfig.class); @@ -286,8 +300,9 @@ class SpringApplicationBuilderTests { @Test void addBootstrapRegistryInitializer() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) - .web(WebApplicationType.NONE).addBootstrapRegistryInitializer((context) -> context.addCloseListener( - (event) -> event.getApplicationContext().getBeanFactory().registerSingleton("test", "spring"))); + .web(WebApplicationType.NONE) + .addBootstrapRegistryInitializer((context) -> context.addCloseListener( + (event) -> event.getApplicationContext().getBeanFactory().registerSingleton("test", "spring"))); this.context = application.run(); assertThat(this.context.getBean("test")).isEqualTo("spring"); } @@ -310,7 +325,7 @@ class SpringApplicationBuilderTests { }; SpringApplication application = applicationBuilder.build(); assertThat(application).asInstanceOf(InstanceOfAssertFactories.type(CustomSpringApplication.class)) - .satisfies((customApp) -> assertThat(customApp.resourceLoader).isEqualTo(resourceLoader)); + .satisfies((customApp) -> assertThat(customApp.resourceLoader).isEqualTo(resourceLoader)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java index 884057e21f..7d330faff5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -242,7 +242,7 @@ class CloudPlatformTests { Environment environment = getEnvironmentWithEnvVariables(envVars); ((MockEnvironment) environment).setProperty("spring.main.cloud-platform", "none"); assertThat(Stream.of(CloudPlatform.values()).filter((platform) -> platform.isActive(environment))) - .containsExactly(CloudPlatform.NONE); + .containsExactly(CloudPlatform.NONE); } private Environment getEnvironmentWithEnvVariables(Map environmentVariables) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java index 396e7b1d65..fe6a05cc23 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -144,7 +144,7 @@ class ApplicationPidFileWriterTests { System.setProperty("PID_FAIL_ON_WRITE_ERROR", "true"); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); assertThatIllegalStateException().isThrownBy(() -> listener.onApplicationEvent(EVENT)) - .withMessageContaining("Cannot create pid file"); + .withMessageContaining("Cannot create pid file"); }); } @@ -154,7 +154,7 @@ class ApplicationPidFileWriterTests { SpringApplicationEvent event = createPreparedEvent("spring.pid.fail-on-write-error", "true"); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); assertThatIllegalStateException().isThrownBy(() -> listener.onApplicationEvent(event)) - .withMessageContaining("Cannot create pid file"); + .withMessageContaining("Cannot create pid file"); }); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java index a5e0036bbe..3c76500b41 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +57,7 @@ class TypeExcludeFilterTests { this.context.refresh(); assertThat(this.context.getBean(ExampleComponent.class)).isNotNull(); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(ExampleFilteredComponent.class)); + .isThrownBy(() -> this.context.getBean(ExampleFilteredComponent.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java index d4515a8b11..71b36adf9e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ class ConfigurationsTests { @Test void createWhenClassesIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new TestConfigurations(null)) - .withMessageContaining("Classes must not be null"); + .withMessageContaining("Classes must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorPlaceholdersResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorPlaceholdersResolverTests.java index a7db25a324..23022678f5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorPlaceholdersResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorPlaceholdersResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -75,8 +75,8 @@ class ConfigDataEnvironmentContributorPlaceholdersResolverTests { ConfigDataEnvironmentContributorPlaceholdersResolver resolver = new ConfigDataEnvironmentContributorPlaceholdersResolver( contributors, null, null, true); assertThatExceptionOfType(InactiveConfigDataAccessException.class) - .isThrownBy(() -> resolver.resolvePlaceholders("${test}")) - .satisfies(propertyNameAndOriginOf("test", "s3")); + .isThrownBy(() -> resolver.resolvePlaceholders("${test}")) + .satisfies(propertyNameAndOriginOf("test", "s3")); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorTests.java index c0cac3c0f6..87f6f89750 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -105,7 +105,8 @@ class ConfigDataEnvironmentContributorTests { ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor.ofUnboundImport(null, null, false, configData, 0); assertThat(contributor.getConfigurationPropertySource() - .getConfigurationProperty(ConfigurationPropertyName.of("spring")).getValue()).isEqualTo("boot"); + .getConfigurationProperty(ConfigurationPropertyName.of("spring")) + .getValue()).isEqualTo("boot"); } @Test @@ -357,8 +358,8 @@ class ConfigDataEnvironmentContributorTests { void bindWhenHasUseLegacyPropertyThrowsException() { MockPropertySource propertySource = new MockPropertySource(); propertySource.setProperty("spring.config.use-legacy-processing", "true"); - assertThatExceptionOfType(UseLegacyConfigProcessingException.class).isThrownBy( - () -> createBoundContributor(null, new ConfigData(Collections.singleton(propertySource)), 0)); + assertThatExceptionOfType(UseLegacyConfigProcessingException.class) + .isThrownBy(() -> createBoundContributor(null, new ConfigData(Collections.singleton(propertySource)), 0)); } @Test // gh-25029 diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorsTests.java index 53fabcdacc..eed7ba8504 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -106,7 +106,7 @@ class ConfigDataEnvironmentContributorsTests { @Test void withProcessedImportsWhenHasNoUnprocessedImportsReturnsSameInstance() { ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor - .ofExisting(new MockPropertySource()); + .ofExisting(new MockPropertySource()); ConfigDataEnvironmentContributors contributors = new ConfigDataEnvironmentContributors(this.logFactory, this.bootstrapContext, Arrays.asList(contributor)); ConfigDataEnvironmentContributors withProcessedImports = contributors.withProcessedImports(this.importer, @@ -123,7 +123,7 @@ class ConfigDataEnvironmentContributorsTests { imported.put(new ConfigDataResolutionResult(LOCATION_1, new TestConfigDataResource("a"), false), new ConfigData(Arrays.asList(propertySource))); given(this.importer.resolveAndLoad(eq(this.activationContext), any(), any(), eq(locations))) - .willReturn(imported); + .willReturn(imported); ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor.ofInitialImport(LOCATION_1); ConfigDataEnvironmentContributors contributors = new ConfigDataEnvironmentContributors(this.logFactory, this.bootstrapContext, Arrays.asList(contributor)); @@ -146,14 +146,14 @@ class ConfigDataEnvironmentContributorsTests { initialImported.put(new ConfigDataResolutionResult(LOCATION_1, new TestConfigDataResource("a"), false), new ConfigData(Arrays.asList(initialPropertySource))); given(this.importer.resolveAndLoad(eq(this.activationContext), any(), any(), eq(initialLocations))) - .willReturn(initialImported); + .willReturn(initialImported); List secondLocations = Arrays.asList(LOCATION_2); MockPropertySource secondPropertySource = new MockPropertySource(); Map secondImported = new LinkedHashMap<>(); secondImported.put(new ConfigDataResolutionResult(LOCATION_2, new TestConfigDataResource("b"), false), new ConfigData(Arrays.asList(secondPropertySource))); given(this.importer.resolveAndLoad(eq(this.activationContext), any(), any(), eq(secondLocations))) - .willReturn(secondImported); + .willReturn(secondImported); ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor.ofInitialImport(LOCATION_1); ConfigDataEnvironmentContributors contributors = new ConfigDataEnvironmentContributors(this.logFactory, this.bootstrapContext, Arrays.asList(contributor)); @@ -172,7 +172,7 @@ class ConfigDataEnvironmentContributorsTests { MockPropertySource existingPropertySource = new MockPropertySource(); existingPropertySource.setProperty("test", "springboot"); ConfigDataEnvironmentContributor existingContributor = ConfigDataEnvironmentContributor - .ofExisting(existingPropertySource); + .ofExisting(existingPropertySource); this.importer = mock(ConfigDataImporter.class); List locations = Arrays.asList(LOCATION_1); MockPropertySource propertySource = new MockPropertySource(); @@ -180,7 +180,7 @@ class ConfigDataEnvironmentContributorsTests { imported.put(new ConfigDataResolutionResult(LOCATION_1, new TestConfigDataResource("a'"), false), new ConfigData(Arrays.asList(propertySource))); given(this.importer.resolveAndLoad(eq(this.activationContext), any(), any(), eq(locations))) - .willReturn(imported); + .willReturn(imported); ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor.ofInitialImport(LOCATION_1); ConfigDataEnvironmentContributors contributors = new ConfigDataEnvironmentContributors(this.logFactory, this.bootstrapContext, Arrays.asList(existingContributor, contributor)); @@ -200,20 +200,20 @@ class ConfigDataEnvironmentContributorsTests { initialImported.put(new ConfigDataResolutionResult(LOCATION_1, new TestConfigDataResource("a"), false), new ConfigData(Arrays.asList(initialPropertySource))); given(this.importer.resolveAndLoad(eq(this.activationContext), any(), any(), eq(initialLocations))) - .willReturn(initialImported); + .willReturn(initialImported); List secondLocations = Arrays.asList(LOCATION_2); MockPropertySource secondPropertySource = new MockPropertySource(); Map secondImported = new LinkedHashMap<>(); secondImported.put(new ConfigDataResolutionResult(LOCATION_2, new TestConfigDataResource("b"), false), new ConfigData(Arrays.asList(secondPropertySource))); given(this.importer.resolveAndLoad(eq(this.activationContext), any(), any(), eq(secondLocations))) - .willReturn(secondImported); + .willReturn(secondImported); ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor.ofInitialImport(LOCATION_1); ConfigDataEnvironmentContributors contributors = new ConfigDataEnvironmentContributors(this.logFactory, this.bootstrapContext, Arrays.asList(contributor)); contributors.withProcessedImports(this.importer, this.activationContext); - then(this.importer).should().resolveAndLoad(any(), this.locationResolverContext.capture(), any(), - eq(secondLocations)); + then(this.importer).should() + .resolveAndLoad(any(), this.locationResolverContext.capture(), any(), eq(secondLocations)); ConfigDataLocationResolverContext context = this.locationResolverContext.getValue(); assertThat(context.getParent()).hasToString("a"); } @@ -223,7 +223,7 @@ class ConfigDataEnvironmentContributorsTests { MockPropertySource existingPropertySource = new MockPropertySource(); existingPropertySource.setProperty("test", "springboot"); ConfigDataEnvironmentContributor existingContributor = ConfigDataEnvironmentContributor - .ofExisting(existingPropertySource); + .ofExisting(existingPropertySource); this.importer = mock(ConfigDataImporter.class); List locations = Arrays.asList(LOCATION_1); MockPropertySource propertySource = new MockPropertySource(); @@ -231,7 +231,7 @@ class ConfigDataEnvironmentContributorsTests { imported.put(new ConfigDataResolutionResult(LOCATION_1, new TestConfigDataResource("a'"), false), new ConfigData(Arrays.asList(propertySource))); given(this.importer.resolveAndLoad(eq(this.activationContext), any(), any(), eq(locations))) - .willReturn(imported); + .willReturn(imported); ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor.ofInitialImport(LOCATION_1); ConfigDataEnvironmentContributors contributors = new ConfigDataEnvironmentContributors(this.logFactory, this.bootstrapContext, Arrays.asList(existingContributor, contributor)); @@ -246,7 +246,7 @@ class ConfigDataEnvironmentContributorsTests { MockPropertySource existingPropertySource = new MockPropertySource(); existingPropertySource.setProperty("test", "springboot"); ConfigDataEnvironmentContributor existingContributor = ConfigDataEnvironmentContributor - .ofExisting(existingPropertySource); + .ofExisting(existingPropertySource); this.importer = mock(ConfigDataImporter.class); List locations = Arrays.asList(LOCATION_1); MockPropertySource propertySource = new MockPropertySource(); @@ -254,7 +254,7 @@ class ConfigDataEnvironmentContributorsTests { imported.put(new ConfigDataResolutionResult(LOCATION_1, new TestConfigDataResource("a'"), false), new ConfigData(Arrays.asList(propertySource))); given(this.importer.resolveAndLoad(eq(this.activationContext), any(), any(), eq(locations))) - .willReturn(imported); + .willReturn(imported); ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor.ofInitialImport(LOCATION_1); ConfigDataEnvironmentContributors contributors = new ConfigDataEnvironmentContributors(this.logFactory, this.bootstrapContext, Arrays.asList(existingContributor, contributor)); @@ -349,7 +349,7 @@ class ConfigDataEnvironmentContributorsTests { this.bootstrapContext, Arrays.asList(firstContributor, secondContributor)); Binder binder = contributors.getBinder(this.activationContext, BinderOption.FAIL_ON_BIND_TO_INACTIVE_SOURCE); assertThatExceptionOfType(BindException.class).isThrownBy(() -> binder.bind("test", String.class)) - .satisfies((ex) -> assertThat(ex.getCause()).isInstanceOf(InactiveConfigDataAccessException.class)); + .satisfies((ex) -> assertThat(ex.getCause()).isInstanceOf(InactiveConfigDataAccessException.class)); } @Test @@ -366,7 +366,7 @@ class ConfigDataEnvironmentContributorsTests { this.bootstrapContext, Arrays.asList(firstContributor, secondContributor)); Binder binder = contributors.getBinder(this.activationContext, BinderOption.FAIL_ON_BIND_TO_INACTIVE_SOURCE); assertThatExceptionOfType(BindException.class).isThrownBy(() -> binder.bind("test", String.class)) - .satisfies((ex) -> assertThat(ex.getCause()).isInstanceOf(InactiveConfigDataAccessException.class)); + .satisfies((ex) -> assertThat(ex.getCause()).isInstanceOf(InactiveConfigDataAccessException.class)); } @Test @@ -384,7 +384,7 @@ class ConfigDataEnvironmentContributorsTests { this.bootstrapContext, Arrays.asList(firstContributor, secondContributor)); Binder binder = contributors.getBinder(this.activationContext, BinderOption.FAIL_ON_BIND_TO_INACTIVE_SOURCE); assertThatExceptionOfType(BindException.class).isThrownBy(() -> binder.bind("test", String.class)) - .satisfies((ex) -> assertThat(ex.getCause()).isInstanceOf(InactiveConfigDataAccessException.class)); + .satisfies((ex) -> assertThat(ex.getCause()).isInstanceOf(InactiveConfigDataAccessException.class)); } private ConfigDataEnvironmentContributor createBoundImportContributor(ConfigData configData, diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorBootstrapContextIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorBootstrapContextIntegrationTests.java index 78c3eee333..45d8eec771 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorBootstrapContextIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorBootstrapContextIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,13 +47,13 @@ class ConfigDataEnvironmentPostProcessorBootstrapContextIntegrationTests { @Test void bootstrapsApplicationContext() { try (ConfigurableApplicationContext context = this.application - .run("--spring.config.import=classpath:application-bootstrap-registry-integration-tests.properties")) { + .run("--spring.config.import=classpath:application-bootstrap-registry-integration-tests.properties")) { LoaderHelper bean = context.getBean(TestConfigDataBootstrap.LoaderHelper.class); assertThat(bean).isNotNull(); assertThat(bean.getBound()).isEqualTo("igotbound"); assertThat(bean.getProfileBound()).isEqualTo("igotprofilebound"); assertThat(bean.getLocation().getResolverHelper().getLocation()) - .isEqualTo(ConfigDataLocation.of("testbootstrap:test")); + .isEqualTo(ConfigDataLocation.of("testbootstrap:test")); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorImportCombinedWithProfileSpecificIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorImportCombinedWithProfileSpecificIntegrationTests.java index 1d3dbbeca8..0b9f5e58c6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorImportCombinedWithProfileSpecificIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorImportCombinedWithProfileSpecificIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,7 +61,7 @@ class ConfigDataEnvironmentPostProcessorImportCombinedWithProfileSpecificIntegra @Test void testWithoutProfile() { ConfigurableApplicationContext context = this.application - .run("--spring.config.name=configimportwithprofilespecific"); + .run("--spring.config.name=configimportwithprofilespecific"); String value = context.getEnvironment().getProperty("prop"); assertThat(value).isEqualTo("fromicwps1"); } @@ -69,7 +69,7 @@ class ConfigDataEnvironmentPostProcessorImportCombinedWithProfileSpecificIntegra @Test void testWithProfile() { ConfigurableApplicationContext context = this.application - .run("--spring.config.name=configimportwithprofilespecific", "--spring.profiles.active=prod"); + .run("--spring.config.name=configimportwithprofilespecific", "--spring.profiles.active=prod"); String value = context.getEnvironment().getProperty("prop"); assertThat(value).isEqualTo("fromicwps2"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorIntegrationTests.java index 560129fd48..88dfd6cb06 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -146,7 +146,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenMultipleCustomNamesLoadsEachName() { ConfigurableApplicationContext context = this.application - .run("--spring.config.name=moreproperties,testproperties"); + .run("--spring.config.name=moreproperties,testproperties"); String property = context.getEnvironment().getProperty("the.property"); assertThat(property).isEqualTo("frompropertiesfile"); } @@ -177,7 +177,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenHasCustomSpringConfigLocationLoadsAllFromSpecifiedLocation() { ConfigurableApplicationContext context = this.application - .run("--spring.config.location=classpath:application.properties,classpath:testproperties.properties"); + .run("--spring.config.location=classpath:application.properties,classpath:testproperties.properties"); String property1 = context.getEnvironment().getProperty("the.property"); String property2 = context.getEnvironment().getProperty("my.property"); String property3 = context.getEnvironment().getProperty("foo"); @@ -206,13 +206,13 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { void runWhenProfileSpecificMandatoryLocationDoesNotExistShouldFailWhenProfileActive() { this.application.setAdditionalProfiles("prod"); assertThatExceptionOfType(ConfigDataResourceNotFoundException.class).isThrownBy(() -> this.application - .run("--spring.config.name=testprofiles", "--spring.config.location=classpath:configdata/profiles/")); + .run("--spring.config.name=testprofiles", "--spring.config.location=classpath:configdata/profiles/")); } @Test void runWhenHasActiveProfilesFromMultipleLocationsActivatesProfileFromOneLocation() { ConfigurableApplicationContext context = this.application - .run("--spring.config.location=classpath:enableprofile.properties,classpath:enableother.properties"); + .run("--spring.config.location=classpath:enableprofile.properties,classpath:enableother.properties"); ConfigurableEnvironment environment = context.getEnvironment(); assertThat(environment.getActiveProfiles()).containsExactly("other"); String property = environment.getProperty("other.property"); @@ -252,7 +252,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { void runWhenHasCommandLinePropertiesLoadsWithCommandLineTakingPrecedence() { StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources() - .addFirst(new SimpleCommandLinePropertySource("--the.property=fromcommandline")); + .addFirst(new SimpleCommandLinePropertySource("--the.property=fromcommandline")); this.application.setEnvironment(environment); ConfigurableApplicationContext context = this.application.run("--spring.config.name=testproperties"); String property = context.getEnvironment().getProperty("the.property"); @@ -408,9 +408,10 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { String property = context.getEnvironment().getProperty("my.property"); assertThat(context.getEnvironment().getActiveProfiles()).contains("dev"); assertThat(property).isEqualTo("fromdevprofile"); - assertThat(context.getEnvironment().getPropertySources()).extracting("name").contains( - "Config resource 'class path resource [configdata/profiles/testsetprofiles.yml]' via location 'classpath:configdata/profiles/' (document #0)", - "Config resource 'class path resource [configdata/profiles/testsetprofiles.yml]' via location 'classpath:configdata/profiles/' (document #1)"); + assertThat(context.getEnvironment().getPropertySources()).extracting("name") + .contains( + "Config resource 'class path resource [configdata/profiles/testsetprofiles.yml]' via location 'classpath:configdata/profiles/' (document #0)", + "Config resource 'class path resource [configdata/profiles/testsetprofiles.yml]' via location 'classpath:configdata/profiles/' (document #1)"); } @Test @@ -428,7 +429,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void loadWhenHasWhitespaceTrims() { ConfigurableApplicationContext context = this.application - .run("--spring.config.name=testsetmultiprofileswhitespace"); + .run("--spring.config.name=testsetmultiprofileswhitespace"); assertThat(context.getEnvironment().getActiveProfiles()).containsExactly("dev", "healthcheck"); } @@ -437,7 +438,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { String location = "file:src/test/resources/specificlocation.properties"; ConfigurableApplicationContext context = this.application.run("--spring.config.location=" + location); assertThat(context.getEnvironment()).has(matchingPropertySource("Config resource 'file [" + Strings - .join(Arrays.asList("src", "test", "resources", "specificlocation.properties"), File.separatorChar) + .join(Arrays.asList("src", "test", "resources", "specificlocation.properties"), File.separatorChar) + "]' via location '" + location + "'")); } @@ -446,7 +447,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { String location = "src/test/resources/specificlocation.properties"; ConfigurableApplicationContext context = this.application.run("--spring.config.location=" + location); assertThat(context.getEnvironment()).has(matchingPropertySource("Config resource 'file [" + Strings - .join(Arrays.asList("src", "test", "resources", "specificlocation.properties"), File.separatorChar) + .join(Arrays.asList("src", "test", "resources", "specificlocation.properties"), File.separatorChar) + "]' via location '" + location + "'")); } @@ -480,7 +481,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenHasAdditionalLocationLoadsWithAdditionalTakingPrecedenceOverDefaultLocation() { ConfigurableApplicationContext context = this.application - .run("--spring.config.additional-location=classpath:override.properties"); + .run("--spring.config.additional-location=classpath:override.properties"); assertThat(context.getEnvironment().getProperty("foo")).isEqualTo("bar"); assertThat(context.getEnvironment().getProperty("value")).isEqualTo("1234"); } @@ -488,7 +489,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenMultipleAdditionalLocationsLoadsWithLastWinning() { ConfigurableApplicationContext context = this.application - .run("--spring.config.additional-location=classpath:override.properties,classpath:some.properties"); + .run("--spring.config.additional-location=classpath:override.properties,classpath:some.properties"); assertThat(context.getEnvironment().getProperty("foo")).isEqualTo("spam"); assertThat(context.getEnvironment().getProperty("value")).isEqualTo("1234"); } @@ -536,9 +537,10 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { void runWhenConfigLocationHasUnknownFileExtensionFailsFast() { String location = "classpath:application.unknown"; assertThatIllegalStateException().isThrownBy(() -> this.application.run("--spring.config.location=" + location)) - .withMessageContaining("Unable to load config data").withMessageContaining(location) - .satisfies((ex) -> assertThat(ex.getCause()).hasMessageContaining("File extension is not known") - .hasMessageContaining("it must end in '/'")); + .withMessageContaining("Unable to load config data") + .withMessageContaining(location) + .satisfies((ex) -> assertThat(ex.getCause()).hasMessageContaining("File extension is not known") + .hasMessageContaining("it must end in '/'")); } @Test @@ -551,14 +553,14 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { void runWhenConfigLocationHasNonOptionalMissingFileDirectoryThrowsResourceNotFoundException() { File location = new File(this.temp, "application.unknown"); assertThatExceptionOfType(ConfigDataLocationNotFoundException.class).isThrownBy(() -> this.application - .run("--spring.config.location=" + StringUtils.cleanPath(location.getAbsolutePath()) + "/")); + .run("--spring.config.location=" + StringUtils.cleanPath(location.getAbsolutePath()) + "/")); } @Test void runWhenConfigLocationHasNonOptionalMissingClasspathDirectoryThrowsLocationNotFoundException() { String location = "classpath:application.unknown/"; assertThatExceptionOfType(ConfigDataLocationNotFoundException.class) - .isThrownBy(() -> this.application.run("--spring.config.location=" + location)); + .isThrownBy(() -> this.application.run("--spring.config.location=" + location)); } @Test @@ -566,13 +568,13 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { File location = new File(this.temp, "application.empty"); location.mkdirs(); assertThatNoException().isThrownBy(() -> this.application - .run("--spring.config.location=" + StringUtils.cleanPath(location.getAbsolutePath()) + "/")); + .run("--spring.config.location=" + StringUtils.cleanPath(location.getAbsolutePath()) + "/")); } @Test void runWhenConfigLocationHasMandatoryDirectoryThatDoesntExistThrowsException() { - assertThatExceptionOfType(ConfigDataLocationNotFoundException.class).isThrownBy( - () -> this.application.run("--spring.config.location=" + StringUtils.cleanPath("invalid/"))); + assertThatExceptionOfType(ConfigDataLocationNotFoundException.class) + .isThrownBy(() -> this.application.run("--spring.config.location=" + StringUtils.cleanPath("invalid/"))); } @Test @@ -580,8 +582,8 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { File location = new File(this.temp, "application.properties"); FileCopyUtils.copy(new byte[0], location); assertThatNoException() - .isThrownBy(() -> this.application.run("--spring.config.location=classpath:/application.properties," - + StringUtils.cleanPath(location.getAbsolutePath()))); + .isThrownBy(() -> this.application.run("--spring.config.location=classpath:/application.properties," + + StringUtils.cleanPath(location.getAbsolutePath()))); } @Test @@ -593,21 +595,21 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test @Disabled("Disabled until spring.profiles suppport is dropped") void runWhenUsingInvalidPropertyThrowsException() { - assertThatExceptionOfType(InvalidConfigDataPropertyException.class).isThrownBy( - () -> this.application.run("--spring.config.location=classpath:invalidproperty.properties")); + assertThatExceptionOfType(InvalidConfigDataPropertyException.class) + .isThrownBy(() -> this.application.run("--spring.config.location=classpath:invalidproperty.properties")); } @Test void runWhenImportUsesPlaceholder() { ConfigurableApplicationContext context = this.application - .run("--spring.config.location=classpath:application-import-with-placeholder.properties"); + .run("--spring.config.location=classpath:application-import-with-placeholder.properties"); assertThat(context.getEnvironment().getProperty("my.value")).isEqualTo("iwasimported"); } @Test void runWhenImportFromEarlierDocumentUsesPlaceholder() { ConfigurableApplicationContext context = this.application - .run("--spring.config.location=classpath:application-import-with-placeholder-in-document.properties"); + .run("--spring.config.location=classpath:application-import-with-placeholder-in-document.properties"); assertThat(context.getEnvironment().getProperty("my.value")).isEqualTo("iwasimported"); } @@ -615,9 +617,9 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { void runWhenImportWithProfileVariantOrdersPropertySourcesCorrectly() { this.application.setAdditionalProfiles("dev"); ConfigurableApplicationContext context = this.application - .run("--spring.config.location=classpath:application-import-with-profile-variant.properties"); + .run("--spring.config.location=classpath:application-import-with-profile-variant.properties"); assertThat(context.getEnvironment().getProperty("my.value")) - .isEqualTo("application-import-with-profile-variant-imported-dev"); + .isEqualTo("application-import-with-profile-variant-imported-dev"); } @Test @@ -626,21 +628,21 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { ConfigurableApplicationContext context = this.application.run( "--spring.config.location=classpath:application-import-with-profile-variant-and-direct-profile-import.properties"); assertThat(context.getEnvironment().getProperty("my.value")) - .isEqualTo("application-import-with-profile-variant-imported-dev"); + .isEqualTo("application-import-with-profile-variant-imported-dev"); } @Test void runWhenHasPropertyInProfileDocumentThrowsException() { assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.application.run( "--spring.config.location=classpath:application-import-with-placeholder-in-profile-document.properties")) - .withCauseInstanceOf(InactiveConfigDataAccessException.class); + .withCauseInstanceOf(InactiveConfigDataAccessException.class); } @Test // gh-29386 void runWhenHasPropertyInEarlierProfileDocumentThrowsException() { assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.application.run( "--spring.config.location=classpath:application-import-with-placeholder-in-earlier-profile-document.properties")) - .withCauseInstanceOf(InactiveConfigDataAccessException.class); + .withCauseInstanceOf(InactiveConfigDataAccessException.class); } @Test // gh-29386 @@ -648,7 +650,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { ConfigurableApplicationContext context = this.application.run( "--spring.config.location=classpath:application-import-with-placeholder-in-earlier-document.properties"); assertThat(context.getEnvironment().getProperty("my.value")) - .isEqualTo("application-import-with-placeholder-in-earlier-document-imported"); + .isEqualTo("application-import-with-placeholder-in-earlier-document-imported"); } @Test @@ -666,7 +668,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenHasIncludedProfilesActivatesProfiles() { ConfigurableApplicationContext context = this.application - .run("--spring.config.location=classpath:application-include-profiles.properties"); + .run("--spring.config.location=classpath:application-include-profiles.properties"); assertThat(context.getEnvironment().getActiveProfiles()).containsExactlyInAnyOrder("p1", "p2", "p3", "p4", "p5"); } @@ -674,7 +676,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenHasIncludedProfilesWithPlaceholderActivatesProfiles() { ConfigurableApplicationContext context = this.application - .run("--spring.config.location=classpath:application-include-profiles-with-placeholder.properties"); + .run("--spring.config.location=classpath:application-include-profiles-with-placeholder.properties"); assertThat(context.getEnvironment().getActiveProfiles()).containsExactlyInAnyOrder("p1", "p2", "p3", "p4", "p5"); } @@ -695,7 +697,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenImportingIncludesParentOrigin() { ConfigurableApplicationContext context = this.application - .run("--spring.config.location=classpath:application-import-with-placeholder.properties"); + .run("--spring.config.location=classpath:application-import-with-placeholder.properties"); Binder binder = Binder.get(context.getEnvironment()); List properties = new ArrayList<>(); BindHandler bindHandler = new BindHandler() { @@ -717,8 +719,8 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenHasWildcardLocationLoadsFromAllMatchingLocations() { - ConfigurableApplicationContext context = this.application.run( - "--spring.config.location=file:src/test/resources/config/*/", "--spring.config.name=testproperties"); + ConfigurableApplicationContext context = this.application + .run("--spring.config.location=file:src/test/resources/config/*/", "--spring.config.name=testproperties"); ConfigurableEnvironment environment = context.getEnvironment(); assertThat(environment.getProperty("first.property")).isEqualTo("apple"); assertThat(environment.getProperty("second.property")).isEqualTo("ball"); @@ -726,52 +728,52 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenOptionalWildcardLocationDoesNotExistDoesNotThrowException() { - assertThatNoException().isThrownBy(() -> this.application.run( - "--spring.config.location=optional:file:src/test/resources/nonexistent/*/testproperties.properties")); + assertThatNoException().isThrownBy(() -> this.application + .run("--spring.config.location=optional:file:src/test/resources/nonexistent/*/testproperties.properties")); } @Test void runWhenMandatoryWildcardLocationDoesNotExistThrowsException() { assertThatExceptionOfType(ConfigDataLocationNotFoundException.class).isThrownBy(() -> this.application - .run("--spring.config.location=file:src/test/resources/nonexistent/*/testproperties.properties")); + .run("--spring.config.location=file:src/test/resources/nonexistent/*/testproperties.properties")); } @Test void runWhenMandatoryWildcardLocationHasEmptyFileDirectory() { assertThatNoException() - .isThrownBy(() -> this.application.run("--spring.config.location=file:src/test/resources/config/*/")); + .isThrownBy(() -> this.application.run("--spring.config.location=file:src/test/resources/config/*/")); } @Test void runWhenMandatoryWildcardLocationHasNoSubdirectories() { - assertThatExceptionOfType(ConfigDataLocationNotFoundException.class).isThrownBy( - () -> this.application.run("--spring.config.location=file:src/test/resources/config/0-empty/*/")) - .withMessage( - "Config data location 'file:src/test/resources/config/0-empty/*/' contains no subdirectories"); + assertThatExceptionOfType(ConfigDataLocationNotFoundException.class) + .isThrownBy( + () -> this.application.run("--spring.config.location=file:src/test/resources/config/0-empty/*/")) + .withMessage("Config data location 'file:src/test/resources/config/0-empty/*/' contains no subdirectories"); } @Test void runWhenHasMandatoryWildcardLocationThatDoesNotExist() { assertThatExceptionOfType(ConfigDataLocationNotFoundException.class) - .isThrownBy(() -> this.application.run("--spring.config.location=file:invalid/*/")); + .isThrownBy(() -> this.application.run("--spring.config.location=file:invalid/*/")); } @Test void runWhenHasOptionalWildcardLocationThatDoesNotExistDoesNotThrow() { assertThatNoException() - .isThrownBy(() -> this.application.run("--spring.config.location=optional:file:invalid/*/")); + .isThrownBy(() -> this.application.run("--spring.config.location=optional:file:invalid/*/")); } @Test void runWhenOptionalWildcardLocationHasNoSubdirectoriesDoesNotThrow() { assertThatNoException().isThrownBy(() -> this.application - .run("--spring.config.location=optional:file:src/test/resources/config/0-empty/*/")); + .run("--spring.config.location=optional:file:src/test/resources/config/0-empty/*/")); } @Test // gh-24990 void runWhenHasProfileSpecificFileWithActiveOnProfileProperty() { ConfigurableApplicationContext context = this.application - .run("--spring.config.name=application-activate-on-profile-in-profile-specific-file"); + .run("--spring.config.name=application-activate-on-profile-in-profile-specific-file"); ConfigurableEnvironment environment = context.getEnvironment(); assertThat(environment.getProperty("test1")).isEqualTo("test1"); assertThat(environment.getProperty("test2")).isEqualTo("test2"); @@ -780,7 +782,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test // gh-26960 void runWhenHasProfileSpecificImportWithImportImportsSecondProfileSpecificFile() { ConfigurableApplicationContext context = this.application - .run("--spring.config.name=application-profile-specific-import-with-import"); + .run("--spring.config.name=application-profile-specific-import-with-import"); ConfigurableEnvironment environment = context.getEnvironment(); assertThat(environment.containsProperty("application-profile-specific-import-with-import")).isTrue(); assertThat(environment.containsProperty("application-profile-specific-import-with-import-p1")).isTrue(); @@ -793,7 +795,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test // gh-26960 void runWhenHasProfileSpecificImportWithCustomImportResolvesProfileSpecific() { ConfigurableApplicationContext context = this.application - .run("--spring.config.name=application-profile-specific-import-with-custom-import"); + .run("--spring.config.name=application-profile-specific-import-with-custom-import"); ConfigurableEnvironment environment = context.getEnvironment(); assertThat(environment.containsProperty("test:boot")).isTrue(); assertThat(environment.containsProperty("test:boot:ps")).isTrue(); @@ -802,7 +804,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test // gh-26593 void runWhenHasFilesInRootAndConfigWithProfiles() { ConfigurableApplicationContext context = this.application - .run("--spring.config.name=file-in-root-and-config-with-profile", "--spring.profiles.active=p1,p2"); + .run("--spring.config.name=file-in-root-and-config-with-profile", "--spring.profiles.active=p1,p2"); ConfigurableEnvironment environment = context.getEnvironment(); assertThat(environment.containsProperty("file-in-root-and-config-with-profile")).isTrue(); assertThat(environment.containsProperty("file-in-root-and-config-with-profile-p1")).isTrue(); 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 a449df1318..e0981adb56 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -100,8 +100,8 @@ class ConfigDataEnvironmentPostProcessorTests { this.application.setAdditionalProfiles("dev"); willReturn(this.configDataEnvironment).given(this.postProcessor).getConfigDataEnvironment(any(), any(), any()); this.postProcessor.postProcessEnvironment(this.environment, this.application); - then(this.postProcessor).should().getConfigDataEnvironment(any(), any(), - this.additionalProfilesCaptor.capture()); + then(this.postProcessor).should() + .getConfigDataEnvironment(any(), any(), this.additionalProfilesCaptor.capture()); then(this.configDataEnvironment).should().processAndApply(); assertThat(this.additionalProfilesCaptor.getValue()).containsExactly("dev"); } @@ -120,7 +120,7 @@ class ConfigDataEnvironmentPostProcessorTests { ConfigDataEnvironmentPostProcessor.LegacyConfigFileApplicationListener legacyListener = mock( ConfigDataEnvironmentPostProcessor.LegacyConfigFileApplicationListener.class); willThrow(new UseLegacyConfigProcessingException(null)).given(this.postProcessor) - .getConfigDataEnvironment(any(), any(), any()); + .getConfigDataEnvironment(any(), any(), any()); willReturn(legacyListener).given(this.postProcessor).getLegacyListener(); this.postProcessor.postProcessEnvironment(this.environment, this.application); then(this.configDataEnvironment).shouldHaveNoInteractions(); @@ -134,7 +134,7 @@ class ConfigDataEnvironmentPostProcessorTests { ConfigDataEnvironmentPostProcessor.LegacyConfigFileApplicationListener legacyListener = mock( ConfigDataEnvironmentPostProcessor.LegacyConfigFileApplicationListener.class); willThrow(new UseLegacyConfigProcessingException(null)).given(this.postProcessor) - .getConfigDataEnvironment(any(), any(), any()); + .getConfigDataEnvironment(any(), any(), any()); willReturn(legacyListener).given(this.postProcessor).getLegacyListener(); this.postProcessor.postProcessEnvironment(this.environment, this.application); then(this.configDataEnvironment).shouldHaveNoInteractions(); @@ -153,7 +153,7 @@ class ConfigDataEnvironmentPostProcessorTests { assertThat(listener.getAddedPropertySources()).hasSizeGreaterThan(0); assertThat(listener.getProfiles().getActive()).containsExactly("dev"); assertThat(listener.getAddedPropertySources().stream().anyMatch((added) -> hasDevProfile(added.getResource()))) - .isTrue(); + .isTrue(); } private boolean hasDevProfile(ConfigDataResource resource) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentTests.java index 9b4430682f..db19c960f7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,8 +71,8 @@ class ConfigDataEnvironmentTests { void createWhenUseLegacyPropertyInEnvironmentThrowsException() { this.environment.setProperty("spring.config.use-legacy-processing", "true"); assertThatExceptionOfType(UseLegacyConfigProcessingException.class) - .isThrownBy(() -> new ConfigDataEnvironment(this.logFactory, this.bootstrapContext, this.environment, - this.resourceLoader, this.additionalProfiles, null)); + .isThrownBy(() -> new ConfigDataEnvironment(this.logFactory, this.bootstrapContext, this.environment, + this.resourceLoader, this.additionalProfiles, null)); } @Test @@ -81,7 +81,7 @@ class ConfigDataEnvironmentTests { TestConfigDataEnvironment configDataEnvironment = new TestConfigDataEnvironment(this.logFactory, this.bootstrapContext, this.environment, this.resourceLoader, this.additionalProfiles, null); assertThat(configDataEnvironment.getConfigDataLocationResolversBinder().bind("spring", String.class).get()) - .isEqualTo("boot"); + .isEqualTo("boot"); } @Test @@ -94,10 +94,13 @@ class ConfigDataEnvironmentTests { this.environment.getPropertySources().addLast(propertySource3); ConfigDataEnvironment configDataEnvironment = new ConfigDataEnvironment(this.logFactory, this.bootstrapContext, this.environment, this.resourceLoader, this.additionalProfiles, null); - List children = configDataEnvironment.getContributors().getRoot() - .getChildren(ImportPhase.BEFORE_PROFILE_ACTIVATION); - Object[] wrapped = children.stream().filter((child) -> child.getKind() == Kind.EXISTING) - .map(ConfigDataEnvironmentContributor::getPropertySource).toArray(); + List children = configDataEnvironment.getContributors() + .getRoot() + .getChildren(ImportPhase.BEFORE_PROFILE_ACTIVATION); + Object[] wrapped = children.stream() + .filter((child) -> child.getKind() == Kind.EXISTING) + .map(ConfigDataEnvironmentContributor::getPropertySource) + .toArray(); assertThat(wrapped[1]).isEqualTo(propertySource1); assertThat(wrapped[2]).isEqualTo(propertySource2); assertThat(wrapped[3]).isEqualTo(propertySource3); @@ -113,10 +116,13 @@ class ConfigDataEnvironmentTests { this.environment.getPropertySources().addLast(propertySource2); ConfigDataEnvironment configDataEnvironment = new ConfigDataEnvironment(this.logFactory, this.bootstrapContext, this.environment, this.resourceLoader, this.additionalProfiles, null); - List children = configDataEnvironment.getContributors().getRoot() - .getChildren(ImportPhase.BEFORE_PROFILE_ACTIVATION); - Object[] wrapped = children.stream().filter((child) -> child.getKind() == Kind.EXISTING) - .map(ConfigDataEnvironmentContributor::getPropertySource).toArray(); + List children = configDataEnvironment.getContributors() + .getRoot() + .getChildren(ImportPhase.BEFORE_PROFILE_ACTIVATION); + Object[] wrapped = children.stream() + .filter((child) -> child.getKind() == Kind.EXISTING) + .map(ConfigDataEnvironmentContributor::getPropertySource) + .toArray(); assertThat(wrapped[1]).isEqualTo(propertySource1); assertThat(wrapped[2]).isEqualTo(propertySource2); assertThat(wrapped[3]).isEqualTo(defaultPropertySource); @@ -129,10 +135,14 @@ class ConfigDataEnvironmentTests { this.environment.setProperty("spring.config.import", "i1,i2"); ConfigDataEnvironment configDataEnvironment = new ConfigDataEnvironment(this.logFactory, this.bootstrapContext, this.environment, this.resourceLoader, this.additionalProfiles, null); - List children = configDataEnvironment.getContributors().getRoot() - .getChildren(ImportPhase.BEFORE_PROFILE_ACTIVATION); - Object[] imports = children.stream().filter((child) -> child.getKind() == Kind.INITIAL_IMPORT) - .map(ConfigDataEnvironmentContributor::getImports).map(Object::toString).toArray(); + List children = configDataEnvironment.getContributors() + .getRoot() + .getChildren(ImportPhase.BEFORE_PROFILE_ACTIVATION); + Object[] imports = children.stream() + .filter((child) -> child.getKind() == Kind.INITIAL_IMPORT) + .map(ConfigDataEnvironmentContributor::getImports) + .map(Object::toString) + .toArray(); assertThat(imports).containsExactly("[i2]", "[i1]", "[a2]", "[a1]", "[l2]", "[l1]"); } @@ -239,7 +249,7 @@ class ConfigDataEnvironmentTests { }; assertThatExceptionOfType(InactiveConfigDataAccessException.class) - .isThrownBy(configDataEnvironment::processAndApply); + .isThrownBy(configDataEnvironment::processAndApply); } @ParameterizedTest @@ -297,7 +307,7 @@ class ConfigDataEnvironmentTests { ConfigDataEnvironment configDataEnvironment = new ConfigDataEnvironment(this.logFactory, this.bootstrapContext, this.environment, this.resourceLoader, this.additionalProfiles, null); assertThatExceptionOfType(InvalidConfigDataPropertyException.class) - .isThrownBy(() -> configDataEnvironment.processAndApply()); + .isThrownBy(() -> configDataEnvironment.processAndApply()); } @Test @@ -312,7 +322,7 @@ class ConfigDataEnvironmentTests { assertThat(addedPropertySource.getPropertySource().getProperty("spring")).isEqualTo("boot"); assertThat(addedPropertySource.getLocation().toString()).isEqualTo(getConfigLocation(info)); assertThat(addedPropertySource.getResource().toString()).contains("class path resource") - .contains(info.getTestMethod().get().getName()); + .contains(info.getTestMethod().get().getName()); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataImporterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataImporterTests.java index 73082f3f6a..5617644e8c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataImporterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataImporterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,15 +81,17 @@ class ConfigDataImporterTests { ConfigData configData1 = new ConfigData(Collections.singleton(new MockPropertySource())); ConfigData configData2 = new ConfigData(Collections.singleton(new MockPropertySource())); given(this.resolvers.resolve(this.locationResolverContext, location1, this.profiles)) - .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location1, resource1, false))); + .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location1, resource1, false))); given(this.resolvers.resolve(this.locationResolverContext, location2, this.profiles)) - .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location2, resource2, false))); + .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location2, resource2, false))); given(this.loaders.load(this.loaderContext, resource1)).willReturn(configData1); given(this.loaders.load(this.loaderContext, resource2)).willReturn(configData2); ConfigDataImporter importer = new ConfigDataImporter(this.logFactory, ConfigDataNotFoundAction.FAIL, this.resolvers, this.loaders); - Collection loaded = importer.resolveAndLoad(this.activationContext, this.locationResolverContext, - this.loaderContext, Arrays.asList(location1, location2)).values(); + Collection loaded = importer + .resolveAndLoad(this.activationContext, this.locationResolverContext, this.loaderContext, + Arrays.asList(location1, location2)) + .values(); assertThat(loaded).containsExactly(configData2, configData1); } @@ -107,20 +109,22 @@ class ConfigDataImporterTests { ConfigData configData2 = new ConfigData(Collections.singleton(new MockPropertySource())); ConfigData configData3 = new ConfigData(Collections.singleton(new MockPropertySource())); given(this.resolvers.resolve(this.locationResolverContext, location1, this.profiles)) - .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location1, resource1, false))); + .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location1, resource1, false))); given(this.resolvers.resolve(this.locationResolverContext, location2, this.profiles)) - .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location2, resource2, false))); + .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location2, resource2, false))); given(this.resolvers.resolve(this.locationResolverContext, location3, this.profiles)) - .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location3, resource3, false))); + .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location3, resource3, false))); given(this.loaders.load(this.loaderContext, resource1)).willReturn(configData1); given(this.loaders.load(this.loaderContext, resource2)).willReturn(configData2); given(this.loaders.load(this.loaderContext, resource3)).willReturn(configData3); ConfigDataImporter importer = new ConfigDataImporter(this.logFactory, ConfigDataNotFoundAction.FAIL, this.resolvers, this.loaders); - Collection loaded1and2 = importer.resolveAndLoad(this.activationContext, - this.locationResolverContext, this.loaderContext, locations1and2).values(); - Collection loaded2and3 = importer.resolveAndLoad(this.activationContext, - this.locationResolverContext, this.loaderContext, locations2and3).values(); + Collection loaded1and2 = importer + .resolveAndLoad(this.activationContext, this.locationResolverContext, this.loaderContext, locations1and2) + .values(); + Collection loaded2and3 = importer + .resolveAndLoad(this.activationContext, this.locationResolverContext, this.loaderContext, locations2and3) + .values(); assertThat(loaded1and2).containsExactly(configData2, configData1); assertThat(loaded2and3).containsExactly(configData3); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLoadersTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLoadersTests.java index 3bd6ad6a98..ca829ed76e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLoadersTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLoadersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,8 +61,9 @@ class ConfigDataLoadersTests { void createWhenLoaderHasDeferredLogFactoryParameterInjectsDeferredLogFactory() { ConfigDataLoaders loaders = new ConfigDataLoaders(this.logFactory, this.bootstrapContext, null, Arrays.asList(DeferredLogFactoryConfigDataLoader.class.getName())); - assertThat(loaders).extracting("loaders").asList() - .satisfies(this::containsValidDeferredLogFactoryConfigDataLoader); + assertThat(loaders).extracting("loaders") + .asList() + .satisfies(this::containsValidDeferredLogFactoryConfigDataLoader); } private void containsValidDeferredLogFactoryConfigDataLoader(List list) { @@ -93,7 +94,7 @@ class ConfigDataLoadersTests { ConfigDataLoaders loaders = new ConfigDataLoaders(this.logFactory, this.bootstrapContext, null, Arrays.asList(LoggingConfigDataLoader.class.getName(), TestConfigDataLoader.class.getName())); assertThatIllegalStateException().isThrownBy(() -> loaders.load(this.context, location)) - .withMessageContaining("Multiple loaders found for resource 'test'"); + .withMessageContaining("Multiple loaders found for resource 'test'"); } @Test @@ -102,7 +103,7 @@ class ConfigDataLoadersTests { ConfigDataLoaders loaders = new ConfigDataLoaders(this.logFactory, this.bootstrapContext, null, Arrays.asList(NonLoadableConfigDataLoader.class.getName())); assertThatIllegalStateException().isThrownBy(() -> loaders.load(this.context, location)) - .withMessage("No loader found for resource 'test'"); + .withMessage("No loader found for resource 'test'"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationBindHandlerTests.java index 254326e610..2cfa963d0e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationBindHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -126,13 +126,13 @@ class ConfigDataLocationBindHandlerTests { ValueObject bound = binder.bind("test", VALUE_OBJECT, this.handler).get(); assertThat(bound.getLocation(0)).hasToString("a"); assertThat(bound.getLocation(0).getOrigin()) - .hasToString("\"test.locations[0]\" from property source \"source\""); + .hasToString("\"test.locations[0]\" from property source \"source\""); assertThat(bound.getLocation(1)).hasToString("b"); assertThat(bound.getLocation(1).getOrigin()) - .hasToString("\"test.locations[1]\" from property source \"source\""); + .hasToString("\"test.locations[1]\" from property source \"source\""); assertThat(bound.getLocation(2)).hasToString("c"); assertThat(bound.getLocation(2).getOrigin()) - .hasToString("\"test.locations[2]\" from property source \"source\""); + .hasToString("\"test.locations[2]\" from property source \"source\""); } static class ValueObject { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationNotFoundExceptionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationNotFoundExceptionTests.java index ff1ffbcd01..6adc60b5d6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationNotFoundExceptionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationNotFoundExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ class ConfigDataLocationNotFoundExceptionTests { @Test void createWhenLocationIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigDataLocationNotFoundException(null)) - .withMessage("Location must not be null"); + .withMessage("Location must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationResolversTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationResolversTests.java index 169101a8d6..42494c3192 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationResolversTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationResolversTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -107,9 +107,11 @@ class ConfigDataLocationResolversTests { @Test void createWhenNameIsNotConfigDataLocationResolverThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ConfigDataLocationResolvers(this.logFactory, this.bootstrapContext, this.binder, - this.resourceLoader, Collections.singletonList(InputStream.class.getName()))) - .withMessageContaining("Unable to instantiate").havingCause().withMessageContaining("not assignable"); + .isThrownBy(() -> new ConfigDataLocationResolvers(this.logFactory, this.bootstrapContext, this.binder, + this.resourceLoader, Collections.singletonList(InputStream.class.getName()))) + .withMessageContaining("Unable to instantiate") + .havingCause() + .withMessageContaining("not assignable"); } @Test @@ -164,8 +166,8 @@ class ConfigDataLocationResolversTests { Arrays.asList(LowestTestResolver.class.getName(), HighestTestResolver.class.getName())); ConfigDataLocation location = ConfigDataLocation.of("Missing:test"); assertThatExceptionOfType(UnsupportedConfigDataLocationException.class) - .isThrownBy(() -> resolvers.resolve(this.context, location, null)) - .satisfies((ex) -> assertThat(ex.getLocation()).isEqualTo(location)); + .isThrownBy(() -> resolvers.resolve(this.context, location, null)) + .satisfies((ex) -> assertThat(ex.getLocation()).isEqualTo(location)); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataNotFoundFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataNotFoundFailureAnalyzerTests.java index 78035672ac..9446c98334 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataNotFoundFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataNotFoundFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,7 +40,7 @@ class ConfigDataNotFoundFailureAnalyzerTests { FailureAnalysis result = this.analyzer.analyze(exception); assertThat(result.getDescription()).isEqualTo("Config data location 'test' does not exist"); assertThat(result.getAction()) - .isEqualTo("Check that the value 'test' is correct, or prefix it with 'optional:'"); + .isEqualTo("Check that the value 'test' is correct, or prefix it with 'optional:'"); } @Test @@ -59,7 +59,7 @@ class ConfigDataNotFoundFailureAnalyzerTests { FailureAnalysis result = this.analyzer.analyze(exception); assertThat(result.getDescription()).isEqualTo("Config data location 'test' does not exist"); assertThat(result.getAction()) - .isEqualTo("Check that the value 'test' at origin is correct, or prefix it with 'optional:'"); + .isEqualTo("Check that the value 'test' at origin is correct, or prefix it with 'optional:'"); } @Test @@ -76,12 +76,12 @@ class ConfigDataNotFoundFailureAnalyzerTests { ConfigDataLocation location = ConfigDataLocation.of("test"); ConfigDataResource resource = new TestConfigDataResource("myresource"); ConfigDataResourceNotFoundException exception = new ConfigDataResourceNotFoundException(resource) - .withLocation(location); + .withLocation(location); FailureAnalysis result = this.analyzer.analyze(exception); assertThat(result.getDescription()) - .isEqualTo("Config data resource 'myresource' via location 'test' does not exist"); + .isEqualTo("Config data resource 'myresource' via location 'test' does not exist"); assertThat(result.getAction()) - .isEqualTo("Check that the value 'test' is correct, or prefix it with 'optional:'"); + .isEqualTo("Check that the value 'test' is correct, or prefix it with 'optional:'"); } static class TestOrigin implements Origin { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataPropertiesTests.java index 2c9cd2c6c6..df6ede14a8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -211,7 +211,7 @@ class ConfigDataPropertiesTests { source.put("spring.config.activate.on-profile", "a | b"); Binder binder = new Binder(source); assertThatExceptionOfType(InvalidConfigDataPropertyException.class) - .isThrownBy(() -> ConfigDataProperties.get(binder)); + .isThrownBy(() -> ConfigDataProperties.get(binder)); } @Test @@ -221,7 +221,7 @@ class ConfigDataPropertiesTests { Binder binder = new Binder(source); ConfigDataProperties properties = ConfigDataProperties.get(binder); assertThat(properties.getImports().get(1).getOrigin()) - .hasToString("\"spring.config.import\" from property source \"source\""); + .hasToString("\"spring.config.import\" from property source \"source\""); } @Test @@ -233,7 +233,7 @@ class ConfigDataPropertiesTests { Binder binder = new Binder(source); ConfigDataProperties properties = ConfigDataProperties.get(binder); assertThat(properties.getImports().get(1).getOrigin()) - .hasToString("\"spring.config.import[1]\" from property source \"source\""); + .hasToString("\"spring.config.import[1]\" from property source \"source\""); } private Profiles createTestProfiles() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataResourceNotFoundExceptionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataResourceNotFoundExceptionTests.java index 14cb46447c..155fb2b80a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataResourceNotFoundExceptionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataResourceNotFoundExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,7 +63,7 @@ class ConfigDataResourceNotFoundExceptionTests { @Test void createWhenResourceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigDataResourceNotFoundException(null)) - .withMessage("Resource must not be null"); + .withMessage("Resource must not be null"); } @Test @@ -95,7 +95,7 @@ class ConfigDataResourceNotFoundExceptionTests { @Test void getLocationWhenHasLocationReturnsLocation() { ConfigDataResourceNotFoundException exception = new ConfigDataResourceNotFoundException(this.resource) - .withLocation(this.location); + .withLocation(this.location); assertThat(exception.getLocation()).isSameAs(this.location); } @@ -108,15 +108,15 @@ class ConfigDataResourceNotFoundExceptionTests { @Test void getReferenceDescriptionWhenHasLocationReturnsDescription() { ConfigDataResourceNotFoundException exception = new ConfigDataResourceNotFoundException(this.resource) - .withLocation(this.location); + .withLocation(this.location); assertThat(exception.getReferenceDescription()) - .isEqualTo("resource 'mytestresource' via location 'optional:test'"); + .isEqualTo("resource 'mytestresource' via location 'optional:test'"); } @Test void withLocationReturnsNewInstanceWithLocation() { ConfigDataResourceNotFoundException exception = new ConfigDataResourceNotFoundException(this.resource) - .withLocation(this.location); + .withLocation(this.location); assertThat(exception.getLocation()).isSameAs(this.location); } @@ -140,7 +140,7 @@ class ConfigDataResourceNotFoundExceptionTests { @Test void throwIfDoesNotExistWhenFileDoesNotExistThrowsException() { assertThatExceptionOfType(ConfigDataResourceNotFoundException.class) - .isThrownBy(() -> ConfigDataResourceNotFoundException.throwIfDoesNotExist(this.resource, this.missing)); + .isThrownBy(() -> ConfigDataResourceNotFoundException.throwIfDoesNotExist(this.resource, this.missing)); } @Test @@ -151,8 +151,8 @@ class ConfigDataResourceNotFoundExceptionTests { @Test void throwIfDoesNotExistWhenResourceDoesNotExistThrowsException() { assertThatExceptionOfType(ConfigDataResourceNotFoundException.class) - .isThrownBy(() -> ConfigDataResourceNotFoundException.throwIfDoesNotExist(this.resource, - new FileSystemResource(this.missing))); + .isThrownBy(() -> ConfigDataResourceNotFoundException.throwIfDoesNotExist(this.resource, + new FileSystemResource(this.missing))); } static class TestConfigDataResource extends ConfigDataResource { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataTests.java index fb5d507fd6..52d9980e05 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,13 +45,13 @@ class ConfigDataTests { @Test void createWhenPropertySourcesIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigData(null)) - .withMessage("PropertySources must not be null"); + .withMessage("PropertySources must not be null"); } @Test void createWhenOptionsIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigData(Collections.emptyList(), (Option[]) null)) - .withMessage("Options must not be null"); + .withMessage("Options must not be null"); } @Test @@ -81,7 +81,7 @@ class ConfigDataTests { PropertySourceOptions propertySourceOptions = (propertySource) -> Options.NONE; ConfigData configData = new ConfigData(Collections.singleton(source), propertySourceOptions); assertThatIllegalStateException().isThrownBy(() -> configData.getOptions()) - .withMessage("No global options defined"); + .withMessage("No global options defined"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java index 8a872a3c23..dbd5f7d76e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java @@ -307,7 +307,7 @@ class ConfigFileApplicationListenerTests { @Test void commandLineWins() { this.environment.getPropertySources() - .addFirst(new SimpleCommandLinePropertySource("--the.property=fromcommandline")); + .addFirst(new SimpleCommandLinePropertySource("--the.property=fromcommandline")); this.initializer.setSearchNames("testproperties"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); @@ -326,7 +326,7 @@ class ConfigFileApplicationListenerTests { @Test void defaultPropertyAsFallback() { this.environment.getPropertySources() - .addLast(new MapPropertySource("defaultProperties", Collections.singletonMap("my.fallback", "foo"))); + .addLast(new MapPropertySource("defaultProperties", Collections.singletonMap("my.fallback", "foo"))); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.fallback"); assertThat(property).isEqualTo("foo"); @@ -334,8 +334,9 @@ class ConfigFileApplicationListenerTests { @Test void defaultPropertyAsFallbackDuringFileParsing() { - this.environment.getPropertySources().addLast(new MapPropertySource("defaultProperties", - Collections.singletonMap("spring.config.name", "testproperties"))); + this.environment.getPropertySources() + .addLast(new MapPropertySource("defaultProperties", + Collections.singletonMap("spring.config.name", "testproperties"))); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); assertThat(property).isEqualTo("frompropertiesfile"); @@ -344,8 +345,9 @@ class ConfigFileApplicationListenerTests { @Test void activeProfilesFromDefaultPropertiesShouldNotTakePrecedence() { this.initializer.setSearchNames("enableprofile"); - this.environment.getPropertySources().addLast( - new MapPropertySource("defaultProperties", Collections.singletonMap("spring.profiles.active", "dev"))); + this.environment.getPropertySources() + .addLast(new MapPropertySource("defaultProperties", + Collections.singletonMap("spring.profiles.active", "dev"))); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).containsExactly("myprofile"); } @@ -355,8 +357,9 @@ class ConfigFileApplicationListenerTests { // required? TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=morespecific"); - this.environment.getPropertySources().addLast( - new MapPropertySource("defaultProperties", Collections.singletonMap("spring.profiles.include", "dev"))); + this.environment.getPropertySources() + .addLast(new MapPropertySource("defaultProperties", + Collections.singletonMap("spring.profiles.include", "dev"))); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).containsExactly("dev", "morespecific", "yetmorespecific"); } @@ -521,7 +524,9 @@ class ConfigFileApplicationListenerTests { String string = ".properties)"; return "Loaded config file '" + new File(this.buildOutput.getTestResourcesLocation(), "application" + suffix + ".properties") - .getAbsoluteFile().toURI().toString() + .getAbsoluteFile() + .toURI() + .toString() + "' (classpath:/application" + suffix + string; } @@ -602,7 +607,8 @@ class ConfigFileApplicationListenerTests { assertThat(this.environment.getActiveProfiles()).contains("dev"); assertThat(property).isEqualTo("fromdevprofile"); List names = StreamSupport.stream(this.environment.getPropertySources().spliterator(), false) - .map(org.springframework.core.env.PropertySource::getName).collect(Collectors.toList()); + .map(org.springframework.core.env.PropertySource::getName) + .collect(Collectors.toList()); assertThat(names).contains("applicationConfig: [classpath:/testsetprofiles.yml] (document #0)", "applicationConfig: [classpath:/testsetprofiles.yml] (document #1)"); } @@ -654,10 +660,10 @@ class ConfigFileApplicationListenerTests { String property = this.environment.getProperty("the.property"); assertThat(property).isEqualTo("fromspecificlocation"); assertThat(this.environment) - .has(matchingPropertySource("applicationConfig: [classpath:specificlocation.properties]")); + .has(matchingPropertySource("applicationConfig: [classpath:specificlocation.properties]")); // The default property source is not there assertThat(this.environment) - .doesNotHave(matchingPropertySource("applicationConfig: [classpath:/application.properties]")); + .doesNotHave(matchingPropertySource("applicationConfig: [classpath:/application.properties]")); assertThat(this.environment.getProperty("foo")).isNull(); } @@ -670,10 +676,10 @@ class ConfigFileApplicationListenerTests { String property = this.environment.getProperty("the.property"); assertThat(property).isEqualTo("fromspecificlocation"); assertThat(this.environment) - .has(matchingPropertySource("applicationConfig: [classpath:specificlocation.properties]")); + .has(matchingPropertySource("applicationConfig: [classpath:specificlocation.properties]")); // The default property source is still there assertThat(this.environment) - .has(matchingPropertySource("applicationConfig: [classpath:/application.properties]")); + .has(matchingPropertySource("applicationConfig: [classpath:/application.properties]")); assertThat(this.environment.getProperty("foo")).isEqualTo("bucket"); } @@ -698,13 +704,13 @@ class ConfigFileApplicationListenerTests { @Test void absoluteResourceDefaultsToFile() { // ? - String location = new File("src/test/resources/specificlocation.properties").getAbsolutePath().replace("\\", - "/"); + String location = new File("src/test/resources/specificlocation.properties").getAbsolutePath() + .replace("\\", "/"); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=" + location); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment).has( - matchingPropertySource("applicationConfig: [file:" + location.replace(File.separatorChar, '/') + "]")); + assertThat(this.environment) + .has(matchingPropertySource("applicationConfig: [file:" + location.replace(File.separatorChar, '/') + "]")); } @Test @@ -712,8 +718,8 @@ class ConfigFileApplicationListenerTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=classpath*:override.properties"); assertThatIllegalStateException() - .isThrownBy(() -> this.initializer.postProcessEnvironment(this.environment, this.application)) - .withMessage("Classpath wildcard patterns cannot be used as a search location"); + .isThrownBy(() -> this.initializer.postProcessEnvironment(this.environment, this.application)) + .withMessage("Classpath wildcard patterns cannot be used as a search location"); } @Test @@ -726,7 +732,7 @@ class ConfigFileApplicationListenerTests { property = context.getEnvironment().getProperty("my.property"); assertThat(property).isEqualTo("fromapplicationproperties"); assertThat(context.getEnvironment()) - .has(matchingPropertySource("class path resource [specificlocation.properties]")); + .has(matchingPropertySource("class path resource [specificlocation.properties]")); context.close(); } @@ -740,7 +746,7 @@ class ConfigFileApplicationListenerTests { String property = context.getEnvironment().getProperty("the.property"); assertThat(property).isEqualTo("fromspecificlocation"); assertThat(context.getEnvironment()) - .has(matchingPropertySource("class path resource [specificlocation.properties]")); + .has(matchingPropertySource("class path resource [specificlocation.properties]")); context.close(); } @@ -763,9 +769,9 @@ class ConfigFileApplicationListenerTests { String property = context.getEnvironment().getProperty("the.property"); assertThat(property).isEqualTo("frompropertiesfile"); assertThat(context.getEnvironment()) - .has(matchingPropertySource("class path resource [enableprofile.properties]")); + .has(matchingPropertySource("class path resource [enableprofile.properties]")); assertThat(context.getEnvironment()) - .doesNotHave(matchingPropertySource("classpath:/enableprofile-myprofile.properties")); + .doesNotHave(matchingPropertySource("classpath:/enableprofile-myprofile.properties")); context.close(); } @@ -777,7 +783,7 @@ class ConfigFileApplicationListenerTests { String property = context.getEnvironment().getProperty("my.property"); assertThat(property).isEqualTo("fromapplicationproperties"); assertThat(context.getEnvironment()) - .doesNotHave(matchingPropertySource("classpath:/enableprofile-myprofile.properties")); + .doesNotHave(matchingPropertySource("classpath:/enableprofile-myprofile.properties")); context.close(); } @@ -789,7 +795,7 @@ class ConfigFileApplicationListenerTests { String property = context.getEnvironment().getProperty("the.property"); assertThat(property).isEqualTo("frommorepropertiesfile"); assertThat(context.getEnvironment()) - .has(matchingPropertySource("class path resource [specificlocation.properties]")); + .has(matchingPropertySource("class path resource [specificlocation.properties]")); context.close(); } @@ -835,7 +841,7 @@ class ConfigFileApplicationListenerTests { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application - .run("--spring.profiles.active=activeprofilewithdifferentsubdoc,activeprofilewithdifferentsubdoc2"); + .run("--spring.profiles.active=activeprofilewithdifferentsubdoc,activeprofilewithdifferentsubdoc2"); String property = this.context.getEnvironment().getProperty("foobar"); assertThat(property).isEqualTo("baz"); } @@ -1016,9 +1022,9 @@ class ConfigFileApplicationListenerTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=" + location); assertThatIllegalStateException() - .isThrownBy(() -> this.initializer.postProcessEnvironment(this.environment, this.application)) - .withMessageContaining(location) - .withMessageContaining("If the location is meant to reference a directory, it must end in '/'"); + .isThrownBy(() -> this.initializer.postProcessEnvironment(this.environment, this.application)) + .withMessageContaining(location) + .withMessageContaining("If the location is meant to reference a directory, it must end in '/'"); } @Test @@ -1035,8 +1041,9 @@ class ConfigFileApplicationListenerTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=" + location); assertThatIllegalStateException() - .isThrownBy(() -> this.initializer.postProcessEnvironment(this.environment, this.application)) - .withMessageStartingWith("Search location '").withMessageEndingWith("' must end with '*/'"); + .isThrownBy(() -> this.initializer.postProcessEnvironment(this.environment, this.application)) + .withMessageStartingWith("Search location '") + .withMessageEndingWith("' must end with '*/'"); } @Test @@ -1044,8 +1051,8 @@ class ConfigFileApplicationListenerTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=file:src/test/resources/", "spring.config.name=*/application"); assertThatIllegalStateException() - .isThrownBy(() -> this.initializer.postProcessEnvironment(this.environment, this.application)) - .withMessage("Config name '*/application' cannot contain wildcards"); + .isThrownBy(() -> this.initializer.postProcessEnvironment(this.environment, this.application)) + .withMessage("Config name '*/application' cannot contain wildcards"); } @Test @@ -1062,9 +1069,9 @@ class ConfigFileApplicationListenerTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=" + location); assertThatIllegalStateException() - .isThrownBy(() -> this.initializer.postProcessEnvironment(this.environment, this.application)) - .withMessageStartingWith("Search location '") - .withMessageEndingWith("' cannot contain multiple wildcards"); + .isThrownBy(() -> this.initializer.postProcessEnvironment(this.environment, this.application)) + .withMessageStartingWith("Search location '") + .withMessageEndingWith("' cannot contain multiple wildcards"); } @Test @@ -1117,13 +1124,16 @@ class ConfigFileApplicationListenerTests { "spring.config.location=" + location); this.initializer.setSearchNames("testproperties"); this.initializer.postProcessEnvironment(this.environment, this.application); - List sources = this.environment.getPropertySources().stream() - .filter((source) -> source.getName().contains("applicationConfig")).map((source) -> { - String name = source.getName(); - name = name.substring(name.indexOf("src/test/resources")); - name = name.substring(0, name.length() - 1); - return name; - }).collect(Collectors.toList()); + List sources = this.environment.getPropertySources() + .stream() + .filter((source) -> source.getName().contains("applicationConfig")) + .map((source) -> { + String name = source.getName(); + name = name.substring(name.indexOf("src/test/resources")); + name = name.substring(0, name.length() - 1); + return name; + }) + .collect(Collectors.toList()); assertThat(sources).containsExactly("src/test/resources/config/1-first/testproperties.properties", "src/test/resources/config/2-second/testproperties.properties"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataLoaderTests.java index 81821653af..da878cb519 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,7 +64,7 @@ class ConfigTreeConfigDataLoaderTests { File missing = this.directory.resolve("missing").toFile(); ConfigTreeConfigDataResource location = new ConfigTreeConfigDataResource(missing.toString()); assertThatExceptionOfType(ConfigDataResourceNotFoundException.class) - .isThrownBy(() -> this.loader.load(this.loaderContext, location)); + .isThrownBy(() -> this.loader.load(this.loaderContext, location)); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataLocationResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataLocationResolverTests.java index 206c76d0c2..2ee6b8c28f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataLocationResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataLocationResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,7 +61,7 @@ class ConfigTreeConfigDataLocationResolverTests { ConfigDataLocation.of("configtree:/etc/config/")); assertThat(locations.size()).isEqualTo(1); assertThat(locations).extracting(Object::toString) - .containsExactly("config tree [" + new File("/etc/config").getAbsolutePath() + "]"); + .containsExactly("config tree [" + new File("/etc/config").getAbsolutePath() + "]"); } @Test @@ -75,9 +75,9 @@ class ConfigTreeConfigDataLocationResolverTests { List locations = this.resolver.resolve(this.context, ConfigDataLocation.of("configtree:" + this.temp.getAbsolutePath() + "/*/")); assertThat(locations.size()).isEqualTo(2); - assertThat(locations).extracting(Object::toString).containsExactly( - "config tree [" + directoryA.getAbsolutePath() + "]", - "config tree [" + directoryB.getAbsolutePath() + "]"); + assertThat(locations).extracting(Object::toString) + .containsExactly("config tree [" + directoryA.getAbsolutePath() + "]", + "config tree [" + directoryB.getAbsolutePath() + "]"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataResourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataResourceTests.java index 58375348d9..b5bbac455a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataResourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataResourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,13 +35,13 @@ class ConfigTreeConfigDataResourceTests { @Test void constructorWhenPathStringIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigTreeConfigDataResource((String) null)) - .withMessage("Path must not be null"); + .withMessage("Path must not be null"); } @Test void constructorWhenPathIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigTreeConfigDataResource((Path) null)) - .withMessage("Path must not be null"); + .withMessage("Path must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java index c8f90e81d9..748d1e65ce 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,7 +69,7 @@ class DelegatingApplicationContextInitializerTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "context.initializer.classes=missing.madeup.class"); assertThatExceptionOfType(ApplicationContextException.class) - .isThrownBy(() -> this.initializer.initialize(context)); + .isThrownBy(() -> this.initializer.initialize(context)); } @Test @@ -86,7 +86,7 @@ class DelegatingApplicationContextInitializerTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "context.initializer.classes=" + NotSuitableInit.class.getName()); assertThatIllegalArgumentException().isThrownBy(() -> this.initializer.initialize(context)) - .withMessageContaining("generic parameter"); + .withMessageContaining("generic parameter"); } @Order(Ordered.HIGHEST_PRECEDENCE) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java index 61cf3b45e0..284c9377d4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,7 +81,7 @@ class DelegatingApplicationListenerTests { @Override public void onApplicationEvent(ContextRefreshedEvent event) { ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) event - .getApplicationContext(); + .getApplicationContext(); applicationContext.getBeanFactory().registerSingleton("a", "a"); } @@ -93,7 +93,7 @@ class DelegatingApplicationListenerTests { @Override public void onApplicationEvent(ContextRefreshedEvent event) { ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) event - .getApplicationContext(); + .getApplicationContext(); assertThat(applicationContext.getBeanFactory().getSingleton("a")).isEqualTo("a"); applicationContext.getBeanFactory().registerSingleton("b", "b"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/InactiveConfigDataAccessExceptionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/InactiveConfigDataAccessExceptionTests.java index 8332a7b4f8..6a7e9dcfec 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/InactiveConfigDataAccessExceptionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/InactiveConfigDataAccessExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -123,10 +123,10 @@ class InactiveConfigDataAccessExceptionTests { given(contributor.getPropertySource()).willReturn((PropertySource) this.propertySource); given(contributor.getResource()).willReturn(this.resource); assertThatExceptionOfType(InactiveConfigDataAccessException.class) - .isThrownBy(() -> InactiveConfigDataAccessException.throwIfPropertyFound(contributor, - ConfigurationPropertyName.of("spring"))) - .withMessage("Inactive property source 'mockProperties' imported from location 'test' " - + "cannot contain property 'spring' [origin: \"spring\" from property source \"mockProperties\"]"); + .isThrownBy(() -> InactiveConfigDataAccessException.throwIfPropertyFound(contributor, + ConfigurationPropertyName.of("spring"))) + .withMessage("Inactive property source 'mockProperties' imported from location 'test' " + + "cannot contain property 'spring' [origin: \"spring\" from property source \"mockProperties\"]"); } private static class TestConfigDataResource extends ConfigDataResource { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/InvalidConfigDataPropertyExceptionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/InvalidConfigDataPropertyExceptionTests.java index 8612104b02..bf3d9d3b96 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/InvalidConfigDataPropertyExceptionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/InvalidConfigDataPropertyExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,20 +54,20 @@ class InvalidConfigDataPropertyExceptionTests { @Test void createHasCorrectMessage() { assertThat(new InvalidConfigDataPropertyException(this.property, false, this.replacement, this.resource)) - .hasMessage( - "Property 'invalid' imported from location 'test' is invalid and should be replaced with 'replacement' [origin: origin]"); + .hasMessage( + "Property 'invalid' imported from location 'test' is invalid and should be replaced with 'replacement' [origin: origin]"); } @Test void createWhenNoLocationHasCorrectMessage() { assertThat(new InvalidConfigDataPropertyException(this.property, false, this.replacement, null)) - .hasMessage("Property 'invalid' is invalid and should be replaced with 'replacement' [origin: origin]"); + .hasMessage("Property 'invalid' is invalid and should be replaced with 'replacement' [origin: origin]"); } @Test void createWhenNoReplacementHasCorrectMessage() { assertThat(new InvalidConfigDataPropertyException(this.property, false, null, this.resource)) - .hasMessage("Property 'invalid' imported from location 'test' is invalid [origin: origin]"); + .hasMessage("Property 'invalid' imported from location 'test' is invalid [origin: origin]"); } @Test @@ -80,8 +80,8 @@ class InvalidConfigDataPropertyExceptionTests { @Test void createWhenProfileSpecificHasCorrectMessage() { ConfigurationProperty property = new ConfigurationProperty(this.invalid, "bad", null); - assertThat(new InvalidConfigDataPropertyException(property, true, null, this.resource)).hasMessage( - "Property 'invalid' imported from location 'test' is invalid in a profile specific resource"); + assertThat(new InvalidConfigDataPropertyException(property, true, null, this.resource)) + .hasMessage("Property 'invalid' imported from location 'test' is invalid in a profile specific resource"); } @Test @@ -112,9 +112,9 @@ class InvalidConfigDataPropertyExceptionTests { propertySource.setProperty("spring.profiles", "a"); ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor.ofExisting(propertySource); assertThatExceptionOfType(InvalidConfigDataPropertyException.class) - .isThrownBy(() -> InvalidConfigDataPropertyException.throwOrWarn(this.logger, contributor)) - .withMessageStartingWith("Property 'spring.profiles' is invalid and should be replaced with " - + "'spring.config.activate.on-profile'"); + .isThrownBy(() -> InvalidConfigDataPropertyException.throwOrWarn(this.logger, contributor)) + .withMessageStartingWith("Property 'spring.profiles' is invalid and should be replaced with " + + "'spring.config.activate.on-profile'"); } @Test @@ -129,14 +129,14 @@ class InvalidConfigDataPropertyExceptionTests { ConfigDataEnvironmentContributor contributor = createInvalidProfileSpecificPropertyContributor( "spring.profiles.active", ConfigData.Option.IGNORE_PROFILES); assertThatNoException() - .isThrownBy(() -> InvalidConfigDataPropertyException.throwOrWarn(this.logger, contributor)); + .isThrownBy(() -> InvalidConfigDataPropertyException.throwOrWarn(this.logger, contributor)); } private void throwOrWarnWhenWhenHasInvalidProfileSpecificPropertyThrowsException(String name) { ConfigDataEnvironmentContributor contributor = createInvalidProfileSpecificPropertyContributor(name); assertThatExceptionOfType(InvalidConfigDataPropertyException.class) - .isThrownBy(() -> InvalidConfigDataPropertyException.throwOrWarn(this.logger, contributor)) - .withMessageStartingWith("Property '" + name + "' is invalid in a profile specific resource"); + .isThrownBy(() -> InvalidConfigDataPropertyException.throwOrWarn(this.logger, contributor)) + .withMessageStartingWith("Property '" + name + "' is invalid in a profile specific resource"); } private ConfigDataEnvironmentContributor createInvalidProfileSpecificPropertyContributor(String name, @@ -152,7 +152,7 @@ class InvalidConfigDataPropertyExceptionTests { @Test void throwOrWarnWhenHasNoInvalidPropertyDoesNothing() { ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor - .ofExisting(new MockPropertySource()); + .ofExisting(new MockPropertySource()); InvalidConfigDataPropertyException.throwOrWarn(this.logger, contributor); } @@ -162,8 +162,9 @@ class InvalidConfigDataPropertyExceptionTests { propertySource.setProperty("spring.profiles", "a"); ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor.ofExisting(propertySource); InvalidConfigDataPropertyException.throwOrWarn(this.logger, contributor); - then(this.logger).should().warn("Property 'spring.profiles' is invalid and should be replaced with " - + "'spring.config.activate.on-profile' [origin: \"spring.profiles\" from property source \"mockProperties\"]"); + then(this.logger).should() + .warn("Property 'spring.profiles' is invalid and should be replaced with " + + "'spring.config.activate.on-profile' [origin: \"spring.profiles\" from property source \"mockProperties\"]"); } @Test @@ -172,8 +173,9 @@ class InvalidConfigDataPropertyExceptionTests { propertySource.setProperty("spring.profiles[0]", "a"); ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor.ofExisting(propertySource); InvalidConfigDataPropertyException.throwOrWarn(this.logger, contributor); - then(this.logger).should().warn("Property 'spring.profiles[0]' is invalid and should be replaced with " - + "'spring.config.activate.on-profile' [origin: \"spring.profiles[0]\" from property source \"mockProperties\"]"); + then(this.logger).should() + .warn("Property 'spring.profiles[0]' is invalid and should be replaced with " + + "'spring.config.activate.on-profile' [origin: \"spring.profiles[0]\" from property source \"mockProperties\"]"); } private static class TestConfigDataResource extends ConfigDataResource { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/LocationResourceLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/LocationResourceLoaderTests.java index f93c734e6a..bf2a0222fd 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/LocationResourceLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/LocationResourceLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,7 +55,7 @@ class LocationResourceLoaderTests { @Test void getResourceWhenPatternThrowsException() { assertThatIllegalStateException().isThrownBy(() -> this.loader.getResource("spring/boot/*")) - .withMessage("Location 'spring/boot/*' must not be a pattern"); + .withMessage("Location 'spring/boot/*' must not be a pattern"); } @Test @@ -85,27 +85,27 @@ class LocationResourceLoaderTests { @Test void getResourcesWhenNotPatternThrowsException() { assertThatIllegalStateException().isThrownBy(() -> this.loader.getResources("spring/boot", ResourceType.FILE)) - .withMessage("Location 'spring/boot' must be a pattern"); + .withMessage("Location 'spring/boot' must be a pattern"); } @Test void getResourcesWhenLocationStartsWithClasspathWildcardThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> this.loader.getResources("classpath*:spring/boot/*/", ResourceType.FILE)) - .withMessage("Location 'classpath*:spring/boot/*/' cannot use classpath wildcards"); + .isThrownBy(() -> this.loader.getResources("classpath*:spring/boot/*/", ResourceType.FILE)) + .withMessage("Location 'classpath*:spring/boot/*/' cannot use classpath wildcards"); } @Test void getResourcesWhenLocationContainsMultipleWildcardsThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> this.loader.getResources("spring/*/boot/*/", ResourceType.FILE)) - .withMessage("Location 'spring/*/boot/*/' cannot contain multiple wildcards"); + .isThrownBy(() -> this.loader.getResources("spring/*/boot/*/", ResourceType.FILE)) + .withMessage("Location 'spring/*/boot/*/' cannot contain multiple wildcards"); } @Test void getResourcesWhenPatternDoesNotEndWithAsteriskSlashThrowsException() { assertThatIllegalStateException().isThrownBy(() -> this.loader.getResources("spring/boot/*", ResourceType.FILE)) - .withMessage("Location 'spring/boot/*' must end with '*/'"); + .withMessage("Location 'spring/boot/*' must end with '*/'"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataLoaderTests.java index 3287efaf3e..e706866c9f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,12 +52,12 @@ class StandardConfigDataLoaderTests { PropertySource source1 = configData.getPropertySources().get(0); PropertySource source2 = configData.getPropertySources().get(1); assertThat(source1.getName()) - .isEqualTo("Config resource 'class path resource [configdata/yaml/application.yml]' " - + "via location 'classpath:configdata/yaml/application.yml' (document #0)"); + .isEqualTo("Config resource 'class path resource [configdata/yaml/application.yml]' " + + "via location 'classpath:configdata/yaml/application.yml' (document #0)"); assertThat(source1.getProperty("foo")).isEqualTo("bar"); assertThat(source2.getName()) - .isEqualTo("Config resource 'class path resource [configdata/yaml/application.yml]' " - + "via location 'classpath:configdata/yaml/application.yml' (document #1)"); + .isEqualTo("Config resource 'class path resource [configdata/yaml/application.yml]' " + + "via location 'classpath:configdata/yaml/application.yml' (document #1)"); assertThat(source2.getProperty("hello")).isEqualTo("world"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataLocationResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataLocationResolverTests.java index 37e5679ac4..ef5c877799 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataLocationResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataLocationResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -75,56 +75,59 @@ class StandardConfigDataLocationResolverTests { List locations = this.resolver.resolve(this.context, location); assertThat(locations.size()).isEqualTo(1); assertThat(locations).extracting(Object::toString) - .containsExactly("class path resource [configdata/properties/application.properties]"); + .containsExactly("class path resource [configdata/properties/application.properties]"); } @Test void resolveWhenLocationIsFileResolvesFile() { ConfigDataLocation location = ConfigDataLocation - .of("file:src/test/resources/configdata/properties/application.properties"); + .of("file:src/test/resources/configdata/properties/application.properties"); List locations = this.resolver.resolve(this.context, location); assertThat(locations.size()).isEqualTo(1); - assertThat(locations).extracting(Object::toString).containsExactly( - filePath("src", "test", "resources", "configdata", "properties", "application.properties")); + assertThat(locations).extracting(Object::toString) + .containsExactly( + filePath("src", "test", "resources", "configdata", "properties", "application.properties")); } @Test void resolveWhenLocationIsFileAndNoMatchingLoaderThrowsException() { ConfigDataLocation location = ConfigDataLocation - .of("file:src/test/resources/configdata/properties/application.unknown"); + .of("file:src/test/resources/configdata/properties/application.unknown"); assertThatIllegalStateException().isThrownBy(() -> this.resolver.resolve(this.context, location)) - .withMessageStartingWith("Unable to load config data from") - .satisfies((ex) -> assertThat(ex.getCause()).hasMessageStartingWith("File extension is not known")); + .withMessageStartingWith("Unable to load config data from") + .satisfies((ex) -> assertThat(ex.getCause()).hasMessageStartingWith("File extension is not known")); } @Test void resolveWhenLocationWildcardIsSpecifiedForClasspathLocationThrowsException() { ConfigDataLocation location = ConfigDataLocation.of("classpath*:application.properties"); assertThatIllegalStateException().isThrownBy(() -> this.resolver.resolve(this.context, location)) - .withMessageContaining("Location 'classpath*:application.properties' cannot use classpath wildcards"); + .withMessageContaining("Location 'classpath*:application.properties' cannot use classpath wildcards"); } @Test void resolveWhenLocationWildcardIsNotBeforeLastSlashThrowsException() { ConfigDataLocation location = ConfigDataLocation.of("file:src/test/resources/*/config/"); assertThatIllegalStateException().isThrownBy(() -> this.resolver.resolve(this.context, location)) - .withMessageStartingWith("Location '").withMessageEndingWith("' must end with '*/'"); + .withMessageStartingWith("Location '") + .withMessageEndingWith("' must end with '*/'"); } @Test void createWhenConfigNameHasWildcardThrowsException() { this.environment.setProperty("spring.config.name", "*/application"); assertThatIllegalStateException() - .isThrownBy( - () -> new StandardConfigDataLocationResolver(null, this.environmentBinder, this.resourceLoader)) - .withMessageStartingWith("Config name '").withMessageEndingWith("' cannot contain '*'"); + .isThrownBy(() -> new StandardConfigDataLocationResolver(null, this.environmentBinder, this.resourceLoader)) + .withMessageStartingWith("Config name '") + .withMessageEndingWith("' cannot contain '*'"); } @Test void resolveWhenLocationHasMultipleWildcardsThrowsException() { ConfigDataLocation location = ConfigDataLocation.of("file:src/test/resources/config/**/"); assertThatIllegalStateException().isThrownBy(() -> this.resolver.resolve(this.context, location)) - .withMessageStartingWith("Location '").withMessageEndingWith("' cannot contain multiple wildcards"); + .withMessageStartingWith("Location '") + .withMessageEndingWith("' cannot contain multiple wildcards"); } @Test @@ -135,9 +138,9 @@ class StandardConfigDataLocationResolverTests { List locations = this.resolver.resolve(this.context, location); assertThat(locations.size()).isEqualTo(3); assertThat(locations).extracting(Object::toString) - .contains(filePath("src", "test", "resources", "config", "1-first", "testproperties.properties")) - .contains(filePath("src", "test", "resources", "config", "2-second", "testproperties.properties")) - .doesNotContain(filePath("src", "test", "resources", "config", "3-third", "testproperties.properties")); + .contains(filePath("src", "test", "resources", "config", "1-first", "testproperties.properties")) + .contains(filePath("src", "test", "resources", "config", "2-second", "testproperties.properties")) + .doesNotContain(filePath("src", "test", "resources", "config", "3-third", "testproperties.properties")); } @Test @@ -146,10 +149,10 @@ class StandardConfigDataLocationResolverTests { this.environment.setProperty("spring.config.name", "testproperties"); this.resolver = new StandardConfigDataLocationResolver(null, this.environmentBinder, this.resourceLoader); List locations = this.resolver.resolve(this.context, location); - assertThat(locations).extracting(Object::toString).containsExactly( - filePath("src", "test", "resources", "config", "0-empty", "testproperties.properties"), - filePath("src", "test", "resources", "config", "1-first", "testproperties.properties"), - filePath("src", "test", "resources", "config", "2-second", "testproperties.properties")); + assertThat(locations).extracting(Object::toString) + .containsExactly(filePath("src", "test", "resources", "config", "0-empty", "testproperties.properties"), + filePath("src", "test", "resources", "config", "1-first", "testproperties.properties"), + filePath("src", "test", "resources", "config", "2-second", "testproperties.properties")); } @Test @@ -161,14 +164,14 @@ class StandardConfigDataLocationResolverTests { @Test void resolveWhenLocationIsWildcardFilesLoadsAllFilesThatMatch() { ConfigDataLocation location = ConfigDataLocation - .of("file:src/test/resources/config/*/testproperties.properties"); + .of("file:src/test/resources/config/*/testproperties.properties"); List locations = this.resolver.resolve(this.context, location); assertThat(locations.size()).isEqualTo(3); assertThat(locations).extracting(Object::toString) - .contains(filePath("src", "test", "resources", "config", "1-first", "testproperties.properties")) - .contains(filePath("src", "test", "resources", "config", "2-second", "testproperties.properties")) - .doesNotContain(filePath("src", "test", "resources", "config", "nested", "3-third", - "testproperties.properties")); + .contains(filePath("src", "test", "resources", "config", "1-first", "testproperties.properties")) + .contains(filePath("src", "test", "resources", "config", "2-second", "testproperties.properties")) + .doesNotContain( + filePath("src", "test", "resources", "config", "nested", "3-third", "testproperties.properties")); } @Test @@ -187,7 +190,7 @@ class StandardConfigDataLocationResolverTests { List locations = this.resolver.resolve(this.context, location); assertThat(locations.size()).isEqualTo(1); assertThat(locations).extracting(Object::toString) - .contains("class path resource [configdata/properties/other.properties]"); + .contains("class path resource [configdata/properties/other.properties]"); } @Test @@ -205,7 +208,7 @@ class StandardConfigDataLocationResolverTests { List locations = this.resolver.resolve(this.context, location); assertThat(locations.size()).isEqualTo(1); assertThat(locations).extracting(Object::toString) - .contains("class path resource [config/nested/3-third/testproperties.properties]"); + .contains("class path resource [config/nested/3-third/testproperties.properties]"); } @Test @@ -218,8 +221,8 @@ class StandardConfigDataLocationResolverTests { StandardConfigDataResource parent = new StandardConfigDataResource(parentReference, parentResource); given(this.context.getParent()).willReturn(parent); assertThatIllegalStateException().isThrownBy(() -> this.resolver.resolve(this.context, location)) - .withMessageStartingWith("Unable to load config data from 'application.other'") - .satisfies((ex) -> assertThat(ex.getCause()).hasMessageStartingWith("File extension is not known")); + .withMessageStartingWith("Unable to load config data from 'application.other'") + .satisfies((ex) -> assertThat(ex.getCause()).hasMessageStartingWith("File extension is not known")); } @Test @@ -243,7 +246,7 @@ class StandardConfigDataLocationResolverTests { profiles); assertThat(locations.size()).isEqualTo(1); assertThat(locations).extracting(Object::toString) - .containsExactly("class path resource [configdata/properties/application-dev.properties]"); + .containsExactly("class path resource [configdata/properties/application-dev.properties]"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataResourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataResourceTests.java index 8c1734ee2a..56bc44058c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataResourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataResourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,13 +40,13 @@ class StandardConfigDataResourceTests { @Test void createWhenReferenceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new StandardConfigDataResource(null, this.resource)) - .withMessage("Reference must not be null"); + .withMessage("Reference must not be null"); } @Test void createWhenResourceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new StandardConfigDataResource(this.reference, null)) - .withMessage("Resource must not be null"); + .withMessage("Resource must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/TestConfigDataBootstrap.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/TestConfigDataBootstrap.java index 4820905fd7..1f3a673d28 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/TestConfigDataBootstrap.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/TestConfigDataBootstrap.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,8 @@ class TestConfigDataBootstrap { @Override public List resolve(ConfigDataLocationResolverContext context, ConfigDataLocation location) { - context.getBootstrapContext().registerIfAbsent(ResolverHelper.class, - InstanceSupplier.from(() -> new ResolverHelper(location))); + context.getBootstrapContext() + .registerIfAbsent(ResolverHelper.class, InstanceSupplier.from(() -> new ResolverHelper(location))); ResolverHelper helper = context.getBootstrapContext().get(ResolverHelper.class); return Collections.singletonList(new Resource(helper)); } @@ -59,8 +59,9 @@ class TestConfigDataBootstrap { @Override public ConfigData load(ConfigDataLoaderContext context, Resource location) throws IOException { - context.getBootstrapContext().registerIfAbsent(LoaderHelper.class, - (bootstrapContext) -> new LoaderHelper(location, () -> bootstrapContext.get(Binder.class))); + context.getBootstrapContext() + .registerIfAbsent(LoaderHelper.class, + (bootstrapContext) -> new LoaderHelper(location, () -> bootstrapContext.get(Binder.class))); LoaderHelper helper = context.getBootstrapContext().get(LoaderHelper.class); context.getBootstrapContext().addCloseListener(helper); return new ConfigData( diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/UseLegacyConfigProcessingExceptionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/UseLegacyConfigProcessingExceptionTests.java index eb892dd8e3..8d5af3af05 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/UseLegacyConfigProcessingExceptionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/UseLegacyConfigProcessingExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,9 +53,9 @@ class UseLegacyConfigProcessingExceptionTests { source.put("spring.config.use-legacy-processing", "true"); Binder binder = new Binder(source); assertThatExceptionOfType(UseLegacyConfigProcessingException.class) - .isThrownBy(() -> UseLegacyConfigProcessingException.throwIfRequested(binder)) - .satisfies((ex) -> assertThat(ex.getConfigurationProperty().getName()) - .hasToString("spring.config.use-legacy-processing")); + .isThrownBy(() -> UseLegacyConfigProcessingException.throwIfRequested(binder)) + .satisfies((ex) -> assertThat(ex.getConfigurationProperty().getName()) + .hasToString("spring.config.use-legacy-processing")); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java index dbc8f46c7c..cf0cf4c862 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,8 @@ class LoggingApplicationListenerIntegrationTests { @Test void loggingSystemRegisteredInTheContext() { try (ConfigurableApplicationContext context = new SpringApplicationBuilder(SampleService.class) - .web(WebApplicationType.NONE).run()) { + .web(WebApplicationType.NONE) + .run()) { SampleService service = context.getBean(SampleService.class); assertThat(service.loggingSystem).isNotNull(); } @@ -60,7 +61,9 @@ class LoggingApplicationListenerIntegrationTests { void logFileRegisteredInTheContextWhenApplicable(@TempDir File tempDir) { String logFile = new File(tempDir, "test.log").getAbsolutePath(); try (ConfigurableApplicationContext context = new SpringApplicationBuilder(SampleService.class) - .web(WebApplicationType.NONE).properties("logging.file.name=" + logFile).run()) { + .web(WebApplicationType.NONE) + .properties("logging.file.name=" + logFile) + .run()) { SampleService service = context.getBean(SampleService.class); assertThat(service.logFile).isNotNull(); assertThat(service.logFile.toString()).isEqualTo(logFile); @@ -72,17 +75,20 @@ class LoggingApplicationListenerIntegrationTests { @Test void loggingPerformedDuringChildApplicationStartIsNotLost(CapturedOutput output) { - new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).child(Config.class) - .web(WebApplicationType.NONE).listeners(new ApplicationListener() { + new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE) + .child(Config.class) + .web(WebApplicationType.NONE) + .listeners(new ApplicationListener() { - private final Logger logger = LoggerFactory.getLogger(getClass()); + private final Logger logger = LoggerFactory.getLogger(getClass()); - @Override - public void onApplicationEvent(ApplicationStartingEvent event) { - this.logger.info("Child application starting"); - } + @Override + public void onApplicationEvent(ApplicationStartingEvent event) { + this.logger.info("Child application starting"); + } - }).run(); + }) + .run(); assertThat(output).contains("Child application starting"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java index 9ac81baa25..629a07d344 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -177,11 +177,11 @@ class LoggingApplicationListenerTests { @Test void overrideConfigDoesNotExist() { addPropertiesToEnvironment(this.context, "logging.config=doesnotexist.xml"); - assertThatIllegalStateException().isThrownBy( - () -> this.listener.initialize(this.context.getEnvironment(), this.context.getClassLoader())); + assertThatIllegalStateException() + .isThrownBy(() -> this.listener.initialize(this.context.getEnvironment(), this.context.getClassLoader())); assertThat(this.output) - .contains("Logging system failed to initialize using configuration from 'doesnotexist.xml'") - .doesNotContain("JoranException"); + .contains("Logging system failed to initialize using configuration from 'doesnotexist.xml'") + .doesNotContain("JoranException"); } @Test @@ -343,8 +343,8 @@ class LoggingApplicationListenerTests { void parseLevelsFails() { this.logger.setLevel(Level.INFO); addPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=GARBAGE"); - assertThatExceptionOfType(BindException.class).isThrownBy( - () -> this.listener.initialize(this.context.getEnvironment(), this.context.getClassLoader())); + assertThatExceptionOfType(BindException.class) + .isThrownBy(() -> this.listener.initialize(this.context.getEnvironment(), this.context.getClassLoader())); } @Test @@ -485,7 +485,7 @@ class LoggingApplicationListenerTests { addPropertiesToEnvironment(this.context, "logging.pattern.console=console ${doesnotexist}"); this.listener.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)) - .isEqualTo("console ${doesnotexist}"); + .isEqualTo("console ${doesnotexist}"); } @Test @@ -493,7 +493,7 @@ class LoggingApplicationListenerTests { addPropertiesToEnvironment(this.context, "logging.pattern.console=console ${pid}"); this.listener.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)) - .isEqualTo(this.context.getEnvironment().getProperty("logging.pattern.console")); + .isEqualTo(this.context.getEnvironment().getProperty("logging.pattern.console")); } @Test @@ -501,7 +501,7 @@ class LoggingApplicationListenerTests { addPropertiesToEnvironment(this.context, "logging.file.name=" + this.tempDir + "${PID}.log"); this.listener.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(System.getProperty(LoggingSystemProperties.LOG_FILE)) - .isEqualTo(this.tempDir + new ApplicationPid().toString() + ".log"); + .isEqualTo(this.tempDir + new ApplicationPid().toString() + ".log"); } @Test @@ -521,8 +521,11 @@ class LoggingApplicationListenerTests { System.setProperty(LoggingSystem.SYSTEM_PROPERTY, TestCleanupLoggingSystem.class.getName()); this.springApplication.setWebApplicationType(WebApplicationType.NONE); ConfigurableApplicationContext context = this.springApplication.run(); - ApplicationListener listener = this.springApplication.getListeners().stream() - .filter(LoggingApplicationListener.class::isInstance).findFirst().get(); + ApplicationListener listener = this.springApplication.getListeners() + .stream() + .filter(LoggingApplicationListener.class::isInstance) + .findFirst() + .get(); TestCleanupLoggingSystem loggingSystem = (TestCleanupLoggingSystem) ReflectionTestUtils.getField(listener, "loggingSystem"); assertThat(loggingSystem.cleanedUp).isFalse(); @@ -543,7 +546,7 @@ class LoggingApplicationListenerTests { void lowPriorityPropertySourceShouldNotOverrideRootLoggerConfig() { MutablePropertySources propertySources = this.context.getEnvironment().getPropertySources(); propertySources - .addFirst(new MapPropertySource("test1", Collections.singletonMap("logging.level.ROOT", "DEBUG"))); + .addFirst(new MapPropertySource("test1", Collections.singletonMap("logging.level.ROOT", "DEBUG"))); propertySources.addLast(new MapPropertySource("test2", Collections.singletonMap("logging.level.root", "WARN"))); this.listener.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/metrics/buffering/BufferingApplicationStartupTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/metrics/buffering/BufferingApplicationStartupTests.java index e544f2389a..24b064b4f9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/metrics/buffering/BufferingApplicationStartupTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/metrics/buffering/BufferingApplicationStartupTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,7 +87,7 @@ class BufferingApplicationStartupTests { BufferingApplicationStartup applicationStartup = new BufferingApplicationStartup(2); applicationStartup.start("first").end(); assertThatThrownBy(applicationStartup::startRecording).isInstanceOf(IllegalStateException.class) - .hasMessage("Cannot restart recording once steps have been buffered."); + .hasMessage("Cannot restart recording once steps have been buffered."); } @Test @@ -96,7 +96,7 @@ class BufferingApplicationStartupTests { StartupStep step = applicationStartup.start("first"); step.end(); assertThatThrownBy(() -> step.tag("name", "value")).isInstanceOf(IllegalStateException.class) - .hasMessage("StartupStep has already ended."); + .hasMessage("StartupStep has already ended."); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrarTests.java index 72a44356be..6354f07b01 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,8 +65,8 @@ class ConfigurationPropertiesBeanRegistrarTests { @Test void registerWhenNoAnnotationThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> this.registrar.register(NoAnnotationConfigurationProperties.class)) - .withMessageContaining("No ConfigurationProperties annotation found"); + .isThrownBy(() -> this.registrar.register(NoAnnotationConfigurationProperties.class)) + .withMessageContaining("No ConfigurationProperties annotation found"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanTests.java index 407f794c3f..308ce7341c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -218,7 +218,7 @@ class ConfigurationPropertiesBeanTests { @Test void forValueObjectWithConstructorBindingAnnotatedClassReturnsBean() { ConfigurationPropertiesBean propertiesBean = ConfigurationPropertiesBean - .forValueObject(ConstructorBindingOnConstructor.class, "valueObjectBean"); + .forValueObject(ConstructorBindingOnConstructor.class, "valueObjectBean"); assertThat(propertiesBean.getName()).isEqualTo("valueObjectBean"); assertThat(propertiesBean.getInstance()).isNull(); assertThat(propertiesBean.getType()).isEqualTo(ConstructorBindingOnConstructor.class); @@ -228,21 +228,25 @@ class ConfigurationPropertiesBeanTests { assertThat(target.getType()).isEqualTo(ResolvableType.forClass(ConstructorBindingOnConstructor.class)); assertThat(target.getValue()).isNull(); assertThat(ConfigurationPropertiesBindConstructorProvider.INSTANCE - .getBindConstructor(ConstructorBindingOnConstructor.class, false)).isNotNull(); + .getBindConstructor(ConstructorBindingOnConstructor.class, false)).isNotNull(); } @Test @EnabledForJreRange(min = JRE.JAVA_16) void forValueObjectWithConstructorBindingAnnotatedRecordReturnsBean() { Class constructorBindingRecord = new ByteBuddy(ClassFileVersion.JAVA_V16).makeRecord() - .name("org.springframework.boot.context.properties.RecordProperties") - .annotateType(AnnotationDescription.Builder.ofType(ConfigurationProperties.class) - .define("prefix", "explicit").build()) - .annotateType(AnnotationDescription.Builder.ofType(ConstructorBinding.class).build()) - .defineRecordComponent("someString", String.class).defineRecordComponent("someInteger", Integer.class) - .make().load(getClass().getClassLoader()).getLoaded(); + .name("org.springframework.boot.context.properties.RecordProperties") + .annotateType(AnnotationDescription.Builder.ofType(ConfigurationProperties.class) + .define("prefix", "explicit") + .build()) + .annotateType(AnnotationDescription.Builder.ofType(ConstructorBinding.class).build()) + .defineRecordComponent("someString", String.class) + .defineRecordComponent("someInteger", Integer.class) + .make() + .load(getClass().getClassLoader()) + .getLoaded(); ConfigurationPropertiesBean propertiesBean = ConfigurationPropertiesBean - .forValueObject(constructorBindingRecord, "constructorBindingRecord"); + .forValueObject(constructorBindingRecord, "constructorBindingRecord"); assertThat(propertiesBean.getName()).isEqualTo("constructorBindingRecord"); assertThat(propertiesBean.getInstance()).isNull(); assertThat(propertiesBean.getType()).isEqualTo(constructorBindingRecord); @@ -252,7 +256,7 @@ class ConfigurationPropertiesBeanTests { assertThat(target.getType()).isEqualTo(ResolvableType.forClass(constructorBindingRecord)); assertThat(target.getValue()).isNull(); Constructor bindConstructor = ConfigurationPropertiesBindConstructorProvider.INSTANCE - .getBindConstructor(constructorBindingRecord, false); + .getBindConstructor(constructorBindingRecord, false); assertThat(bindConstructor).isNotNull(); assertThat(bindConstructor.getParameterTypes()).containsExactly(String.class, Integer.class); } @@ -261,13 +265,17 @@ class ConfigurationPropertiesBeanTests { @EnabledForJreRange(min = JRE.JAVA_16) void forValueObjectWithUnannotatedRecordReturnsBean() { Class implicitConstructorBinding = new ByteBuddy(ClassFileVersion.JAVA_V16).makeRecord() - .name("org.springframework.boot.context.properties.ImplicitConstructorBinding") - .annotateType(AnnotationDescription.Builder.ofType(ConfigurationProperties.class) - .define("prefix", "implicit").build()) - .defineRecordComponent("someString", String.class).defineRecordComponent("someInteger", Integer.class) - .make().load(getClass().getClassLoader()).getLoaded(); + .name("org.springframework.boot.context.properties.ImplicitConstructorBinding") + .annotateType(AnnotationDescription.Builder.ofType(ConfigurationProperties.class) + .define("prefix", "implicit") + .build()) + .defineRecordComponent("someString", String.class) + .defineRecordComponent("someInteger", Integer.class) + .make() + .load(getClass().getClassLoader()) + .getLoaded(); ConfigurationPropertiesBean propertiesBean = ConfigurationPropertiesBean - .forValueObject(implicitConstructorBinding, "implicitBindingRecord"); + .forValueObject(implicitConstructorBinding, "implicitBindingRecord"); assertThat(propertiesBean.getName()).isEqualTo("implicitBindingRecord"); assertThat(propertiesBean.getInstance()).isNull(); assertThat(propertiesBean.getType()).isEqualTo(implicitConstructorBinding); @@ -277,7 +285,7 @@ class ConfigurationPropertiesBeanTests { assertThat(target.getType()).isEqualTo(ResolvableType.forClass(implicitConstructorBinding)); assertThat(target.getValue()).isNull(); Constructor bindConstructor = ConfigurationPropertiesBindConstructorProvider.INSTANCE - .getBindConstructor(implicitConstructorBinding, false); + .getBindConstructor(implicitConstructorBinding, false); assertThat(bindConstructor).isNotNull(); assertThat(bindConstructor.getParameterTypes()).containsExactly(String.class, Integer.class); } @@ -285,12 +293,11 @@ class ConfigurationPropertiesBeanTests { @Test void forValueObjectWhenJavaBeanBindTypeThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> ConfigurationPropertiesBean.forValueObject(AnnotatedBean.class, "annotatedBean")) - .withMessage("Bean 'annotatedBean' is not a @ConfigurationProperties value object"); + .isThrownBy(() -> ConfigurationPropertiesBean.forValueObject(AnnotatedBean.class, "annotatedBean")) + .withMessage("Bean 'annotatedBean' is not a @ConfigurationProperties value object"); assertThatIllegalStateException() - .isThrownBy( - () -> ConfigurationPropertiesBean.forValueObject(NonAnnotatedBean.class, "nonAnnotatedBean")) - .withMessage("Bean 'nonAnnotatedBean' is not a @ConfigurationProperties value object"); + .isThrownBy(() -> ConfigurationPropertiesBean.forValueObject(NonAnnotatedBean.class, "nonAnnotatedBean")) + .withMessage("Bean 'nonAnnotatedBean' is not a @ConfigurationProperties value object"); } @@ -315,9 +322,9 @@ class ConfigurationPropertiesBeanTests { @Test void bindTypeForTypeWhenConstructorBindingOnMultipleConstructorsThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> BindMethod.forType(ConstructorBindingOnMultipleConstructors.class)) - .withMessage(ConstructorBindingOnMultipleConstructors.class.getName() - + " has more than one @ConstructorBinding constructor"); + .isThrownBy(() -> BindMethod.forType(ConstructorBindingOnMultipleConstructors.class)) + .withMessage(ConstructorBindingOnMultipleConstructors.class.getName() + + " has more than one @ConstructorBinding constructor"); } private void get(Class configuration, String beanName, ThrowingConsumer consumer) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrarTests.java index 9cd33e4e45..a6be50d146 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,7 +81,7 @@ class ConfigurationPropertiesScanRegistrarTests { beanFactory); assertThat(beanFactory.containsBeanDefinition( "foo-org.springframework.boot.context.properties.scan.valid.ConfigurationPropertiesScanConfiguration$FooProperties")) - .isFalse(); + .isFalse(); BeanDefinition aDefinition = beanFactory.getBeanDefinition( "a-org.springframework.boot.context.properties.scan.valid.a.AScanConfiguration$AProperties"); BeanDefinition bFirstDefinition = beanFactory.getBeanDefinition( diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanTests.java index 5609874e90..012e00fac0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,7 +70,7 @@ class ConfigurationPropertiesScanTests { load(TestConfiguration.class); assertThat(this.context.containsBean( "profile-org.springframework.boot.context.properties.scan.valid.a.AScanConfiguration$MyProfileProperties")) - .isTrue(); + .isTrue(); } @Test @@ -78,7 +78,7 @@ class ConfigurationPropertiesScanTests { load(TestConfiguration.class); assertThat(this.context.containsBean( "profile-org.springframework.boot.context.properties.scan.valid.a.AScanConfiguration$MyProfileProperties")) - .isFalse(); + .isFalse(); } @Test @@ -90,7 +90,7 @@ class ConfigurationPropertiesScanTests { load(TestConfiguration.class); assertThat(this.context.containsBean( "resource-org.springframework.boot.context.properties.scan.valid.a.AScanConfiguration$MyResourceProperties")) - .isTrue(); + .isTrue(); } @Test @@ -98,7 +98,7 @@ class ConfigurationPropertiesScanTests { load(TestConfiguration.class); assertThat(this.context.containsBean( "resource-org.springframework.boot.context.properties.scan.valid.a.AScanConfiguration$MyResourceProperties")) - .isFalse(); + .isFalse(); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java index b23119dc0d..e68fa1a276 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -182,8 +182,8 @@ class ConfigurationPropertiesTests { void loadWhenHasIgnoreUnknownFieldsFalseAndUnknownFieldsShouldFail() { removeSystemProperties(); assertThatExceptionOfType(ConfigurationPropertiesBindException.class) - .isThrownBy(() -> load(IgnoreUnknownFieldsFalseConfiguration.class, "name=foo", "bar=baz")) - .withCauseInstanceOf(BindException.class); + .isThrownBy(() -> load(IgnoreUnknownFieldsFalseConfiguration.class, "name=foo", "bar=baz")) + .withCauseInstanceOf(BindException.class); } @Test @@ -191,7 +191,7 @@ class ConfigurationPropertiesTests { removeSystemProperties(); assertThatExceptionOfType(ConfigurationPropertiesBindException.class).isThrownBy( () -> load(IgnoreUnknownFieldsFalseIgnoreInvalidFieldsTrueConfiguration.class, "name=foo", "bar=baz")) - .withCauseInstanceOf(BindException.class); + .withCauseInstanceOf(BindException.class); } @Test @@ -244,7 +244,7 @@ class ConfigurationPropertiesTests { @Test void loadWhenBindingWithoutAndAnnotationShouldFail() { assertThatIllegalStateException().isThrownBy(() -> load(WithoutAndAnnotationConfiguration.class, "name:foo")) - .withMessageContaining("No ConfigurationProperties annotation found"); + .withMessageContaining("No ConfigurationProperties annotation found"); } @Test @@ -356,7 +356,7 @@ class ConfigurationPropertiesTests { void loadWithPropertyPlaceholderValueShouldBind() { load(WithPropertyPlaceholderValueConfiguration.class, "default.value=foo"); WithPropertyPlaceholderValueProperties bean = this.context - .getBean(WithPropertyPlaceholderValueProperties.class); + .getBean(WithPropertyPlaceholderValueProperties.class); assertThat(bean.getValue()).isEqualTo("foo"); } @@ -459,9 +459,10 @@ class ConfigurationPropertiesTests { @Test void loadWhenUsingSystemPropertiesShouldBindToMap() { - this.context.getEnvironment().getPropertySources().addLast( - new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, - Collections.singletonMap("TEST_MAP_FOO_BAR", "baz"))); + this.context.getEnvironment() + .getPropertySources() + .addLast(new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, + Collections.singletonMap("TEST_MAP_FOO_BAR", "baz"))); load(WithComplexMapProperties.class); WithComplexMapProperties bean = this.context.getBean(WithComplexMapProperties.class); assertThat(bean.getMap()).containsOnlyKeys("foo"); @@ -470,9 +471,10 @@ class ConfigurationPropertiesTests { @Test void loadWhenDotsInSystemEnvironmentPropertiesShouldBind() { - this.context.getEnvironment().getPropertySources().addLast( - new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, - Collections.singletonMap("com.example.bar", "baz"))); + this.context.getEnvironment() + .getPropertySources() + .addLast(new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, + Collections.singletonMap("com.example.bar", "baz"))); load(SimplePrefixedProperties.class); SimplePrefixedProperties bean = this.context.getBean(SimplePrefixedProperties.class); assertThat(bean.getBar()).isEqualTo("baz"); @@ -507,29 +509,29 @@ class ConfigurationPropertiesTests { @Test void loadWhenJsr303ConstraintDoesNotMatchShouldFail() { assertThatExceptionOfType(ConfigurationPropertiesBindException.class) - .isThrownBy(() -> load(ValidatedJsr303Configuration.class, "description=")) - .withCauseInstanceOf(BindException.class); + .isThrownBy(() -> load(ValidatedJsr303Configuration.class, "description=")) + .withCauseInstanceOf(BindException.class); } @Test void loadValidatedOnBeanMethodAndJsr303ConstraintDoesNotMatchShouldFail() { assertThatExceptionOfType(ConfigurationPropertiesBindException.class) - .isThrownBy(() -> load(ValidatedOnBeanJsr303Configuration.class, "description=")) - .withCauseInstanceOf(BindException.class); + .isThrownBy(() -> load(ValidatedOnBeanJsr303Configuration.class, "description=")) + .withCauseInstanceOf(BindException.class); } @Test void loadWhenJsr303ConstraintDoesNotMatchOnNestedThatIsNotDirectlyAnnotatedShouldFail() { assertThatExceptionOfType(ConfigurationPropertiesBindException.class) - .isThrownBy(() -> load(ValidatedNestedJsr303Properties.class, "properties.description=")) - .withCauseInstanceOf(BindException.class); + .isThrownBy(() -> load(ValidatedNestedJsr303Properties.class, "properties.description=")) + .withCauseInstanceOf(BindException.class); } @Test void loadWhenJsr303ConstraintDoesNotMatchOnNestedThatIsNotDirectlyAnnotatedButIsValidShouldFail() { assertThatExceptionOfType(ConfigurationPropertiesBindException.class) - .isThrownBy(() -> load(ValidatedValidNestedJsr303Properties.class)) - .withCauseInstanceOf(BindException.class); + .isThrownBy(() -> load(ValidatedValidNestedJsr303Properties.class)) + .withCauseInstanceOf(BindException.class); } @Test @@ -555,8 +557,8 @@ class ConfigurationPropertiesTests { @Test void loadWhenOverridingPropertiesWithPlaceholderResolutionInEnvironmentShouldBindWithOverride() { MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); - sources.addFirst( - new SystemEnvironmentPropertySource("system", Collections.singletonMap("COM_EXAMPLE_BAR", "10"))); + sources + .addFirst(new SystemEnvironmentPropertySource("system", Collections.singletonMap("COM_EXAMPLE_BAR", "10"))); Map source = new HashMap<>(); source.put("com.example.bar", 5); source.put("com.example.foo", "${com.example.bar}"); @@ -665,9 +667,8 @@ class ConfigurationPropertiesTests { @Test void loadWhenConfigurationConverterIsNotQualifiedShouldNotConvert() { assertThatExceptionOfType(BeanCreationException.class) - .isThrownBy( - () -> prepareConverterContext(NonQualifiedConverterConfiguration.class, PersonProperties.class)) - .withCauseInstanceOf(BindException.class); + .isThrownBy(() -> prepareConverterContext(NonQualifiedConverterConfiguration.class, PersonProperties.class)) + .withCauseInstanceOf(BindException.class); } @Test @@ -690,7 +691,7 @@ class ConfigurationPropertiesTests { void loadWhenGenericConfigurationConverterIsNotQualifiedShouldNotConvert() { assertThatExceptionOfType(BeanCreationException.class).isThrownBy( () -> prepareConverterContext(NonQualifiedGenericConverterConfiguration.class, PersonProperties.class)) - .withCauseInstanceOf(BindException.class); + .withCauseInstanceOf(BindException.class); } @Test @@ -708,17 +709,17 @@ class ConfigurationPropertiesTests { @Test void loadWhenHasConfigurationPropertiesValidatorShouldApplyValidator() { assertThatExceptionOfType(Exception.class).isThrownBy(() -> load(WithCustomValidatorConfiguration.class)) - .satisfies((ex) -> { - assertThat(ex).hasCauseInstanceOf(BindException.class); - assertThat(ex.getCause()).hasCauseExactlyInstanceOf(BindValidationException.class); - }); + .satisfies((ex) -> { + assertThat(ex).hasCauseInstanceOf(BindException.class); + assertThat(ex.getCause()).hasCauseExactlyInstanceOf(BindValidationException.class); + }); } @Test void loadWhenHasUnsupportedConfigurationPropertiesValidatorShouldBind() { load(WithUnsupportedCustomValidatorConfiguration.class, "test.foo=bar"); WithSetterThatThrowsValidationExceptionProperties bean = this.context - .getBean(WithSetterThatThrowsValidationExceptionProperties.class); + .getBean(WithSetterThatThrowsValidationExceptionProperties.class); assertThat(bean.getFoo()).isEqualTo("bar"); } @@ -740,18 +741,18 @@ class ConfigurationPropertiesTests { @Test void loadWhenSetterThrowsValidationExceptionShouldFail() { assertThatExceptionOfType(BeanCreationException.class) - .isThrownBy(() -> load(WithSetterThatThrowsValidationExceptionProperties.class, "test.foo=spam")) - .withCauseInstanceOf(BindException.class); + .isThrownBy(() -> load(WithSetterThatThrowsValidationExceptionProperties.class, "test.foo=spam")) + .withCauseInstanceOf(BindException.class); } @Test void loadWhenFailsShouldIncludeAnnotationDetails() { removeSystemProperties(); assertThatExceptionOfType(ConfigurationPropertiesBindException.class) - .isThrownBy(() -> load(IgnoreUnknownFieldsFalseConfiguration.class, "name=foo", "bar=baz")) - .withMessageContaining("Could not bind properties to " - + "'ConfigurationPropertiesTests.IgnoreUnknownFieldsFalseProperties' : " - + "prefix=, ignoreInvalidFields=false, ignoreUnknownFields=false;"); + .isThrownBy(() -> load(IgnoreUnknownFieldsFalseConfiguration.class, "name=foo", "bar=baz")) + .withMessageContaining("Could not bind properties to " + + "'ConfigurationPropertiesTests.IgnoreUnknownFieldsFalseProperties' : " + + "prefix=, ignoreInvalidFields=false, ignoreUnknownFields=false;"); } @Test @@ -812,9 +813,9 @@ class ConfigurationPropertiesTests { @Test void loadWhenConfigurationPropertiesInjectsAnotherBeanShouldNotFail() { assertThatExceptionOfType(ConfigurationPropertiesBindException.class) - .isThrownBy(() -> load(OtherInjectPropertiesConfiguration.class)) - .withMessageContaining(OtherInjectedProperties.class.getName()) - .withMessageContaining("Failed to bind properties under 'test'"); + .isThrownBy(() -> load(OtherInjectPropertiesConfiguration.class)) + .withMessageContaining(OtherInjectedProperties.class.getName()) + .withMessageContaining("Failed to bind properties under 'test'"); } @Test @@ -840,7 +841,7 @@ class ConfigurationPropertiesTests { sources.addLast(new MapPropertySource("test", source)); load(ConstructorParameterWithUnitConfiguration.class); ConstructorParameterWithUnitProperties bean = this.context - .getBean(ConstructorParameterWithUnitProperties.class); + .getBean(ConstructorParameterWithUnitProperties.class); assertThat(bean.getDuration()).isEqualTo(Duration.ofDays(12)); assertThat(bean.getSize()).isEqualTo(DataSize.ofMegabytes(13)); assertThat(bean.getPeriod()).isEqualTo(Period.ofYears(14)); @@ -858,7 +859,7 @@ class ConfigurationPropertiesTests { void loadWhenBindingToConstructorParametersWithEmptyDefaultValueShouldBind() { load(ConstructorParameterEmptyDefaultValueConfiguration.class); ConstructorParameterEmptyDefaultValueProperties bean = this.context - .getBean(ConstructorParameterEmptyDefaultValueProperties.class); + .getBean(ConstructorParameterEmptyDefaultValueProperties.class); assertThat(bean.getSet()).isEmpty(); assertThat(bean.getMap()).isEmpty(); assertThat(bean.getArray()).isEmpty(); @@ -869,7 +870,7 @@ class ConfigurationPropertiesTests { void loadWhenBindingToConstructorParametersWithDefaultDataUnitShouldBind() { load(ConstructorParameterWithUnitConfiguration.class); ConstructorParameterWithUnitProperties bean = this.context - .getBean(ConstructorParameterWithUnitProperties.class); + .getBean(ConstructorParameterWithUnitProperties.class); assertThat(bean.getDuration()).isEqualTo(Duration.ofDays(2)); assertThat(bean.getSize()).isEqualTo(DataSize.ofMegabytes(3)); assertThat(bean.getPeriod()).isEqualTo(Period.ofYears(4)); @@ -884,7 +885,7 @@ class ConfigurationPropertiesTests { sources.addLast(new MapPropertySource("test", source)); load(ConstructorParameterWithFormatConfiguration.class); ConstructorParameterWithFormatProperties bean = this.context - .getBean(ConstructorParameterWithFormatProperties.class); + .getBean(ConstructorParameterWithFormatProperties.class); assertThat(bean.getDuration()).isEqualTo(Duration.ofDays(12)); assertThat(bean.getPeriod()).isEqualTo(Period.ofYears(13)); } @@ -896,8 +897,9 @@ class ConfigurationPropertiesTests { source.put("test.duration", "P12D"); sources.addLast(new MapPropertySource("test", source)); assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> load(ConstructorParameterWithFormatConfiguration.class)).havingCause() - .isInstanceOf(BindException.class); + .isThrownBy(() -> load(ConstructorParameterWithFormatConfiguration.class)) + .havingCause() + .isInstanceOf(BindException.class); } @Test @@ -907,15 +909,16 @@ class ConfigurationPropertiesTests { source.put("test.period", "P12D"); sources.addLast(new MapPropertySource("test", source)); assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> load(ConstructorParameterWithFormatConfiguration.class)).havingCause() - .isInstanceOf(BindException.class); + .isThrownBy(() -> load(ConstructorParameterWithFormatConfiguration.class)) + .havingCause() + .isInstanceOf(BindException.class); } @Test void loadWhenBindingToConstructorParametersWithDefaultDataFormatShouldBind() { load(ConstructorParameterWithFormatConfiguration.class); ConstructorParameterWithFormatProperties bean = this.context - .getBean(ConstructorParameterWithFormatProperties.class); + .getBean(ConstructorParameterWithFormatProperties.class); assertThat(bean.getDuration()).isEqualTo(Duration.ofDays(2)); assertThat(bean.getPeriod()).isEqualTo(Period.ofYears(3)); } @@ -923,10 +926,11 @@ class ConfigurationPropertiesTests { @Test void loadWhenBindingToConstructorParametersShouldValidate() { assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> load(ConstructorParameterValidationConfiguration.class)).satisfies((ex) -> { - assertThat(ex).hasCauseInstanceOf(BindException.class); - assertThat(ex.getCause()).hasCauseExactlyInstanceOf(BindValidationException.class); - }); + .isThrownBy(() -> load(ConstructorParameterValidationConfiguration.class)) + .satisfies((ex) -> { + assertThat(ex).hasCauseInstanceOf(BindException.class); + assertThat(ex.getCause()).hasCauseExactlyInstanceOf(BindValidationException.class); + }); } @Test @@ -935,8 +939,8 @@ class ConfigurationPropertiesTests { BasicProperties bean = this.context.getBean(BasicProperties.class); assertThat(bean.name).isEqualTo("test"); bean.name = "override"; - this.context.getBean(ConfigurationPropertiesBindingPostProcessor.class).postProcessBeforeInitialization(bean, - "does-not-exist"); + this.context.getBean(ConfigurationPropertiesBindingPostProcessor.class) + .postProcessBeforeInitialization(bean, "does-not-exist"); assertThat(bean.name).isEqualTo("test"); } @@ -962,7 +966,7 @@ class ConfigurationPropertiesTests { sources.addLast(new MapPropertySource("test", source)); load(MultiConstructorConfigurationPropertiesConfiguration.class); MultiConstructorConfigurationListProperties bean = this.context - .getBean(MultiConstructorConfigurationListProperties.class); + .getBean(MultiConstructorConfigurationListProperties.class); MultiConstructorConfigurationProperties nested = bean.getNested().get(0); assertThat(nested.getName()).isEqualTo("spring"); assertThat(nested.getAge()).isEqualTo(5); @@ -976,7 +980,7 @@ class ConfigurationPropertiesTests { sources.addLast(new MapPropertySource("test", source)); load(MultiConstructorConfigurationPropertiesConfiguration.class); MultiConstructorConfigurationListProperties bean = this.context - .getBean(MultiConstructorConfigurationListProperties.class); + .getBean(MultiConstructorConfigurationListProperties.class); MultiConstructorConfigurationProperties nested = bean.getNested().get(0); assertThat(nested.getName()).isEqualTo("spring"); assertThat(nested.getAge()).isEqualTo(0); @@ -1014,7 +1018,7 @@ class ConfigurationPropertiesTests { sources.addLast(new MapPropertySource("test", source)); load(JavaBeanNestedConstructorBindingPropertiesConfiguration.class); JavaBeanNestedConstructorBindingProperties bean = this.context - .getBean(JavaBeanNestedConstructorBindingProperties.class); + .getBean(JavaBeanNestedConstructorBindingProperties.class); assertThat(bean.getNested().getAge()).isEqualTo(5); } @@ -1037,7 +1041,7 @@ class ConfigurationPropertiesTests { sources.addLast(new MapPropertySource("test", source)); load(JavaBeanNonDefaultConstructorPropertiesConfiguration.class); JavaBeanNonDefaultConstructorProperties bean = this.context - .getBean(JavaBeanNonDefaultConstructorProperties.class); + .getBean(JavaBeanNonDefaultConstructorProperties.class); assertThat(bean.getNested().getAge()).isEqualTo(10); } @@ -1058,7 +1062,7 @@ class ConfigurationPropertiesTests { sources.addLast(new MapPropertySource("test", source)); load(ConstructorBindingWithOuterClassConstructorBoundConfiguration.class); ConstructorBindingWithOuterClassConstructorBoundProperties bean = this.context - .getBean(ConstructorBindingWithOuterClassConstructorBoundProperties.class); + .getBean(ConstructorBindingWithOuterClassConstructorBoundProperties.class); assertThat(bean.getNested().getOuter().getAge()).isEqualTo(5); } @@ -1099,7 +1103,7 @@ class ConfigurationPropertiesTests { this.context.getBeanFactory().setConversionService(ApplicationConversionService.getSharedInstance()); load(WithCustomConverterAndObjectToObjectMethodConfiguration.class, "test.item=foo"); WithCustomConverterAndObjectToObjectMethodProperties bean = this.context - .getBean(WithCustomConverterAndObjectToObjectMethodProperties.class); + .getBean(WithCustomConverterAndObjectToObjectMethodProperties.class); assertThat(bean.getItem().getValue()).isEqualTo("foo"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesRegistrarTests.java index 571fc63960..70b2ba6759 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesRegistrarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,7 +56,7 @@ class EnableConfigurationPropertiesRegistrarTests { void typeWithDefaultConstructorShouldRegisterRootBeanDefinition() { register(TestConfiguration.class); BeanDefinition definition = this.beanFactory - .getBeanDefinition("foo-" + getClass().getName() + "$FooProperties"); + .getBeanDefinition("foo-" + getClass().getName() + "$FooProperties"); assertThat(definition).satisfies(configurationPropertiesBeanDefinition(BindMethod.JAVA_BEAN)); } @@ -64,7 +64,7 @@ class EnableConfigurationPropertiesRegistrarTests { void typeWithConstructorBindingShouldRegisterConfigurationPropertiesBeanDefinition() { register(TestConfiguration.class); BeanDefinition definition = this.beanFactory - .getBeanDefinition("bar-" + getClass().getName() + "$BarProperties"); + .getBeanDefinition("bar-" + getClass().getName() + "$BarProperties"); assertThat(definition).satisfies(configurationPropertiesBeanDefinition(BindMethod.VALUE_OBJECT)); } @@ -72,15 +72,15 @@ class EnableConfigurationPropertiesRegistrarTests { void typeWithMultipleConstructorsShouldRegisterGenericBeanDefinition() { register(TestConfiguration.class); BeanDefinition definition = this.beanFactory - .getBeanDefinition("bing-" + getClass().getName() + "$BingProperties"); + .getBeanDefinition("bing-" + getClass().getName() + "$BingProperties"); assertThat(definition).satisfies(configurationPropertiesBeanDefinition(BindMethod.JAVA_BEAN)); } @Test void typeWithNoAnnotationShouldFail() { assertThatIllegalStateException().isThrownBy(() -> register(InvalidConfiguration.class)) - .withMessageContaining("No ConfigurationProperties annotation found") - .withMessageContaining(EnableConfigurationPropertiesRegistrar.class.getName()); + .withMessageContaining("No ConfigurationProperties annotation found") + .withMessageContaining(EnableConfigurationPropertiesRegistrar.class.getName()); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/IncompatibleConfigurationFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/IncompatibleConfigurationFailureAnalyzerTests.java index 344a3df993..72cb48f621 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/IncompatibleConfigurationFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/IncompatibleConfigurationFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ class IncompatibleConfigurationFailureAnalyzerTests { assertThat(failureAnalysis.getDescription()).contains( "The following configuration properties have incompatible values: [spring.first.key, spring.second.key]"); assertThat(failureAnalysis.getAction()) - .contains("Review the docs for spring.first.key, spring.second.key and change the configured values."); + .contains("Review the docs for spring.first.key, spring.second.key and change the configured values."); } private FailureAnalysis performAnalysis(String... keys) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/NotConstructorBoundInjectionFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/NotConstructorBoundInjectionFailureAnalyzerTests.java index d580a3ba99..6edc44685d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/NotConstructorBoundInjectionFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/NotConstructorBoundInjectionFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,9 +44,9 @@ class NotConstructorBoundInjectionFailureAnalyzerTests { + " is annotated with @" + ConstructorBinding.class.getSimpleName() + " but it is defined as a regular bean which caused dependency injection to fail."); assertThat(analysis.getAction()) - .isEqualTo("Update your configuration so that " + ConstructorBoundProperties.class.getSimpleName() - + " is defined via @" + ConfigurationPropertiesScan.class.getSimpleName() + " or @" - + EnableConfigurationProperties.class.getSimpleName() + "."); + .isEqualTo("Update your configuration so that " + ConstructorBoundProperties.class.getSimpleName() + + " is defined via @" + ConfigurationPropertiesScan.class.getSimpleName() + " or @" + + EnableConfigurationProperties.class.getSimpleName() + "."); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java index 392b024731..46fa6d4205 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,13 +62,13 @@ class PropertyMapperTests { @Test void fromWhenSupplierIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.map.from((Supplier) null)) - .withMessageContaining("Supplier must not be null"); + .withMessageContaining("Supplier must not be null"); } @Test void toWhenConsumerIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.map.from(() -> "").to(null)) - .withMessageContaining("Consumer must not be null"); + .withMessageContaining("Consumer must not be null"); } @Test @@ -88,7 +88,7 @@ class PropertyMapperTests { @Test void asWhenAdapterIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.map.from(() -> "").as(null)) - .withMessageContaining("Adapter must not be null"); + .withMessageContaining("Adapter must not be null"); } @Test @@ -185,8 +185,12 @@ class PropertyMapperTests { @Test void whenWhenCombinedWithAsUsesSourceValue() { Count source = new Count<>(() -> "123"); - Long result = this.map.from(source).when("123"::equals).as(Integer::valueOf).when((v) -> v == 123) - .as(Integer::longValue).toInstance(Long::valueOf); + Long result = this.map.from(source) + .when("123"::equals) + .as(Integer::valueOf) + .when((v) -> v == 123) + .as(Integer::longValue) + .toInstance(Long::valueOf); assertThat(result).isEqualTo(123); assertThat(source.getCount()).isOne(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertySourcesDeducerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertySourcesDeducerTests.java index bae6e8963d..6cb182a36f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertySourcesDeducerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertySourcesDeducerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,8 +79,8 @@ class PropertySourcesDeducerTests { Environment environment = mock(Environment.class); given(applicationContext.getEnvironment()).willReturn(environment); PropertySourcesDeducer deducer = new PropertySourcesDeducer(applicationContext); - assertThatIllegalStateException().isThrownBy(() -> deducer.getPropertySources()).withMessage( - "Unable to obtain PropertySources from PropertySourcesPlaceholderConfigurer or Environment"); + assertThatIllegalStateException().isThrownBy(() -> deducer.getPropertySources()) + .withMessage("Unable to obtain PropertySources from PropertySourcesPlaceholderConfigurer or Environment"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java index 9b4d01fe7b..34aafd28a0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,10 +73,10 @@ class ArrayBinderTests { BindHandler handler = mockBindHandler(); this.binder.bind("foo", INTEGER_LIST, handler); InOrder inOrder = inOrder(handler); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo[0]")), eq(Bindable.of(Integer.class)), - any(), eq(1)); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(INTEGER_LIST), any(), - isA(List.class)); + inOrder.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo[0]")), eq(Bindable.of(Integer.class)), any(), eq(1)); + inOrder.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(INTEGER_LIST), any(), isA(List.class)); } @Test @@ -141,14 +141,14 @@ class ArrayBinderTests { source.put("foo[3]", "3"); this.sources.add(source); assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.binder.bind("foo", INTEGER_ARRAY)) - .satisfies((ex) -> { - Set unbound = ((UnboundConfigurationPropertiesException) ex.getCause()) - .getUnboundProperties(); - assertThat(unbound.size()).isEqualTo(1); - ConfigurationProperty property = unbound.iterator().next(); - assertThat(property.getName().toString()).isEqualTo("foo[3]"); - assertThat(property.getValue()).isEqualTo("3"); - }); + .satisfies((ex) -> { + Set unbound = ((UnboundConfigurationPropertiesException) ex.getCause()) + .getUnboundProperties(); + assertThat(unbound.size()).isEqualTo(1); + ConfigurationProperty property = unbound.iterator().next(); + assertThat(property.getName().toString()).isEqualTo("foo[3]"); + assertThat(property.getValue()).isEqualTo("3"); + }); } @Test @@ -204,10 +204,10 @@ class ArrayBinderTests { Bindable target = INTEGER_ARRAY; this.binder.bind("foo", target, handler); InOrder inOrder = inOrder(handler); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo[0]")), eq(Bindable.of(Integer.class)), - any(), eq(1)); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), - isA(Integer[].class)); + inOrder.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo[0]")), eq(Bindable.of(Integer.class)), any(), eq(1)); + inOrder.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), isA(Integer[].class)); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BackCompatibilityBinderIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BackCompatibilityBinderIntegrationTests.java index 7c010d2ead..93b75241dc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BackCompatibilityBinderIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BackCompatibilityBinderIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,9 @@ class BackCompatibilityBinderIntegrationTests { StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, Collections.singletonMap("FOO_ZK_NODES", "foo")); environment.getPropertySources().addFirst(propertySource); - ExampleCamelCaseBean result = Binder.get(environment).bind("foo", Bindable.of(ExampleCamelCaseBean.class)) - .get(); + ExampleCamelCaseBean result = Binder.get(environment) + .bind("foo", Bindable.of(ExampleCamelCaseBean.class)) + .get(); assertThat(result.getZkNodes()).isEqualTo("foo"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java index 7ee4fb899a..6768f00cff 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,7 +70,7 @@ class BindConverterTests { void canConvertWhenHasDefaultEditorShouldReturnTrue() { BindConverter bindConverter = getPropertyEditorOnlyBindConverter(null); assertThat(bindConverter.canConvert("java.lang.RuntimeException", ResolvableType.forClass(Class.class))) - .isTrue(); + .isTrue(); } @Test @@ -89,7 +89,7 @@ class BindConverterTests { void canConvertWhenHasEditorForCollectionElementShouldReturnTrue() { BindConverter bindConverter = getPropertyEditorOnlyBindConverter(this::registerSampleTypeEditor); assertThat(bindConverter.canConvert("test", ResolvableType.forClassWithGenerics(List.class, SampleType.class))) - .isTrue(); + .isTrue(); } @Test @@ -159,7 +159,7 @@ class BindConverterTests { void convertWhenNotPropertyEditorAndConversionServiceCannotConvertShouldThrowException() { BindConverter bindConverter = BindConverter.get(null, null); assertThatExceptionOfType(ConverterNotFoundException.class) - .isThrownBy(() -> bindConverter.convert("test", ResolvableType.forClass(SampleType.class))); + .isThrownBy(() -> bindConverter.convert("test", ResolvableType.forClass(SampleType.class))); } @Test @@ -185,8 +185,8 @@ class BindConverterTests { BindConverter bindConverter = BindConverter.get(Collections.singletonList(new GenericConversionService()), null); assertThatExceptionOfType(ConversionFailedException.class) - .isThrownBy(() -> bindConverter.convert("com.example.Missing", ResolvableType.forClass(Class.class))) - .withRootCauseInstanceOf(ClassNotFoundException.class); + .isThrownBy(() -> bindConverter.convert("com.example.Missing", ResolvableType.forClass(Class.class))) + .withRootCauseInstanceOf(ClassNotFoundException.class); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java index 3e744ad15a..b6ea33be96 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,7 +62,7 @@ class BindResultTests { void getWhenHasNoValueShouldThrowException() { BindResult result = BindResult.of(null); assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(result::get) - .withMessageContaining("No value bound"); + .withMessageContaining("No value bound"); } @Test @@ -81,7 +81,7 @@ class BindResultTests { void ifBoundWhenConsumerIsNullShouldThrowException() { BindResult result = BindResult.of("foo"); assertThatIllegalArgumentException().isThrownBy(() -> result.ifBound(null)) - .withMessageContaining("Consumer must not be null"); + .withMessageContaining("Consumer must not be null"); } @Test @@ -102,7 +102,7 @@ class BindResultTests { void mapWhenMapperIsNullShouldThrowException() { BindResult result = BindResult.of("foo"); assertThatIllegalArgumentException().isThrownBy(() -> result.map(null)) - .withMessageContaining("Mapper must not be null"); + .withMessageContaining("Mapper must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java index 4fcebdf11c..6c7321cd03 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,13 +42,13 @@ class BindableTests { @Test void ofClassWhenTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> Bindable.of((Class) null)) - .withMessageContaining("Type must not be null"); + .withMessageContaining("Type must not be null"); } @Test void ofTypeWhenTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> Bindable.of((ResolvableType) null)) - .withMessageContaining("Type must not be null"); + .withMessageContaining("Type must not be null"); } @Test @@ -78,14 +78,14 @@ class BindableTests { @Test void ofTypeWithExistingValueShouldSetTypeAndExistingValue() { assertThat(Bindable.of(ResolvableType.forClass(String.class)).withExistingValue("foo").getValue().get()) - .isEqualTo("foo"); + .isEqualTo("foo"); } @Test void ofTypeWhenExistingValueIsNotInstanceOfTypeShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> Bindable.of(ResolvableType.forClass(String.class)).withExistingValue(123)) - .withMessageContaining("ExistingValue must be an instance of " + String.class.getName()); + .isThrownBy(() -> Bindable.of(ResolvableType.forClass(String.class)).withExistingValue(123)) + .withMessageContaining("ExistingValue must be an instance of " + String.class.getName()); } @Test @@ -131,7 +131,7 @@ class BindableTests { void getAnnotationWhenMatchShouldReturnAnnotation() { Test annotation = AnnotationUtils.synthesizeAnnotation(Test.class); assertThat(Bindable.of(String.class).withAnnotations(annotation).getAnnotation(Test.class)) - .isSameAs(annotation); + .isSameAs(annotation); } @Test @@ -145,8 +145,8 @@ class BindableTests { Annotation annotation = AnnotationUtils.synthesizeAnnotation(TestAnnotation.class); Bindable bindable = Bindable.of(String.class).withExistingValue("foo").withAnnotations(annotation); assertThat(bindable.toString()) - .contains("type = java.lang.String, value = 'provided', annotations = array[" - + "@org.springframework.boot.context.properties.bind.BindableTests.TestAnnotation()]"); + .contains("type = java.lang.String, value = 'provided', annotations = array[" + + "@org.springframework.boot.context.properties.bind.BindableTests.TestAnnotation()]"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java index cd46b6b8a3..2a622ebb53 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,38 +74,40 @@ class BinderTests { @Test void createWhenSourcesIsNullArrayShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new Binder((ConfigurationPropertySource[]) null)) - .withMessageContaining("Sources must not be null"); + .withMessageContaining("Sources must not be null"); } @Test void createWhenSourcesIsNullIterableShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new Binder((Iterable) null)) - .withMessageContaining("Sources must not be null"); + .withMessageContaining("Sources must not be null"); } @Test void createWhenArraySourcesContainsNullElementShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new Binder(new ConfigurationPropertySource[] { null })) - .withMessageContaining("Sources must not contain null elements"); + .withMessageContaining("Sources must not contain null elements"); } @Test void createWhenIterableSourcesContainsNullElementShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new Binder(Collections.singletonList(null))) - .withMessageContaining("Sources must not contain null elements"); + .withMessageContaining("Sources must not contain null elements"); } @Test void bindWhenNameIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy(() -> this.binder.bind((ConfigurationPropertyName) null, - Bindable.of(String.class), BindHandler.DEFAULT)).withMessageContaining("Name must not be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.binder.bind((ConfigurationPropertyName) null, Bindable.of(String.class), + BindHandler.DEFAULT)) + .withMessageContaining("Name must not be null"); } @Test void bindWhenTargetIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.binder.bind(ConfigurationPropertyName.of("foo"), null, BindHandler.DEFAULT)) - .withMessageContaining("Target must not be null"); + .isThrownBy(() -> this.binder.bind(ConfigurationPropertyName.of("foo"), null, BindHandler.DEFAULT)) + .withMessageContaining("Target must not be null"); } @Test @@ -225,10 +227,10 @@ class BinderTests { Bindable target = Bindable.of(JavaBean.class); this.binder.bind("foo", target, handler); InOrder inOrder = inOrder(handler); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo.value")), eq(Bindable.of(String.class)), - any(), eq("bar")); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), - isA(JavaBean.class)); + inOrder.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo.value")), eq(Bindable.of(String.class)), any(), eq("bar")); + inOrder.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), isA(JavaBean.class)); } @Test @@ -239,18 +241,18 @@ class BinderTests { Bindable target = Bindable.of(JavaBean.class); binder.bind("foo", target); InOrder inOrder = inOrder(handler); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo.value")), eq(Bindable.of(String.class)), - any(), eq("bar")); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), - isA(JavaBean.class)); + inOrder.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo.value")), eq(Bindable.of(String.class)), any(), eq("bar")); + inOrder.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), isA(JavaBean.class)); } @Test void bindWhenHasMalformedDateShouldThrowException() { this.sources.add(new MockConfigurationPropertySource("foo", "2014-04-01T01:30:00.000-05:00")); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", Bindable.of(LocalDate.class))) - .withCauseInstanceOf(ConversionFailedException.class); + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(LocalDate.class))) + .withCauseInstanceOf(ConversionFailedException.class); } @Test @@ -301,7 +303,7 @@ class BinderTests { source.put("value", "hello"); source.put("", "bar"); Iterable propertySources = ConfigurationPropertySources - .from(new MapPropertySource("test", source)); + .from(new MapPropertySource("test", source)); propertySources.forEach(this.sources::add); Bindable target = Bindable.of(JavaBean.class); JavaBean result = this.binder.bind("", target).get(); @@ -347,7 +349,7 @@ class BinderTests { @Test void bindToJavaBeanWithPublicConstructorWhenHasBindRestriction() { Bindable bindable = Bindable.of(JavaBeanWithPublicConstructor.class) - .withBindRestrictions(BindRestriction.NO_DIRECT_PROPERTY); + .withBindRestrictions(BindRestriction.NO_DIRECT_PROPERTY); JavaBeanWithPublicConstructor result = bindToJavaBeanWithPublicConstructor(bindable); assertThat(result.getValue()).isEqualTo("setter"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java index 34238bf53d..a0e57229fc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -88,7 +88,7 @@ class CollectionBinderTests { source.put("foo[1][1]", "4"); this.sources.add(source); Bindable>> target = Bindable - .of(ResolvableType.forClassWithGenerics(List.class, INTEGER_LIST.getType())); + .of(ResolvableType.forClassWithGenerics(List.class, INTEGER_LIST.getType())); List> result = this.binder.bind("foo", target).get(); assertThat(result).hasSize(2); assertThat(result.get(0)).containsExactly(1, 2); @@ -114,14 +114,14 @@ class CollectionBinderTests { source.put("foo[3]", "3"); this.sources.add(source); assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.binder.bind("foo", INTEGER_LIST)) - .satisfies((ex) -> { - Set unbound = ((UnboundConfigurationPropertiesException) ex.getCause()) - .getUnboundProperties(); - assertThat(unbound).hasSize(1); - ConfigurationProperty property = unbound.iterator().next(); - assertThat(property.getName().toString()).isEqualTo("foo[3]"); - assertThat(property.getValue()).isEqualTo("3"); - }); + .satisfies((ex) -> { + Set unbound = ((UnboundConfigurationPropertiesException) ex.getCause()) + .getUnboundProperties(); + assertThat(unbound).hasSize(1); + ConfigurationProperty property = unbound.iterator().next(); + assertThat(property.getName().toString()).isEqualTo("foo[3]"); + assertThat(property.getValue()).isEqualTo("3"); + }); } @Test @@ -133,14 +133,14 @@ class CollectionBinderTests { this.sources.add(source); Bindable> target = Bindable.listOf(JavaBean.class); assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.binder.bind("foo", target)) - .satisfies((ex) -> { - Set unbound = ((UnboundConfigurationPropertiesException) ex.getCause()) - .getUnboundProperties(); - assertThat(unbound).hasSize(1); - ConfigurationProperty property = unbound.iterator().next(); - assertThat(property.getName().toString()).isEqualTo("foo[4].value"); - assertThat(property.getValue()).isEqualTo("4"); - }); + .satisfies((ex) -> { + Set unbound = ((UnboundConfigurationPropertiesException) ex.getCause()) + .getUnboundProperties(); + assertThat(unbound).hasSize(1); + ConfigurationProperty property = unbound.iterator().next(); + assertThat(property.getName().toString()).isEqualTo("foo[4].value"); + assertThat(property.getValue()).isEqualTo("4"); + }); } @Test @@ -308,7 +308,8 @@ class CollectionBinderTests { source.put("foo.items", "a,b,c,c"); this.sources.add(source); ExampleCustomNoDefaultConstructorBean result = this.binder - .bind("foo", ExampleCustomNoDefaultConstructorBean.class).get(); + .bind("foo", ExampleCustomNoDefaultConstructorBean.class) + .get(); assertThat(result.getItems()).hasSize(4); assertThat(result.getItems()).containsExactly("a", "b", "c", "c"); } @@ -320,7 +321,8 @@ class CollectionBinderTests { source.put("foo.items", "a,b,c,c"); this.sources.add(source); ExampleCustomWithDefaultConstructorBean result = this.binder - .bind("foo", ExampleCustomWithDefaultConstructorBean.class).get(); + .bind("foo", ExampleCustomWithDefaultConstructorBean.class) + .get(); assertThat(result.getItems()).hasSize(4); assertThat(result.getItems()).containsExactly("a", "b", "c", "c"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java index 9ead5a9403..ed21c49c9a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -83,7 +83,7 @@ class JavaBeanBinderTests { source.put("enum-value", "foo-bar"); this.sources.add(source); ExampleValueBean bean = this.binder.bind(ConfigurationPropertyName.of(""), Bindable.of(ExampleValueBean.class)) - .get(); + .get(); assertThat(bean.getIntValue()).isEqualTo(12); assertThat(bean.getLongValue()).isEqualTo(34); assertThat(bean.getStringValue()).isEqualTo("foo"); @@ -100,7 +100,8 @@ class JavaBeanBinderTests { this.sources.add(source); ExampleValueBean bean = new ExampleValueBean(); ExampleValueBean boundBean = this.binder - .bind("foo", Bindable.of(ExampleValueBean.class).withExistingValue(bean)).get(); + .bind("foo", Bindable.of(ExampleValueBean.class).withExistingValue(bean)) + .get(); assertThat(boundBean).isSameAs(bean); assertThat(bean.getIntValue()).isEqualTo(12); assertThat(bean.getLongValue()).isEqualTo(34); @@ -138,7 +139,8 @@ class JavaBeanBinderTests { ExampleDefaultsBean bean = new ExampleDefaultsBean(); bean.setFoo(888); ExampleDefaultsBean boundBean = this.binder - .bind("foo", Bindable.of(ExampleDefaultsBean.class).withExistingValue(bean)).get(); + .bind("foo", Bindable.of(ExampleDefaultsBean.class).withExistingValue(bean)) + .get(); assertThat(boundBean).isSameAs(bean); assertThat(bean.getFoo()).isEqualTo(888); assertThat(bean.getBar()).isEqualTo(999); @@ -171,8 +173,8 @@ class JavaBeanBinderTests { source.put("foo.list[2]", "bar-baz"); this.sources.add(source); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleListBean.class))) - .withCauseInstanceOf(UnboundConfigurationPropertiesException.class); + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleListBean.class))) + .withCauseInstanceOf(UnboundConfigurationPropertiesException.class); } @Test @@ -201,7 +203,8 @@ class JavaBeanBinderTests { source.put("foo.collection", "foo-bar|bar-baz"); this.sources.add(source); ExampleCollectionBeanWithDelimiter bean = this.binder - .bind("foo", Bindable.of(ExampleCollectionBeanWithDelimiter.class)).get(); + .bind("foo", Bindable.of(ExampleCollectionBeanWithDelimiter.class)) + .get(); assertThat(bean.getCollection()).containsExactly(ExampleEnum.FOO_BAR, ExampleEnum.BAR_BAZ); } @@ -212,7 +215,7 @@ class JavaBeanBinderTests { source.put("foo.map.bar-baz", "2"); this.sources.add(source); ExampleMapBeanWithoutSetter bean = this.binder.bind("foo", Bindable.of(ExampleMapBeanWithoutSetter.class)) - .get(); + .get(); assertThat(bean.getMap()).containsExactly(entry(ExampleEnum.FOO_BAR, 1), entry(ExampleEnum.BAR_BAZ, 2)); } @@ -223,7 +226,7 @@ class JavaBeanBinderTests { source.put("foo.list[1]", "bar-baz"); this.sources.add(source); ExampleListBeanWithoutSetter bean = this.binder.bind("foo", Bindable.of(ExampleListBeanWithoutSetter.class)) - .get(); + .get(); assertThat(bean.getList()).containsExactly(ExampleEnum.FOO_BAR, ExampleEnum.BAR_BAZ); } @@ -234,7 +237,7 @@ class JavaBeanBinderTests { source.put("foo.set[1]", "bar-baz"); this.sources.add(source); ExampleSetBeanWithoutSetter bean = this.binder.bind("foo", Bindable.of(ExampleSetBeanWithoutSetter.class)) - .get(); + .get(); assertThat(bean.getSet()).containsExactly(ExampleEnum.FOO_BAR, ExampleEnum.BAR_BAZ); } @@ -245,7 +248,8 @@ class JavaBeanBinderTests { source.put("foo.collection[1]", "bar-baz"); this.sources.add(source); ExampleCollectionBeanWithoutSetter bean = this.binder - .bind("foo", Bindable.of(ExampleCollectionBeanWithoutSetter.class)).get(); + .bind("foo", Bindable.of(ExampleCollectionBeanWithoutSetter.class)) + .get(); assertThat(bean.getCollection()).containsExactly(ExampleEnum.FOO_BAR, ExampleEnum.BAR_BAZ); } @@ -267,7 +271,8 @@ class JavaBeanBinderTests { source.put("foo.value-bean.string-value", "foo"); this.sources.add(source); ExampleNestedBeanWithoutSetterOrType bean = this.binder - .bind("foo", Bindable.of(ExampleNestedBeanWithoutSetterOrType.class)).get(); + .bind("foo", Bindable.of(ExampleNestedBeanWithoutSetterOrType.class)) + .get(); ExampleValueBean valueBean = (ExampleValueBean) bean.getValueBean(); assertThat(valueBean.getIntValue()).isEqualTo(123); assertThat(valueBean.getStringValue()).isEqualTo("foo"); @@ -293,7 +298,7 @@ class JavaBeanBinderTests { source.put("foo.value-bean.string-value", "foo"); this.sources.add(source); ExampleNestedBeanWithoutSetter bean = this.binder.bind("foo", Bindable.of(ExampleNestedBeanWithoutSetter.class)) - .get(); + .get(); assertThat(bean.getValueBean().getIntValue()).isEqualTo(123); assertThat(bean.getValueBean().getStringValue()).isEqualTo("foo"); } @@ -304,7 +309,7 @@ class JavaBeanBinderTests { source.put("foo.nested.foo", "bar"); this.sources.add(source); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleImmutableNestedBeanWithoutSetter.class))); + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleImmutableNestedBeanWithoutSetter.class))); } @Test @@ -361,7 +366,8 @@ class JavaBeanBinderTests { this.sources.add(source); ExampleWithNonDefaultConstructor bean = new ExampleWithNonDefaultConstructor("faf"); ExampleWithNonDefaultConstructor boundBean = binder - .bind("foo", Bindable.of(ExampleWithNonDefaultConstructor.class).withExistingValue(bean)).get(); + .bind("foo", Bindable.of(ExampleWithNonDefaultConstructor.class).withExistingValue(bean)) + .get(); assertThat(boundBean).isSameAs(bean); assertThat(bean.getValue()).isEqualTo("bar"); } @@ -381,7 +387,7 @@ class JavaBeanBinderTests { void bindToClassWhenPropertyCannotBeConvertedShouldThrowException() { this.sources.add(new MockConfigurationPropertySource("foo.int-value", "foo")); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValueBean.class))); + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValueBean.class))); } @Test @@ -444,7 +450,7 @@ class JavaBeanBinderTests { source.put("foo.date", "2014-04-01"); this.sources.add(source); ConverterAnnotatedExampleBean bean = this.binder.bind("foo", Bindable.of(ConverterAnnotatedExampleBean.class)) - .get(); + .get(); assertThat(bean.getDate().toString()).isEqualTo("2014-04-01"); } @@ -455,7 +461,7 @@ class JavaBeanBinderTests { source.put("foo.value", "java.lang.RuntimeException"); this.sources.add(source); ExampleWithPropertyEditorType bean = this.binder.bind("foo", Bindable.of(ExampleWithPropertyEditorType.class)) - .get(); + .get(); assertThat(bean.getValue()).isEqualTo(RuntimeException.class); } @@ -465,7 +471,7 @@ class JavaBeanBinderTests { source.put("foo.name", "something"); this.sources.add(source); ExampleWithInvalidAccessors bean = this.binder.bind("foo", Bindable.of(ExampleWithInvalidAccessors.class)) - .get(); + .get(); assertThat(bean.getName()).isEqualTo("something"); } @@ -499,7 +505,7 @@ class JavaBeanBinderTests { source.put("foo.property", "some string"); this.sources.add(source); PropertyWithOverloadedSetter bean = this.binder.bind("foo", Bindable.of(PropertyWithOverloadedSetter.class)) - .get(); + .get(); assertThat(bean.getProperty()).isEqualTo("some string"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java index f4f0d9afb9..545f9f6c6f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -131,7 +131,8 @@ class MapBinderTests { source.put("faf.far.bin", "x"); this.sources.add(source); Map> result = this.binder - .bind("foo", Bindable.>>of(type)).get(); + .bind("foo", Bindable.>>of(type)) + .get(); assertThat(result).hasSize(2); assertThat(result.get("bar")).containsEntry("baz", 1).containsEntry("bin", 2); assertThat(result.get("far")).containsEntry("baz", 3).containsEntry("bin", 4); @@ -301,7 +302,7 @@ class MapBinderTests { source.put("foo.ccc.ddd.eee", "bazboo"); this.sources.add(source); Map result = this.binder.bind("foo", Bindable.mapOf(String.class, ExampleEnum.class)) - .get(); + .get(); assertThat(result).hasSize(3); assertThat(result).containsEntry("aaa.bbb.ccc", ExampleEnum.FOO_BAR); assertThat(result).containsEntry("bbb.ccc.ddd", ExampleEnum.BAR_BAZ); @@ -316,7 +317,7 @@ class MapBinderTests { this.sources.add(source); this.binder = new Binder(this.sources, new PropertySourcesPlaceholdersResolver(environment)); Map result = this.binder.bind("foo", Bindable.mapOf(String.class, ExampleEnum.class)) - .get(); + .get(); assertThat(result).containsEntry("aaa.bbb.ccc", ExampleEnum.BAZ_BOO); } @@ -335,8 +336,8 @@ class MapBinderTests { Bindable> target = STRING_INTEGER_MAP; this.binder.bind("foo", target, handler); InOrder ordered = inOrder(handler); - ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo.bar")), eq(Bindable.of(Integer.class)), - any(), eq(1)); + ordered.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo.bar")), eq(Bindable.of(Integer.class)), any(), eq(1)); ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), isA(Map.class)); } @@ -348,8 +349,9 @@ class MapBinderTests { this.binder.bind("foo", target, handler); InOrder ordered = inOrder(handler); ArgumentCaptor array = ArgumentCaptor.forClass(String[].class); - ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo.bar")), eq(Bindable.of(String[].class)), - any(), array.capture()); + ordered.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo.bar")), eq(Bindable.of(String[].class)), any(), + array.capture()); assertThat(array.getValue()).containsExactly("a", "b", "c"); ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), isA(Map.class)); } @@ -559,7 +561,8 @@ class MapBinderTests { source.put("foo.items.a", "b"); this.sources.add(source); ExampleCustomNoDefaultConstructorBean result = this.binder - .bind("foo", ExampleCustomNoDefaultConstructorBean.class).get(); + .bind("foo", ExampleCustomNoDefaultConstructorBean.class) + .get(); assertThat(result.getItems()).containsOnly(entry("foo", "bar"), entry("a", "b")); } @@ -570,7 +573,8 @@ class MapBinderTests { source.put("foo.items.a", "b"); this.sources.add(source); ExampleCustomWithDefaultConstructorBean result = this.binder - .bind("foo", ExampleCustomWithDefaultConstructorBean.class).get(); + .bind("foo", ExampleCustomWithDefaultConstructorBean.class) + .get(); assertThat(result.getItems()).containsExactly(entry("a", "b")); } @@ -581,7 +585,8 @@ class MapBinderTests { source.put("foo.values.e", "f"); this.sources.add(source); Map result = this.binder - .bind("foo.values", STRING_STRING_MAP.withExistingValue(Collections.singletonMap("a", "b"))).get(); + .bind("foo.values", STRING_STRING_MAP.withExistingValue(Collections.singletonMap("a", "b"))) + .get(); assertThat(result).hasSize(3); assertThat(result).containsExactly(entry("a", "b"), entry("c", "d"), entry("e", "f")); } @@ -604,7 +609,7 @@ class MapBinderTests { this.sources.add(source); MapWithWildcardProperties result = this.binder.bind("foo", Bindable.of(MapWithWildcardProperties.class)).get(); assertThat(result.getAddresses().get("localhost").stream().map(InetAddress::getHostAddress)) - .containsExactly("127.0.0.1", "127.0.0.2"); + .containsExactly("127.0.0.1", "127.0.0.2"); } private Bindable> getMapBindable(Class keyGeneric, ResolvableType valueType) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java index 7ef7214b52..3b4e283bbc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,8 @@ class PropertySourcesPlaceholdersResolverTests { @Test void placeholderResolverIfEnvironmentNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new PropertySourcesPlaceholdersResolver((Environment) null)) - .withMessageContaining("Environment must not be null"); + .isThrownBy(() -> new PropertySourcesPlaceholdersResolver((Environment) null)) + .withMessageContaining("Environment must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java index 529e2aeeb7..569073aa26 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -89,7 +89,7 @@ class ValueObjectBinderTests { source.put("enum-value", "foo-bar"); this.sources.add(source); ExampleValueBean bean = this.binder.bind(ConfigurationPropertyName.of(""), Bindable.of(ExampleValueBean.class)) - .get(); + .get(); assertThat(bean.getIntValue()).isEqualTo(12); assertThat(bean.getLongValue()).isEqualTo(34); assertThat(bean.isBooleanValue()).isTrue(); @@ -143,7 +143,8 @@ class ValueObjectBinderTests { source.put("foo.int-value", "12"); this.sources.add(source); MultipleConstructorsOnlyOneNotPrivateBean bean = this.binder - .bind("foo", Bindable.of(MultipleConstructorsOnlyOneNotPrivateBean.class)).get(); + .bind("foo", Bindable.of(MultipleConstructorsOnlyOneNotPrivateBean.class)) + .get(); bean = bean.withString("test"); assertThat(bean.getIntValue()).isEqualTo(12); assertThat(bean.getStringValue()).isEqualTo("test"); @@ -199,7 +200,7 @@ class ValueObjectBinderTests { source.put("foo.date", "2014-04-01"); this.sources.add(source); ConverterAnnotatedExampleBean bean = this.binder.bind("foo", Bindable.of(ConverterAnnotatedExampleBean.class)) - .get(); + .get(); assertThat(bean.getDate().toString()).isEqualTo("2014-04-01"); } @@ -209,7 +210,7 @@ class ValueObjectBinderTests { source.put("foo.bar", "hello"); this.sources.add(source); ConverterAnnotatedExampleBean bean = this.binder.bind("foo", Bindable.of(ConverterAnnotatedExampleBean.class)) - .get(); + .get(); assertThat(bean.getDate().toString()).isEqualTo("2019-05-10"); } @@ -219,7 +220,8 @@ class ValueObjectBinderTests { source.put("foo.property", "test"); this.sources.add(source); ExamplePackagePrivateConstructorBean bound = this.binder - .bind("foo", Bindable.of(ExamplePackagePrivateConstructorBean.class)).get(); + .bind("foo", Bindable.of(ExamplePackagePrivateConstructorBean.class)) + .get(); assertThat(bound.getProperty()).isEqualTo("test"); } @@ -261,7 +263,7 @@ class ValueObjectBinderTests { this.sources.add(source); Bindable target = Bindable.of(ValidatingConstructorBean.class); assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.binder.bind("foo", target)) - .satisfies(this::noConfigurationProperty); + .satisfies(this::noConfigurationProperty); } @Test @@ -271,9 +273,10 @@ class ValueObjectBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value.bar", "baz"); this.sources.add(source); - GenericValue> bean = this.binder.bind("foo", Bindable + GenericValue> bean = this.binder + .bind("foo", Bindable .>>of(ResolvableType.forClassWithGenerics(GenericValue.class, type))) - .get(); + .get(); assertThat(bean.getValue().get("bar")).isEqualTo("baz"); } @@ -288,9 +291,9 @@ class ValueObjectBinderTests { @Test void bindWhenJavaLangParameterWithEmptyDefaultValueShouldThrowException() { assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bindOrCreate("foo", - Bindable.of(NestedConstructorBeanWithEmptyDefaultValueForJavaLangTypes.class))) - .withStackTraceContaining("Parameter of type java.lang.String must have a non-empty default value."); + .isThrownBy(() -> this.binder.bindOrCreate("foo", + Bindable.of(NestedConstructorBeanWithEmptyDefaultValueForJavaLangTypes.class))) + .withStackTraceContaining("Parameter of type java.lang.String must have a non-empty default value."); } @Test @@ -324,18 +327,18 @@ class ValueObjectBinderTests { @Test void bindWhenEnumParameterWithEmptyDefaultValueShouldThrowException() { assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bindOrCreate("foo", - Bindable.of(NestedConstructorBeanWithEmptyDefaultValueForEnumTypes.class))) - .withStackTraceContaining( - "Parameter of type org.springframework.boot.context.properties.bind.ValueObjectBinderTests$NestedConstructorBeanWithEmptyDefaultValueForEnumTypes$Foo must have a non-empty default value."); + .isThrownBy(() -> this.binder.bindOrCreate("foo", + Bindable.of(NestedConstructorBeanWithEmptyDefaultValueForEnumTypes.class))) + .withStackTraceContaining( + "Parameter of type org.springframework.boot.context.properties.bind.ValueObjectBinderTests$NestedConstructorBeanWithEmptyDefaultValueForEnumTypes$Foo must have a non-empty default value."); } @Test void bindWhenPrimitiveParameterWithEmptyDefaultValueShouldThrowException() { assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bindOrCreate("foo", - Bindable.of(NestedConstructorBeanWithEmptyDefaultValueForPrimitiveTypes.class))) - .withStackTraceContaining("Parameter of type int must have a non-empty default value."); + .isThrownBy(() -> this.binder.bindOrCreate("foo", + Bindable.of(NestedConstructorBeanWithEmptyDefaultValueForPrimitiveTypes.class))) + .withStackTraceContaining("Parameter of type int must have a non-empty default value."); } @Test @@ -392,7 +395,7 @@ class ValueObjectBinderTests { ClassLoader ucl = new URLClassLoader(new URL[] { tempDir.toURI().toURL() }); Object bean = this.binder.bind("test.record", Class.forName("RecordProperties", true, ucl)).get(); assertThat(bean).hasFieldOrPropertyWithValue("property1", "value-from-config-1") - .hasFieldOrPropertyWithValue("property2", "default-value-2"); + .hasFieldOrPropertyWithValue("property2", "default-value-2"); } private void noConfigurationProperty(BindException ex) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java index df9c908ef9..02d147de36 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ class IgnoreErrorsBindHandlerTests { @Test void bindWhenNotIgnoringErrorsShouldFail() { assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class))); + .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class))); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java index d557c416b1..024da3ee36 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,8 @@ class IgnoreTopLevelConverterNotFoundBindHandlerTests { @Test void bindWhenHandlerNotPresentShouldFail() { assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class))) - .withCauseInstanceOf(ConverterNotFoundException.class); + .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class))) + .withCauseInstanceOf(ConverterNotFoundException.class); } @Test @@ -69,9 +69,9 @@ class IgnoreTopLevelConverterNotFoundBindHandlerTests { source.put("example.foo", "1"); this.sources.add(source); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class), - new IgnoreTopLevelConverterNotFoundBindHandler())) - .withCauseInstanceOf(IllegalStateException.class); + .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class), + new IgnoreTopLevelConverterNotFoundBindHandler())) + .withCauseInstanceOf(IllegalStateException.class); } @Test @@ -80,9 +80,9 @@ class IgnoreTopLevelConverterNotFoundBindHandlerTests { source.put("example.map", "hello"); this.sources.add(source); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class), - new IgnoreTopLevelConverterNotFoundBindHandler())) - .withCauseInstanceOf(ConverterNotFoundException.class); + .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class), + new IgnoreTopLevelConverterNotFoundBindHandler())) + .withCauseInstanceOf(ConverterNotFoundException.class); } static class Example { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java index f10e46b2cd..5e4f7a2ff5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,7 +62,7 @@ class NoUnboundElementsBindHandlerTests { this.sources.add(source); this.binder = new Binder(this.sources); Example bound = this.binder.bind("example", Bindable.of(Example.class), new NoUnboundElementsBindHandler()) - .get(); + .get(); assertThat(bound.getFoo()).isEqualTo("bar"); } @@ -73,10 +73,11 @@ class NoUnboundElementsBindHandlerTests { source.put("example.baz", "bar"); this.sources.add(source); this.binder = new Binder(this.sources); - assertThatExceptionOfType(BindException.class).isThrownBy( - () -> this.binder.bind("example", Bindable.of(Example.class), new NoUnboundElementsBindHandler())) - .satisfies((ex) -> assertThat(ex.getCause().getMessage()) - .contains("The elements [example.baz] were left unbound")); + assertThatExceptionOfType(BindException.class) + .isThrownBy( + () -> this.binder.bind("example", Bindable.of(Example.class), new NoUnboundElementsBindHandler())) + .satisfies((ex) -> assertThat(ex.getCause().getMessage()) + .contains("The elements [example.baz] were left unbound")); } @Test @@ -87,7 +88,7 @@ class NoUnboundElementsBindHandlerTests { this.sources.add(source); this.binder = new Binder(this.sources); Example bound = this.binder.bind("example", Bindable.of(Example.class), new NoUnboundElementsBindHandler()) - .get(); + .get(); assertThat(bound.getFoo()).isEqualTo("bar"); } @@ -125,10 +126,11 @@ class NoUnboundElementsBindHandlerTests { source.put("example.foo[0]", "bar"); this.sources.add(source); this.binder = new Binder(this.sources); - assertThatExceptionOfType(BindException.class).isThrownBy( - () -> this.binder.bind("example", Bindable.of(Example.class), new NoUnboundElementsBindHandler())) - .satisfies((ex) -> assertThat(ex.getCause().getMessage()) - .contains("The elements [example.foo[0]] were left unbound")); + assertThatExceptionOfType(BindException.class) + .isThrownBy( + () -> this.binder.bind("example", Bindable.of(Example.class), new NoUnboundElementsBindHandler())) + .satisfies((ex) -> assertThat(ex.getCause().getMessage()) + .contains("The elements [example.foo[0]] were left unbound")); } @Test @@ -145,7 +147,7 @@ class NoUnboundElementsBindHandlerTests { this.binder = new Binder(this.sources); NoUnboundElementsBindHandler handler = new NoUnboundElementsBindHandler(); ExampleWithNestedList bound = this.binder.bind("example", Bindable.of(ExampleWithNestedList.class), handler) - .get(); + .get(); assertThat(bound.getNested().get(0).getStringValue()).isEqualTo("bar"); } @@ -161,10 +163,10 @@ class NoUnboundElementsBindHandlerTests { this.sources.add(source2); this.binder = new Binder(this.sources); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("example", Bindable.of(ExampleWithNestedList.class), - new NoUnboundElementsBindHandler())) - .satisfies((ex) -> assertThat(ex.getCause().getMessage()) - .contains("The elements [example.nested[1].invalid] were left unbound")); + .isThrownBy(() -> this.binder.bind("example", Bindable.of(ExampleWithNestedList.class), + new NoUnboundElementsBindHandler())) + .satisfies((ex) -> assertThat(ex.getCause().getMessage()) + .contains("The elements [example.nested[1].invalid] were left unbound")); } static class Example { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/test/PackagePrivateBeanBindingTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/test/PackagePrivateBeanBindingTests.java index cec4eec197..b976002091 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/test/PackagePrivateBeanBindingTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/test/PackagePrivateBeanBindingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,7 +55,7 @@ class PackagePrivateBeanBindingTests { source.put("foo.bar", "999"); this.sources.add(source); ExamplePackagePrivateBean bean = this.binder.bind(this.name, Bindable.of(ExamplePackagePrivateBean.class)) - .get(); + .get(); assertThat(bean.getBar()).isEqualTo(999); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java index 29cd41ed8b..b3d1f734dd 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ class BindValidationExceptionTests { @Test void createWhenValidationErrorsIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new BindValidationException(null)) - .withMessageContaining("ValidationErrors must not be null"); + .withMessageContaining("ValidationErrors must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldErrorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldErrorTests.java index 61c3ca9875..5f83c0b289 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldErrorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldErrorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,8 +57,8 @@ class OriginTrackedFieldErrorTests { @Test void toStringShouldAddOrigin() { assertThat(OriginTrackedFieldError.of(FIELD_ERROR, ORIGIN).toString()) - .isEqualTo("Field error in object 'foo' on field 'bar': rejected value [null]" - + "; codes []; arguments []; default message [faf]; origin afile"); + .isEqualTo("Field error in object 'foo' on field 'bar': rejected value [null]" + + "; codes []; arguments []; default message [faf]; origin afile"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java index 34480b24a3..731e63cb64 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -88,24 +88,23 @@ class ValidationBindHandlerTests { void bindShouldFailWithHandler() { this.sources.add(new MockConfigurationPropertySource("foo.age", 4)); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValidatedBean.class), this.handler)) - .withCauseInstanceOf(BindValidationException.class); + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValidatedBean.class), this.handler)) + .withCauseInstanceOf(BindValidationException.class); } @Test void bindShouldValidateNestedProperties() { this.sources.add(new MockConfigurationPropertySource("foo.nested.age", 4)); assertThatExceptionOfType(BindException.class) - .isThrownBy( - () -> this.binder.bind("foo", Bindable.of(ExampleValidatedWithNestedBean.class), this.handler)) - .withCauseInstanceOf(BindValidationException.class); + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValidatedWithNestedBean.class), this.handler)) + .withCauseInstanceOf(BindValidationException.class); } @Test void bindShouldFailWithAccessToOrigin() { this.sources.add(new MockConfigurationPropertySource("foo.age", 4, "file")); BindValidationException cause = bindAndExpectValidationError(() -> this.binder - .bind(ConfigurationPropertyName.of("foo"), Bindable.of(ExampleValidatedBean.class), this.handler)); + .bind(ConfigurationPropertyName.of("foo"), Bindable.of(ExampleValidatedBean.class), this.handler)); ObjectError objectError = cause.getValidationErrors().getAllErrors().get(0); assertThat(Origin.from(objectError).toString()).isEqualTo("file"); } @@ -120,8 +119,8 @@ class ValidationBindHandlerTests { BindValidationException cause = bindAndExpectValidationError(() -> this.binder.bind( ConfigurationPropertyName.of("foo"), Bindable.of(ExampleValidatedWithNestedBean.class), this.handler)); Set boundProperties = cause.getValidationErrors().getBoundProperties(); - assertThat(boundProperties).extracting((p) -> p.getName().toString()).contains("foo.nested.age", - "foo.nested.name"); + assertThat(boundProperties).extracting((p) -> p.getName().toString()) + .contains("foo.nested.age", "foo.nested.name"); } @Test @@ -168,9 +167,9 @@ class ValidationBindHandlerTests { this.sources.add(new MockConfigurationPropertySource("foo", "hello")); ExampleValidatedBean bean = new ExampleValidatedBean(); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", - Bindable.of(ExampleValidatedBean.class).withExistingValue(bean), this.handler)) - .withCauseInstanceOf(ConverterNotFoundException.class); + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValidatedBean.class).withExistingValue(bean), + this.handler)) + .withCauseInstanceOf(ConverterNotFoundException.class); } @Test @@ -180,9 +179,9 @@ class ValidationBindHandlerTests { this.sources.add(new MockConfigurationPropertySource("foo", "hello")); ExampleValidatedBean bean = new ExampleValidatedBean(); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", - Bindable.of(ExampleValidatedBean.class).withExistingValue(bean), this.handler)) - .withCauseInstanceOf(BindValidationException.class); + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValidatedBean.class).withExistingValue(bean), + this.handler)) + .withCauseInstanceOf(BindValidationException.class); } @Test @@ -194,17 +193,17 @@ class ValidationBindHandlerTests { this.sources.add(new MockConfigurationPropertySource("foo.years", "99")); ExampleValidatedBean bean = new ExampleValidatedBean(); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", - Bindable.of(ExampleValidatedBean.class).withExistingValue(bean), this.handler)) - .withCauseInstanceOf(BindValidationException.class) - .satisfies((ex) -> assertThat(ex.getCause()).hasMessageContaining("years")); + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValidatedBean.class).withExistingValue(bean), + this.handler)) + .withCauseInstanceOf(BindValidationException.class) + .satisfies((ex) -> assertThat(ex.getCause()).hasMessageContaining("years")); } @Test void validationErrorsForCamelCaseFieldsShouldContainRejectedValue() { this.sources.add(new MockConfigurationPropertySource("foo.inner.person-age", 2)); BindValidationException cause = bindAndExpectValidationError(() -> this.binder - .bind(ConfigurationPropertyName.of("foo"), Bindable.of(ExampleCamelCase.class), this.handler)); + .bind(ConfigurationPropertyName.of("foo"), Bindable.of(ExampleCamelCase.class), this.handler)); assertThat(cause.getMessage()).contains("rejected value [2]"); } @@ -212,7 +211,7 @@ class ValidationBindHandlerTests { void validationShouldBeSkippedIfPreviousValidationErrorPresent() { this.sources.add(new MockConfigurationPropertySource("foo.inner.person-age", 2)); BindValidationException cause = bindAndExpectValidationError(() -> this.binder - .bind(ConfigurationPropertyName.of("foo"), Bindable.of(ExampleCamelCase.class), this.handler)); + .bind(ConfigurationPropertyName.of("foo"), Bindable.of(ExampleCamelCase.class), this.handler)); FieldError fieldError = (FieldError) cause.getValidationErrors().getAllErrors().get(0); assertThat(fieldError.getField()).isEqualTo("personAge"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java index a3657e6065..4a5ca36eb0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,20 +47,20 @@ class ValidationErrorsTests { @Test void createWhenNameIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ValidationErrors(null, Collections.emptySet(), Collections.emptyList())) - .withMessageContaining("Name must not be null"); + .isThrownBy(() -> new ValidationErrors(null, Collections.emptySet(), Collections.emptyList())) + .withMessageContaining("Name must not be null"); } @Test void createWhenBoundPropertiesIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ValidationErrors(NAME, null, Collections.emptyList())) - .withMessageContaining("BoundProperties must not be null"); + .withMessageContaining("BoundProperties must not be null"); } @Test void createWhenErrorsIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ValidationErrors(NAME, Collections.emptySet(), null)) - .withMessageContaining("Errors must not be null"); + .withMessageContaining("Errors must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySourceTests.java index 8556562334..77dc3ff0a0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ class AliasedConfigurationPropertySourceTests { source.put("foo.bar", "bing"); source.put("foo.baz", "biff"); ConfigurationPropertySource aliased = source.nonIterable() - .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); + .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); assertThat(getValue(aliased, "foo.bar")).isEqualTo("bing"); assertThat(getValue(aliased, "foo.bar1")).isEqualTo("bing"); } @@ -47,7 +47,7 @@ class AliasedConfigurationPropertySourceTests { source.put("foo.bar", "bing"); source.put("foo.baz", "biff"); ConfigurationPropertySource aliased = source.nonIterable() - .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); + .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); assertThat(getValue(aliased, "foo.baz")).isEqualTo("biff"); } @@ -56,7 +56,7 @@ class AliasedConfigurationPropertySourceTests { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = new KnownAncestorsConfigurationPropertySource().unknown(name); ConfigurationPropertySource aliased = source - .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); + .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); assertThat(aliased.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.UNKNOWN); } @@ -64,9 +64,9 @@ class AliasedConfigurationPropertySourceTests { void containsDescendantOfWhenSourceReturnsPresentShouldReturnPresent() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = new KnownAncestorsConfigurationPropertySource().present(name) - .unknown(ConfigurationPropertyName.of("bar")); + .unknown(ConfigurationPropertyName.of("bar")); ConfigurationPropertySource aliased = source - .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); + .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); assertThat(aliased.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.PRESENT); } @@ -74,7 +74,7 @@ class AliasedConfigurationPropertySourceTests { void containsDescendantOfWhenAllAreAbsentShouldReturnAbsent() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = new KnownAncestorsConfigurationPropertySource().absent(name) - .absent(ConfigurationPropertyName.of("bar")); + .absent(ConfigurationPropertyName.of("bar")); ConfigurationPropertySource aliased = source.withAliases(new ConfigurationPropertyNameAliases("foo", "bar")); assertThat(aliased.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.ABSENT); } @@ -83,7 +83,7 @@ class AliasedConfigurationPropertySourceTests { void containsDescendantOfWhenAnyIsPresentShouldReturnPresent() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = new KnownAncestorsConfigurationPropertySource().absent(name) - .present(ConfigurationPropertyName.of("bar")); + .present(ConfigurationPropertyName.of("bar")); ConfigurationPropertySource aliased = source.withAliases(new ConfigurationPropertyNameAliases("foo", "bar")); assertThat(aliased.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.PRESENT); } @@ -93,9 +93,9 @@ class AliasedConfigurationPropertySourceTests { ConfigurationPropertySource source = new MapConfigurationPropertySource( Collections.singletonMap("foo.bar", "foobar")); ConfigurationPropertySource aliased = source - .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "baz.foo")); + .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "baz.foo")); assertThat(aliased.containsDescendantOf(ConfigurationPropertyName.of("baz"))) - .isEqualTo(ConfigurationPropertyState.PRESENT); + .isEqualTo(ConfigurationPropertyState.PRESENT); } private Object getValue(ConfigurationPropertySource source, String name) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySourceTests.java index 95599959a3..fdd2769208 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ class AliasedIterableConfigurationPropertySourceTests extends AliasedConfigurati source.put("foo.bar", "bing"); source.put("foo.baz", "biff"); IterableConfigurationPropertySource aliased = source - .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); + .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); assertThat(aliased.stream()).containsExactly(ConfigurationPropertyName.of("foo.bar"), ConfigurationPropertyName.of("foo.bar1"), ConfigurationPropertyName.of("foo.baz")); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyCachingTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyCachingTests.java index 13edbc49ed..aa84049991 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyCachingTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyCachingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,8 +63,8 @@ class ConfigurationPropertyCachingTests { @Test void getFromSourcesWhenSourcesIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> ConfigurationPropertyCaching.get((Iterable) null)) - .withMessage("Sources must not be null"); + .isThrownBy(() -> ConfigurationPropertyCaching.get((Iterable) null)) + .withMessage("Sources must not be null"); } @Test @@ -89,8 +89,8 @@ class ConfigurationPropertyCachingTests { sources.add(SpringConfigurationPropertySource.from(this.propertySource)); MapPropertySource anotherPropertySource = new MapPropertySource("test2", Collections.emptyMap()); assertThatIllegalStateException() - .isThrownBy(() -> ConfigurationPropertyCaching.get(sources, anotherPropertySource)) - .withMessage("Unable to find cache from configuration property sources"); + .isThrownBy(() -> ConfigurationPropertyCaching.get(sources, anotherPropertySource)) + .withMessage("Unable to find cache from configuration property sources"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java index 3ae273f1b5..7a91afa5e3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,14 +32,14 @@ class ConfigurationPropertyNameAliasesTests { @Test void createWithStringWhenNullNameShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigurationPropertyNameAliases((String) null)) - .withMessageContaining("Name must not be null"); + .withMessageContaining("Name must not be null"); } @Test void createWithStringShouldAddMapping() { ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases("foo", "bar", "baz"); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) - .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); + .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); } @Test @@ -48,7 +48,7 @@ class ConfigurationPropertyNameAliasesTests { ConfigurationPropertyName.of("foo"), ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) - .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); + .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); } @Test @@ -56,7 +56,7 @@ class ConfigurationPropertyNameAliasesTests { ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases(); aliases.addAliases("foo", "bar", "baz"); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) - .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); + .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); } @Test @@ -65,7 +65,7 @@ class ConfigurationPropertyNameAliasesTests { aliases.addAliases(ConfigurationPropertyName.of("foo"), ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) - .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); + .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); } @Test @@ -74,7 +74,7 @@ class ConfigurationPropertyNameAliasesTests { aliases.addAliases("foo", "bar"); aliases.addAliases("foo", "baz"); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) - .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); + .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); } @Test @@ -88,7 +88,7 @@ class ConfigurationPropertyNameAliasesTests { ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases(); aliases.addAliases("foo", "bar"); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) - .containsExactly(ConfigurationPropertyName.of("bar")); + .containsExactly(ConfigurationPropertyName.of("bar")); } @Test @@ -97,9 +97,9 @@ class ConfigurationPropertyNameAliasesTests { aliases.addAliases("foo", "bar"); aliases.addAliases("foo", "baz"); assertThat((Object) aliases.getNameForAlias(ConfigurationPropertyName.of("bar"))) - .isEqualTo(ConfigurationPropertyName.of("foo")); + .isEqualTo(ConfigurationPropertyName.of("foo")); assertThat((Object) aliases.getNameForAlias(ConfigurationPropertyName.of("baz"))) - .isEqualTo(ConfigurationPropertyName.of("foo")); + .isEqualTo(ConfigurationPropertyName.of("foo")); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java index 11ca1d56b3..e0afc334b4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,31 +42,35 @@ class ConfigurationPropertyNameTests { @Test void ofNameShouldNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> ConfigurationPropertyName.of(null)) - .withMessageContaining("Name must not be null"); + .withMessageContaining("Name must not be null"); } @Test void ofNameShouldNotStartWithDash() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("-foo")).withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("-foo")) + .withMessageContaining("is not valid"); } @Test void ofNameShouldNotStartWithDot() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of(".foo")).withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of(".foo")) + .withMessageContaining("is not valid"); } @Test void ofNameShouldNotEndWithDot() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("foo.")).withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("foo.")) + .withMessageContaining("is not valid"); } @Test void ofNameShouldNotContainUppercase() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("fOo")).withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("fOo")) + .withMessageContaining("is not valid"); } @Test @@ -74,8 +78,8 @@ class ConfigurationPropertyNameTests { String invalid = "_@$%*+=':;"; for (char c : invalid.toCharArray()) { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("foo" + c)) - .satisfies((ex) -> assertThat(ex.getMessage()).contains("is not valid")); + .isThrownBy(() -> ConfigurationPropertyName.of("foo" + c)) + .satisfies((ex) -> assertThat(ex.getMessage()).contains("is not valid")); } } @@ -154,19 +158,22 @@ class ConfigurationPropertyNameTests { @Test void ofNameWhenMissingCloseBracket() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("[bar")).withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("[bar")) + .withMessageContaining("is not valid"); } @Test void ofNameWhenMissingOpenBracket() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("bar]")).withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("bar]")) + .withMessageContaining("is not valid"); } @Test void ofNameWhenMultipleMismatchedBrackets() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("[a[[[b]ar]")).withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("[a[[[b]ar]")) + .withMessageContaining("is not valid"); } @Test @@ -180,7 +187,8 @@ class ConfigurationPropertyNameTests { @Test void ofNameWithWhitespaceInName() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("foo. bar")).withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("foo. bar")) + .withMessageContaining("is not valid"); } @Test @@ -225,7 +233,7 @@ class ConfigurationPropertyNameTests { @Test void adaptWhenNameIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> ConfigurationPropertyName.adapt(null, '.')) - .withMessageContaining("Name must not be null"); + .withMessageContaining("Name must not be null"); } @Test @@ -409,8 +417,8 @@ class ConfigurationPropertyNameTests { @Test void appendWhenElementNameIsNotValidShouldThrowException() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("foo").append("-bar")) - .withMessageContaining("Configuration property name '-bar' is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("foo").append("-bar")) + .withMessageContaining("Configuration property name '-bar' is not valid"); } @Test @@ -582,14 +590,14 @@ class ConfigurationPropertyNameTests { names.add(ConfigurationPropertyName.of("foo")); Collections.sort(names); assertThat(names.stream().map(ConfigurationPropertyName::toString).collect(Collectors.toList())) - .containsExactly("foo", "foo[2]", "foo[10]", "foo.bar", "foo.bard", "foo.baz"); + .containsExactly("foo", "foo[2]", "foo[10]", "foo.bar", "foo.bard", "foo.baz"); } @Test void compareDifferentLengthsShouldSortNames() { ConfigurationPropertyName name = ConfigurationPropertyName.of("spring.web.resources.chain.strategy.content"); ConfigurationPropertyName other = ConfigurationPropertyName - .of("spring.web.resources.chain.strategy.content.enabled"); + .of("spring.web.resources.chain.strategy.content.enabled"); assertThat(name.compareTo(other)).isLessThan(0); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourceTests.java index dda5128a53..6c8ae09ca8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ class ConfigurationPropertySourceTests { source.setProperty("spring", "boot"); ConfigurationPropertySource adapted = ConfigurationPropertySource.from(source); assertThat(adapted.getConfigurationProperty(ConfigurationPropertyName.of("spring")).getValue()) - .isEqualTo("boot"); + .isEqualTo("boot"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesTests.java index af0490ea98..552bbbc2ef 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,7 +66,7 @@ class ConfigurationPropertySourcesTests { ConfigurableEnvironment child = new StandardEnvironment(); child.merge(parent); child.getPropertySources() - .addLast(new MapPropertySource("config", Collections.singletonMap("my.example_property", "1234"))); + .addLast(new MapPropertySource("config", Collections.singletonMap("my.example_property", "1234"))); ConfigurationPropertySources.attach(child); assertThat(child.getProperty("my.example-property")).isEqualTo("1234"); } @@ -115,8 +115,9 @@ class ConfigurationPropertySourcesTests { @Test void fromPropertySourceShouldReturnSpringConfigurationPropertySource() { PropertySource source = new MapPropertySource("foo", Collections.singletonMap("foo", "bar")); - ConfigurationPropertySource configurationPropertySource = ConfigurationPropertySources.from(source).iterator() - .next(); + ConfigurationPropertySource configurationPropertySource = ConfigurationPropertySources.from(source) + .iterator() + .next(); assertThat(configurationPropertySource).isInstanceOf(SpringConfigurationPropertySource.class); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java index 6663cb26ce..61be906666 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,14 +35,14 @@ class ConfigurationPropertyStateTests { @Test void searchWhenIterableIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> ConfigurationPropertyState.search(null, (e) -> true)) - .withMessageContaining("Source must not be null"); + .withMessageContaining("Source must not be null"); } @Test void searchWhenPredicateIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> ConfigurationPropertyState.search(Collections.emptyList(), null)) - .withMessageContaining("Predicate must not be null"); + .isThrownBy(() -> ConfigurationPropertyState.search(Collections.emptyList(), null)) + .withMessageContaining("Predicate must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java index aaee7ba44b..ea71e128ed 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,13 +41,13 @@ class ConfigurationPropertyTests { @Test void createWhenNameIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigurationProperty(null, "bar", null)) - .withMessageContaining("Name must not be null"); + .withMessageContaining("Name must not be null"); } @Test void createWhenValueIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigurationProperty(NAME, null, null)) - .withMessageContaining("Value must not be null"); + .withMessageContaining("Value must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java index 5bce71fcd9..685a6e63cb 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,16 +34,15 @@ class FilteredConfigurationPropertiesSourceTests { @Test void createWhenSourceIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new FilteredConfigurationPropertiesSource(null, Objects::nonNull)) - .withMessageContaining("Source must not be null"); + .isThrownBy(() -> new FilteredConfigurationPropertiesSource(null, Objects::nonNull)) + .withMessageContaining("Source must not be null"); } @Test void createWhenFilterIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> new FilteredConfigurationPropertiesSource(new MockConfigurationPropertySource(), null)) - .withMessageContaining("Filter must not be null"); + .isThrownBy(() -> new FilteredConfigurationPropertiesSource(new MockConfigurationPropertySource(), null)) + .withMessageContaining("Filter must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSourceTests.java index 816c5d83bd..0b36cbbfd4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,9 @@ class FilteredIterableConfigurationPropertiesSourceTests extends FilteredConfigu void iteratorShouldFilterNames() { MockConfigurationPropertySource source = (MockConfigurationPropertySource) createTestSource(); IterableConfigurationPropertySource filtered = source.filter(this::noBrackets); - assertThat(filtered.iterator()).toIterable().extracting(ConfigurationPropertyName::toString) - .containsExactly("a", "b", "c"); + assertThat(filtered.iterator()).toIterable() + .extracting(ConfigurationPropertyName::toString) + .containsExactly("a", "b", "c"); } @Override @@ -49,9 +50,9 @@ class FilteredIterableConfigurationPropertiesSourceTests extends FilteredConfigu source.put("faf.bar[0]", "1"); IterableConfigurationPropertySource filtered = source.filter(this::noBrackets); assertThat(filtered.containsDescendantOf(ConfigurationPropertyName.of("foo"))) - .isEqualTo(ConfigurationPropertyState.PRESENT); + .isEqualTo(ConfigurationPropertyState.PRESENT); assertThat(filtered.containsDescendantOf(ConfigurationPropertyName.of("faf"))) - .isEqualTo(ConfigurationPropertyState.ABSENT); + .isEqualTo(ConfigurationPropertyState.ABSENT); } private boolean noBrackets(ConfigurationPropertyName name) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java index c7b4b2798e..dc2e63d655 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ class MapConfigurationPropertySourceTests { @Test void createWhenMapIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new MapConfigurationPropertySource(null)) - .withMessageContaining("Map must not be null"); + .withMessageContaining("Map must not be null"); } @Test @@ -52,7 +52,7 @@ class MapConfigurationPropertySourceTests { void putAllWhenMapIsNullShouldThrowException() { MapConfigurationPropertySource source = new MapConfigurationPropertySource(); assertThatIllegalArgumentException().isThrownBy(() -> source.putAll(null)) - .withMessageContaining("Map must not be null"); + .withMessageContaining("Map must not be null"); } @Test @@ -87,8 +87,8 @@ class MapConfigurationPropertySourceTests { MapConfigurationPropertySource source = new MapConfigurationPropertySource(); source.put("foo.BAR", "spring"); source.put("foo.baz", "boot"); - assertThat(source.iterator()).toIterable().containsExactly(ConfigurationPropertyName.of("foo.bar"), - ConfigurationPropertyName.of("foo.baz")); + assertThat(source.iterator()).toIterable() + .containsExactly(ConfigurationPropertyName.of("foo.bar"), ConfigurationPropertyName.of("foo.baz")); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MutuallyExclusiveConfigurationPropertiesExceptionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MutuallyExclusiveConfigurationPropertiesExceptionTests.java index 6a0676de19..51a03d3a6d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MutuallyExclusiveConfigurationPropertiesExceptionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MutuallyExclusiveConfigurationPropertiesExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,39 +37,39 @@ class MutuallyExclusiveConfigurationPropertiesExceptionTests { @Test void createWhenConfiguredNamesIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new MutuallyExclusiveConfigurationPropertiesException(null, Arrays.asList("a", "b"))) - .withMessage("ConfiguredNames must contain 2 or more names"); + .isThrownBy(() -> new MutuallyExclusiveConfigurationPropertiesException(null, Arrays.asList("a", "b"))) + .withMessage("ConfiguredNames must contain 2 or more names"); } @Test void createWhenConfiguredNamesContainsOneElementThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new MutuallyExclusiveConfigurationPropertiesException(Collections.singleton("a"), - Arrays.asList("a", "b"))) - .withMessage("ConfiguredNames must contain 2 or more names"); + .isThrownBy(() -> new MutuallyExclusiveConfigurationPropertiesException(Collections.singleton("a"), + Arrays.asList("a", "b"))) + .withMessage("ConfiguredNames must contain 2 or more names"); } @Test void createWhenMutuallyExclusiveNamesIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new MutuallyExclusiveConfigurationPropertiesException(Arrays.asList("a", "b"), null)) - .withMessage("MutuallyExclusiveNames must contain 2 or more names"); + .isThrownBy(() -> new MutuallyExclusiveConfigurationPropertiesException(Arrays.asList("a", "b"), null)) + .withMessage("MutuallyExclusiveNames must contain 2 or more names"); } @Test void createWhenMutuallyExclusiveNamesContainsOneElementThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new MutuallyExclusiveConfigurationPropertiesException(Arrays.asList("a", "b"), - Collections.singleton("a"))) - .withMessage("MutuallyExclusiveNames must contain 2 or more names"); + .isThrownBy(() -> new MutuallyExclusiveConfigurationPropertiesException(Arrays.asList("a", "b"), + Collections.singleton("a"))) + .withMessage("MutuallyExclusiveNames must contain 2 or more names"); } @Test void createBuildsSensibleMessage() { List names = Arrays.asList("a", "b"); assertThat(new MutuallyExclusiveConfigurationPropertiesException(names, names)) - .hasMessage("The configuration properties 'a, b' are mutually exclusive " - + "and 'a, b' have been configured together"); + .hasMessage("The configuration properties 'a, b' are mutually exclusive " + + "and 'a, b' have been configured together"); } @Test @@ -117,10 +117,11 @@ class MutuallyExclusiveConfigurationPropertiesExceptionTests { entries.put("a", "a"); entries.put("b", "B"); entries.put("c", null); - })).satisfies((ex) -> { - assertThat(ex.getConfiguredNames()).containsExactly("a", "b"); - assertThat(ex.getMutuallyExclusiveNames()).containsExactly("a", "b", "c"); - }); + })) + .satisfies((ex) -> { + assertThat(ex.getConfiguredNames()).containsExactly("a", "b"); + assertThat(ex.getMutuallyExclusiveNames()).containsExactly("a", "b", "c"); + }); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/PrefixedConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/PrefixedConfigurationPropertySourceTests.java index 19290644dd..0bb6a66728 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/PrefixedConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/PrefixedConfigurationPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,27 +45,27 @@ class PrefixedConfigurationPropertySourceTests { ConfigurationPropertySource source = new KnownAncestorsConfigurationPropertySource().unknown(name); ConfigurationPropertySource prefixed = source.withPrefix("my"); assertThat(prefixed.containsDescendantOf(ConfigurationPropertyName.of("foo"))) - .isEqualTo(ConfigurationPropertyState.UNKNOWN); + .isEqualTo(ConfigurationPropertyState.UNKNOWN); } @Test void containsDescendantOfWhenSourceReturnsPresentShouldReturnPresent() { ConfigurationPropertyName name = ConfigurationPropertyName.of("my.foo"); ConfigurationPropertySource source = new KnownAncestorsConfigurationPropertySource().present(name) - .unknown(ConfigurationPropertyName.of("bar")); + .unknown(ConfigurationPropertyName.of("bar")); ConfigurationPropertySource prefixed = source.withPrefix("my"); assertThat(prefixed.containsDescendantOf(ConfigurationPropertyName.of("foo"))) - .isEqualTo(ConfigurationPropertyState.PRESENT); + .isEqualTo(ConfigurationPropertyState.PRESENT); } @Test void containsDescendantOfWhenSourceReturnsAbsentShouldReturnAbsent() { ConfigurationPropertyName name = ConfigurationPropertyName.of("my.foo"); ConfigurationPropertySource source = new KnownAncestorsConfigurationPropertySource().absent(name) - .absent(ConfigurationPropertyName.of("bar")); + .absent(ConfigurationPropertyName.of("bar")); ConfigurationPropertySource prefixed = source.withPrefix("my"); assertThat(prefixed.containsDescendantOf(ConfigurationPropertyName.of("foo"))) - .isEqualTo(ConfigurationPropertyState.ABSENT); + .isEqualTo(ConfigurationPropertyState.ABSENT); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java index 0821afd933..7ebbbaf2ce 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,8 @@ class SpringConfigurationPropertySourceTests { @Test void createWhenPropertySourceIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new SpringConfigurationPropertySource(null, mock(PropertyMapper.class))) - .withMessageContaining("PropertySource must not be null"); + .isThrownBy(() -> new SpringConfigurationPropertySource(null, mock(PropertyMapper.class))) + .withMessageContaining("PropertySource must not be null"); } @Test @@ -94,13 +94,13 @@ class SpringConfigurationPropertySourceTests { SpringConfigurationPropertySource adapter = new SpringConfigurationPropertySource(propertySource, DefaultPropertyMapper.INSTANCE); assertThat(adapter.containsDescendantOf(ConfigurationPropertyName.of("foo"))) - .isEqualTo(ConfigurationPropertyState.UNKNOWN); + .isEqualTo(ConfigurationPropertyState.UNKNOWN); } @Test void fromWhenPropertySourceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> SpringConfigurationPropertySource.from(null)) - .withMessageContaining("Source must not be null"); + .withMessageContaining("Source must not be null"); } @Test @@ -114,7 +114,7 @@ class SpringConfigurationPropertySourceTests { }; assertThat(SpringConfigurationPropertySource.from(propertySource)) - .isNotInstanceOf(IterableConfigurationPropertySource.class); + .isNotInstanceOf(IterableConfigurationPropertySource.class); } @@ -130,7 +130,7 @@ class SpringConfigurationPropertySourceTests { }; PropertySource propertySource = new MapPropertySource("test", source); assertThat(SpringConfigurationPropertySource.from(propertySource)) - .isNotInstanceOf(IterableConfigurationPropertySource.class); + .isNotInstanceOf(IterableConfigurationPropertySource.class); } @Test @@ -140,13 +140,13 @@ class SpringConfigurationPropertySourceTests { source.put("barBaz", "Boot"); PropertySource propertySource = new MapPropertySource("test", source); assertThat(SpringConfigurationPropertySource.from(propertySource)) - .isInstanceOf(IterableConfigurationPropertySource.class); + .isInstanceOf(IterableConfigurationPropertySource.class); } @Test void containsDescendantOfWhenRandomSourceAndRandomPropertyReturnsPresent() { SpringConfigurationPropertySource source = SpringConfigurationPropertySource - .from(new RandomValuePropertySource()); + .from(new RandomValuePropertySource()); ConfigurationPropertyName name = ConfigurationPropertyName.of("random"); assertThat(source.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.ABSENT); assertThat(source.getConfigurationProperty(name)).isNull(); @@ -155,7 +155,7 @@ class SpringConfigurationPropertySourceTests { @Test void containsDescendantOfWhenRandomSourceAndRandomPrefixedPropertyReturnsPresent() { SpringConfigurationPropertySource source = SpringConfigurationPropertySource - .from(new RandomValuePropertySource()); + .from(new RandomValuePropertySource()); ConfigurationPropertyName name = ConfigurationPropertyName.of("random.int"); assertThat(source.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.PRESENT); assertThat(source.getConfigurationProperty(name)).isNotNull(); @@ -164,7 +164,7 @@ class SpringConfigurationPropertySourceTests { @Test void containsDescendantOfWhenRandomSourceWithDifferentNameAndRandomPrefixedPropertyReturnsPresent() { SpringConfigurationPropertySource source = SpringConfigurationPropertySource - .from(new RandomValuePropertySource("different")); + .from(new RandomValuePropertySource("different")); ConfigurationPropertyName name = ConfigurationPropertyName.of("random.int"); assertThat(source.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.PRESENT); assertThat(source.getConfigurationProperty(name)).isNotNull(); @@ -173,7 +173,7 @@ class SpringConfigurationPropertySourceTests { @Test void containsDescendantOfWhenRandomSourceAndNonRandomPropertyReturnsAbsent() { SpringConfigurationPropertySource source = SpringConfigurationPropertySource - .from(new RandomValuePropertySource()); + .from(new RandomValuePropertySource()); ConfigurationPropertyName name = ConfigurationPropertyName.of("abandon.int"); assertThat(source.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.ABSENT); assertThat(source.getConfigurationProperty(name)).isNull(); @@ -182,7 +182,7 @@ class SpringConfigurationPropertySourceTests { @Test void containsDescendantOfWhenWrappedRandomSourceAndRandomPropertyReturnsPresent() { SpringConfigurationPropertySource source = SpringConfigurationPropertySource - .from(new RandomWrapperPropertySource()); + .from(new RandomWrapperPropertySource()); ConfigurationPropertyName name = ConfigurationPropertyName.of("cachedrandom"); assertThat(source.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.ABSENT); assertThat(source.getConfigurationProperty(name)).isNull(); @@ -191,7 +191,7 @@ class SpringConfigurationPropertySourceTests { @Test void containsDescendantOfWhenWrappedRandomSourceAndRandomPrefixedPropertyReturnsPresent() { SpringConfigurationPropertySource source = SpringConfigurationPropertySource - .from(new RandomWrapperPropertySource()); + .from(new RandomWrapperPropertySource()); ConfigurationPropertyName name = ConfigurationPropertyName.of("cachedrandom.something.int"); assertThat(source.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.ABSENT); assertThat(source.getConfigurationProperty(name)).isNull(); @@ -200,7 +200,7 @@ class SpringConfigurationPropertySourceTests { @Test void containsDescendantOfWhenWrappedRandomSourceWithMatchingNameAndRandomPrefixedPropertyReturnsPresent() { SpringConfigurationPropertySource source = SpringConfigurationPropertySource - .from(new RandomWrapperPropertySource("cachedrandom")); + .from(new RandomWrapperPropertySource("cachedrandom")); ConfigurationPropertyName name = ConfigurationPropertyName.of("cachedrandom.something.int"); assertThat(source.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.PRESENT); assertThat(source.getConfigurationProperty(name)).isNotNull(); @@ -209,7 +209,7 @@ class SpringConfigurationPropertySourceTests { @Test void containsDescendantOfWhenWrappedRandomSourceAndRandomDashPrefixedPropertyReturnsPresent() { SpringConfigurationPropertySource source = SpringConfigurationPropertySource - .from(new RandomWrapperPropertySource()); + .from(new RandomWrapperPropertySource()); ConfigurationPropertyName name = ConfigurationPropertyName.of("cached-random.something.int"); assertThat(source.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.ABSENT); assertThat(source.getConfigurationProperty(name)).isNull(); @@ -218,7 +218,7 @@ class SpringConfigurationPropertySourceTests { @Test void containsDescendantOfWhenWrappedRandomSourceAndNonRandomPropertyReturnsAbsent() { SpringConfigurationPropertySource source = SpringConfigurationPropertySource - .from(new RandomWrapperPropertySource()); + .from(new RandomWrapperPropertySource()); ConfigurationPropertyName name = ConfigurationPropertyName.of("abandon.something.int"); assertThat(source.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.ABSENT); assertThat(source.getConfigurationProperty(name)).isNull(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java index 759721ba1a..95e540eb5e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ class SpringConfigurationPropertySourcesTests { @Test void createWhenPropertySourcesIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new SpringConfigurationPropertySources(null)) - .withMessageContaining("Sources must not be null"); + .withMessageContaining("Sources must not be null"); } @Test @@ -82,8 +82,8 @@ class SpringConfigurationPropertySourcesTests { @Test void shouldNotAdaptSystemEnvironmentPropertyOverrideSource() { MutablePropertySources sources = new MutablePropertySources(); - sources.addLast( - new SystemEnvironmentPropertySource("override", Collections.singletonMap("server.port", "1234"))); + sources + .addLast(new SystemEnvironmentPropertySource("override", Collections.singletonMap("server.port", "1234"))); Iterator iterator = new SpringConfigurationPropertySources(sources).iterator(); ConfigurationPropertyName name = ConfigurationPropertyName.of("server.port"); assertThat(iterator.next().getConfigurationProperty(name).getValue()).isEqualTo("1234"); @@ -112,7 +112,7 @@ class SpringConfigurationPropertySourcesTests { assertThat(iterator.next().getConfigurationProperty(name).getValue()).isEqualTo("1234"); assertThat(iterator.next().getConfigurationProperty(name).getValue()).isEqualTo("4567"); assertThat(iterator.next().getConfigurationProperty(ConfigurationPropertyName.of("a")).getValue()) - .isEqualTo("b"); + .isEqualTo("b"); assertThat(iterator.hasNext()).isFalse(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java index 4493d596bb..3c392151f8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,8 @@ class SpringIterableConfigurationPropertySourceTests { @Test void createWhenPropertySourceIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new SpringIterableConfigurationPropertySource(null, mock(PropertyMapper.class))) - .withMessageContaining("PropertySource must not be null"); + .isThrownBy(() -> new SpringIterableConfigurationPropertySource(null, mock(PropertyMapper.class))) + .withMessageContaining("PropertySource must not be null"); } @Test @@ -70,8 +70,9 @@ class SpringIterableConfigurationPropertySourceTests { mapper2.addFromPropertySource("key2", "my.key2b"); SpringIterableConfigurationPropertySource adapter = new SpringIterableConfigurationPropertySource( propertySource, mapper1, mapper2); - assertThat(adapter.iterator()).toIterable().extracting(Object::toString).containsExactly("my.key1", "my.key2a", - "my.key4"); + assertThat(adapter.iterator()).toIterable() + .extracting(Object::toString) + .containsExactly("my.key1", "my.key2a", "my.key4"); } @Test @@ -116,7 +117,7 @@ class SpringIterableConfigurationPropertySourceTests { SpringIterableConfigurationPropertySource adapter = new SpringIterableConfigurationPropertySource( propertySource, mapper); assertThat(adapter.getConfigurationProperty(name).getOrigin().toString()) - .isEqualTo("\"key\" from property source \"test\""); + .isEqualTo("\"key\" from property source \"test\""); } @Test @@ -143,11 +144,11 @@ class SpringIterableConfigurationPropertySourceTests { SpringIterableConfigurationPropertySource adapter = new SpringIterableConfigurationPropertySource( propertySource, DefaultPropertyMapper.INSTANCE); assertThat(adapter.containsDescendantOf(ConfigurationPropertyName.of("foo"))) - .isEqualTo(ConfigurationPropertyState.PRESENT); + .isEqualTo(ConfigurationPropertyState.PRESENT); assertThat(adapter.containsDescendantOf(ConfigurationPropertyName.of("faf"))) - .isEqualTo(ConfigurationPropertyState.ABSENT); + .isEqualTo(ConfigurationPropertyState.ABSENT); assertThat(adapter.containsDescendantOf(ConfigurationPropertyName.of("fof"))) - .isEqualTo(ConfigurationPropertyState.ABSENT); + .isEqualTo(ConfigurationPropertyState.ABSENT); } @Test @@ -160,11 +161,11 @@ class SpringIterableConfigurationPropertySourceTests { SpringIterableConfigurationPropertySource adapter = new SpringIterableConfigurationPropertySource( propertySource, SystemEnvironmentPropertyMapper.INSTANCE); assertThat(adapter.containsDescendantOf(ConfigurationPropertyName.of("foo.bar-baz"))) - .isEqualTo(ConfigurationPropertyState.PRESENT); + .isEqualTo(ConfigurationPropertyState.PRESENT); assertThat(adapter.containsDescendantOf(ConfigurationPropertyName.of("foo.alpha-bravo"))) - .isEqualTo(ConfigurationPropertyState.PRESENT); + .isEqualTo(ConfigurationPropertyState.PRESENT); assertThat(adapter.containsDescendantOf(ConfigurationPropertyName.of("foo.blah"))) - .isEqualTo(ConfigurationPropertyState.ABSENT); + .isEqualTo(ConfigurationPropertyState.ABSENT); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ApplicationConversionServiceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ApplicationConversionServiceTests.java index 5fe5d23261..a722ef690a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ApplicationConversionServiceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ApplicationConversionServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -117,7 +117,7 @@ class ApplicationConversionServiceTests { @Test void sharedInstanceCannotBeModified() { ApplicationConversionService instance = (ApplicationConversionService) ApplicationConversionService - .getSharedInstance(); + .getSharedInstance(); assertUnmodifiableExceptionThrown(() -> instance.addPrinter(null)); assertUnmodifiableExceptionThrown(() -> instance.addParser(null)); assertUnmodifiableExceptionThrown(() -> instance.addFormatter(null)); @@ -133,7 +133,7 @@ class ApplicationConversionServiceTests { private void assertUnmodifiableExceptionThrown(ThrowingCallable throwingCallable) { assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(throwingCallable) - .withMessage("This ApplicationConversionService cannot be modified"); + .withMessage("This ApplicationConversionService cannot be modified"); } static class ExampleGenericConverter implements GenericConverter { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ArrayToDelimitedStringConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ArrayToDelimitedStringConverterTests.java index 40a7720a0b..bec41a5d63 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ArrayToDelimitedStringConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ArrayToDelimitedStringConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -80,7 +80,7 @@ class ArrayToDelimitedStringConverterTests { static Stream conversionServices() { return ConversionServiceArguments - .with((service) -> service.addConverter(new ArrayToDelimitedStringConverter(service))); + .with((service) -> service.addConverter(new ArrayToDelimitedStringConverter(service))); } static class Data { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CollectionToDelimitedStringConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CollectionToDelimitedStringConverterTests.java index e75f1faf9d..29b7879d2f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CollectionToDelimitedStringConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CollectionToDelimitedStringConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -82,7 +82,7 @@ class CollectionToDelimitedStringConverterTests { static Stream conversionServices() { return ConversionServiceArguments - .with((service) -> service.addConverter(new CollectionToDelimitedStringConverter(service))); + .with((service) -> service.addConverter(new CollectionToDelimitedStringConverter(service))); } static class Data { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToArrayConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToArrayConverterTests.java index 0ccb3914cf..ce9b83c8be 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToArrayConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToArrayConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ class DelimitedStringToArrayConverterTests { void matchesWhenHasAnnotationAndNonConvertibleElementTypeShouldReturnFalse(ConversionService conversionService) { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "nonConvertibleElementType"), 0); + .nested(ReflectionUtils.findField(Values.class, "nonConvertibleElementType"), 0); assertThat(new DelimitedStringToArrayConverter(conversionService).matches(sourceType, targetType)).isFalse(); } @@ -68,17 +68,17 @@ class DelimitedStringToArrayConverterTests { void matchesWhenHasAnnotationAndConvertibleElementTypeShouldReturnTrue() { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); + .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); assertThat( new DelimitedStringToArrayConverter(new ApplicationConversionService()).matches(sourceType, targetType)) - .isTrue(); + .isTrue(); } @Test void convertWhenHasConvertibleElementTypeShouldReturnConvertedType() { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); + .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); Integer[] converted = (Integer[]) new ApplicationConversionService().convert(" 1 | 2| 3 ", sourceType, targetType); assertThat(converted).containsExactly(1, 2, 3); @@ -86,7 +86,7 @@ class DelimitedStringToArrayConverterTests { static Stream conversionServices() { return ConversionServiceArguments - .with((service) -> service.addConverter(new DelimitedStringToArrayConverter(service))); + .with((service) -> service.addConverter(new DelimitedStringToArrayConverter(service))); } static class Values { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToCollectionConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToCollectionConverterTests.java index f445f2db63..69fef031c4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToCollectionConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToCollectionConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ class DelimitedStringToCollectionConverterTests { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor.nested(ReflectionUtils.findField(Values.class, "noAnnotation"), 0); assertThat(new DelimitedStringToCollectionConverter(conversionService).matches(sourceType, targetType)) - .isTrue(); + .isTrue(); } @ConversionServiceTest @@ -55,16 +55,16 @@ class DelimitedStringToCollectionConverterTests { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor.nested(ReflectionUtils.findField(Values.class, "noElementType"), 0); assertThat(new DelimitedStringToCollectionConverter(conversionService).matches(sourceType, targetType)) - .isTrue(); + .isTrue(); } @ConversionServiceTest void matchesWhenHasAnnotationAndNonConvertibleElementTypeShouldReturnFalse(ConversionService conversionService) { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "nonConvertibleElementType"), 0); + .nested(ReflectionUtils.findField(Values.class, "nonConvertibleElementType"), 0); assertThat(new DelimitedStringToCollectionConverter(conversionService).matches(sourceType, targetType)) - .isFalse(); + .isFalse(); } @ConversionServiceTest @@ -100,9 +100,10 @@ class DelimitedStringToCollectionConverterTests { void matchesWhenHasAnnotationAndConvertibleElementTypeShouldReturnTrue() { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); + .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); assertThat(new DelimitedStringToCollectionConverter(new ApplicationConversionService()).matches(sourceType, - targetType)).isTrue(); + targetType)) + .isTrue(); } @Test @@ -110,7 +111,7 @@ class DelimitedStringToCollectionConverterTests { void convertWhenHasConvertibleElementTypeShouldReturnConvertedType() { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); + .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); List converted = (List) new ApplicationConversionService().convert(" 1 | 2| 3 ", sourceType, targetType); assertThat(converted).containsExactly(1, 2, 3); @@ -118,7 +119,7 @@ class DelimitedStringToCollectionConverterTests { static Stream conversionServices() { return ConversionServiceArguments - .with((service) -> service.addConverter(new DelimitedStringToCollectionConverter(service))); + .with((service) -> service.addConverter(new DelimitedStringToCollectionConverter(service))); } static class Values { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java index 213ee92fa4..66438a7f2f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ class DurationStyleTests { @Test void detectAndParseWhenValueIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.detectAndParse(null)) - .withMessageContaining("Value must not be null"); + .withMessageContaining("Value must not be null"); } @Test @@ -124,7 +124,7 @@ class DurationStyleTests { @Test void detectAndParseWhenBadFormatShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.detectAndParse("10foo")) - .withMessageContaining("'10foo' is not a valid duration"); + .withMessageContaining("'10foo' is not a valid duration"); } @Test @@ -159,7 +159,7 @@ class DurationStyleTests { @Test void detectWhenUnknownShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.detect("bad")) - .withMessageContaining("'bad' is not a valid duration"); + .withMessageContaining("'bad' is not a valid duration"); } @Test @@ -191,7 +191,7 @@ class DurationStyleTests { @Test void parseIso8601WhenSimpleShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.ISO8601.parse("10d")) - .withMessageContaining("'10d' is not a valid ISO-8601 duration"); + .withMessageContaining("'10d' is not a valid ISO-8601 duration"); } @Test @@ -208,13 +208,13 @@ class DurationStyleTests { @Test void parseSimpleWhenUnknownUnitShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.SIMPLE.parse("10mb")) - .satisfies((ex) -> assertThat(ex.getCause().getMessage()).isEqualTo("Unknown unit 'mb'")); + .satisfies((ex) -> assertThat(ex.getCause().getMessage()).isEqualTo("Unknown unit 'mb'")); } @Test void parseSimpleWhenIso8601ShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.SIMPLE.parse("PT10H")) - .withMessageContaining("'PT10H' is not a valid simple duration"); + .withMessageContaining("'PT10H' is not a valid simple duration"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java index 626b0eb375..6f57c1a1b2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,7 +58,7 @@ class InetAddressFormatterTests { String missingDomain = "ireallydontexist.example.com"; assumingThat(!isResolvable("ireallydontexist.example.com"), () -> assertThatExceptionOfType(ConversionFailedException.class) - .isThrownBy(() -> conversionService.convert(missingDomain, InetAddress.class))); + .isThrownBy(() -> conversionService.convert(missingDomain, InetAddress.class))); } private boolean isResolvable(String host) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InputStreamSourceToByteArrayConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InputStreamSourceToByteArrayConverterTests.java index d3683e9361..2fa4f6b2a1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InputStreamSourceToByteArrayConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InputStreamSourceToByteArrayConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,9 +53,9 @@ class InputStreamSourceToByteArrayConverterTests { InputStreamSource source = mock(InputStreamSource.class); given(source.getInputStream()).willThrow(IOException.class); assertThatExceptionOfType(ConversionFailedException.class) - .isThrownBy(() -> conversionService.convert(source, byte[].class)) - .withCauseExactlyInstanceOf(IllegalStateException.class) - .withMessageContaining("Unable to read from input stream source"); + .isThrownBy(() -> conversionService.convert(source, byte[].class)) + .withCauseExactlyInstanceOf(IllegalStateException.class) + .withMessageContaining("Unable to read from input stream source"); } @ConversionServiceTest @@ -66,9 +66,9 @@ class InputStreamSourceToByteArrayConverterTests { given(source.getInputStream()).willThrow(IOException.class); given(((OriginProvider) source).getOrigin()).willReturn(origin); assertThatExceptionOfType(ConversionFailedException.class) - .isThrownBy(() -> conversionService.convert(source, byte[].class)) - .withCauseExactlyInstanceOf(IllegalStateException.class) - .withMessageContaining("Unable to read from mylocation"); + .isThrownBy(() -> conversionService.convert(source, byte[].class)) + .withCauseExactlyInstanceOf(IllegalStateException.class) + .withMessageContaining("Unable to read from mylocation"); } @ConversionServiceTest @@ -78,14 +78,14 @@ class InputStreamSourceToByteArrayConverterTests { given(source.getInputStream()).willThrow(IOException.class); given(source.getDescription()).willReturn("myresource"); assertThatExceptionOfType(ConversionFailedException.class) - .isThrownBy(() -> conversionService.convert(source, byte[].class)) - .withCauseExactlyInstanceOf(IllegalStateException.class) - .withMessageContaining("Unable to read from myresource"); + .isThrownBy(() -> conversionService.convert(source, byte[].class)) + .withCauseExactlyInstanceOf(IllegalStateException.class) + .withMessageContaining("Unable to read from myresource"); } static Stream conversionServices() { return ConversionServiceArguments - .with((service) -> service.addConverter(new InputStreamSourceToByteArrayConverter())); + .with((service) -> service.addConverter(new InputStreamSourceToByteArrayConverter())); } private static class TestOrigin implements Origin { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/LenientBooleanToEnumConverterFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/LenientBooleanToEnumConverterFactoryTests.java index fadac100fd..1b69da57e8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/LenientBooleanToEnumConverterFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/LenientBooleanToEnumConverterFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ class LenientBooleanToEnumConverterFactoryTests { static Stream conversionServices() { return ConversionServiceArguments - .with((service) -> service.addConverterFactory(new LenientBooleanToEnumConverterFactory())); + .with((service) -> service.addConverterFactory(new LenientBooleanToEnumConverterFactory())); } enum TestOnOffEnum { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/LenientStringToEnumConverterFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/LenientStringToEnumConverterFactoryTests.java index 0d2b9b2d88..904fe1d719 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/LenientStringToEnumConverterFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/LenientStringToEnumConverterFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -94,7 +94,7 @@ class LenientStringToEnumConverterFactoryTests { static Stream conversionServices() { return ConversionServiceArguments - .with((service) -> service.addConverterFactory(new LenientStringToEnumConverterFactory())); + .with((service) -> service.addConverterFactory(new LenientStringToEnumConverterFactory())); } enum TestEnum { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockDurationTypeDescriptor.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockDurationTypeDescriptor.java index 41abeac07c..6cea88918d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockDurationTypeDescriptor.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockDurationTypeDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ public final class MockDurationTypeDescriptor { } if (style != null) { DurationFormat formatAnnotation = AnnotationUtils - .synthesizeAnnotation(Collections.singletonMap("value", style), DurationFormat.class, null); + .synthesizeAnnotation(Collections.singletonMap("value", style), DurationFormat.class, null); given(descriptor.getAnnotation(DurationFormat.class)).willReturn(formatAnnotation); } given(descriptor.getType()).willReturn((Class) Duration.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockPeriodTypeDescriptor.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockPeriodTypeDescriptor.java index 599adffe8a..815593a895 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockPeriodTypeDescriptor.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockPeriodTypeDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ public final class MockPeriodTypeDescriptor { } if (style != null) { PeriodFormat formatAnnotation = AnnotationUtils - .synthesizeAnnotation(Collections.singletonMap("value", style), PeriodFormat.class, null); + .synthesizeAnnotation(Collections.singletonMap("value", style), PeriodFormat.class, null); given(descriptor.getAnnotation(PeriodFormat.class)).willReturn(formatAnnotation); } given(descriptor.getType()).willReturn((Class) Period.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDataSizeConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDataSizeConverterTests.java index 15b3296efe..8f5ded746f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDataSizeConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDataSizeConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,7 +61,7 @@ class NumberToDataSizeConverterTests { TypeDescriptor targetType = mock(TypeDescriptor.class); if (defaultUnit != null) { DataSizeUnit unitAnnotation = AnnotationUtils - .synthesizeAnnotation(Collections.singletonMap("value", defaultUnit), DataSizeUnit.class, null); + .synthesizeAnnotation(Collections.singletonMap("value", defaultUnit), DataSizeUnit.class, null); given(targetType.getAnnotation(DataSizeUnit.class)).willReturn(unitAnnotation); } given(targetType.getType()).willReturn((Class) DataSize.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDurationConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDurationConverterTests.java index 1ed1ef9cc6..c1c8d517be 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDurationConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDurationConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,7 +61,7 @@ class NumberToDurationConverterTests { TypeDescriptor targetType = mock(TypeDescriptor.class); if (defaultUnit != null) { DurationUnit unitAnnotation = AnnotationUtils - .synthesizeAnnotation(Collections.singletonMap("value", defaultUnit), DurationUnit.class, null); + .synthesizeAnnotation(Collections.singletonMap("value", defaultUnit), DurationUnit.class, null); given(targetType.getAnnotation(DurationUnit.class)).willReturn(unitAnnotation); } given(targetType.getType()).willReturn((Class) Duration.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToPeriodConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToPeriodConverterTests.java index 169191f029..56ce68bdd3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToPeriodConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToPeriodConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,7 +67,7 @@ class NumberToPeriodConverterTests { TypeDescriptor targetType = mock(TypeDescriptor.class); if (defaultUnit != null) { PeriodUnit unitAnnotation = AnnotationUtils - .synthesizeAnnotation(Collections.singletonMap("value", defaultUnit), PeriodUnit.class, null); + .synthesizeAnnotation(Collections.singletonMap("value", defaultUnit), PeriodUnit.class, null); given(targetType.getAnnotation(PeriodUnit.class)).willReturn(unitAnnotation); } given(targetType.getType()).willReturn((Class) Period.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodStyleTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodStyleTests.java index 42cf7b6284..866557b9fe 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodStyleTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodStyleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ class PeriodStyleTests { @Test void detectAndParseWhenValueIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.detectAndParse(null)) - .withMessageContaining("Value must not be null"); + .withMessageContaining("Value must not be null"); } @Test @@ -109,7 +109,7 @@ class PeriodStyleTests { @Test void detectAndParseWhenBadFormatShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.detectAndParse("10foo")) - .withMessageContaining("'10foo' is not a valid period"); + .withMessageContaining("'10foo' is not a valid period"); } @Test @@ -138,7 +138,7 @@ class PeriodStyleTests { @Test void detectWhenUnknownShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.detect("bad")) - .withMessageContaining("'bad' is not a valid period"); + .withMessageContaining("'bad' is not a valid period"); } @Test @@ -168,7 +168,7 @@ class PeriodStyleTests { @Test void parseIso8601WhenSimpleShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.ISO8601.parse("10d")) - .withMessageContaining("'10d' is not a valid ISO-8601 period"); + .withMessageContaining("'10d' is not a valid ISO-8601 period"); } @Test @@ -184,14 +184,15 @@ class PeriodStyleTests { @Test void parseSimpleWhenUnknownUnitShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.SIMPLE.parse("10x")).satisfies( - (ex) -> assertThat(ex.getCause().getMessage()).isEqualTo("Does not match simple period pattern")); + assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.SIMPLE.parse("10x")) + .satisfies( + (ex) -> assertThat(ex.getCause().getMessage()).isEqualTo("Does not match simple period pattern")); } @Test void parseSimpleWhenIso8601ShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.SIMPLE.parse("PT10H")) - .withMessageContaining("'PT10H' is not a valid simple period"); + .withMessageContaining("'PT10H' is not a valid simple period"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java index 0855db899d..0dbb337e80 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -88,7 +88,7 @@ class StringToDataSizeConverterTests { @ConversionServiceTest void convertWhenBadFormatShouldThrowException(ConversionService conversionService) { assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> convert(conversionService, "10WB")) - .withMessageContaining("'10WB' is not a valid data size"); + .withMessageContaining("'10WB' is not a valid data size"); } @ConversionServiceTest diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java index ed64dbff7e..c23704e966 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -122,13 +122,13 @@ class StringToDurationConverterTests { @ConversionServiceTest void convertWhenBadFormatShouldThrowException(ConversionService conversionService) { assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> convert(conversionService, "10foo")) - .withMessageContaining("'10foo' is not a valid duration"); + .withMessageContaining("'10foo' is not a valid duration"); } @ConversionServiceTest void convertWhenStyleMismatchShouldThrowException(ConversionService conversionService) { assertThatExceptionOfType(ConversionFailedException.class) - .isThrownBy(() -> convert(conversionService, "10s", null, DurationStyle.ISO8601)); + .isThrownBy(() -> convert(conversionService, "10s", null, DurationStyle.ISO8601)); } @ConversionServiceTest diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToFileConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToFileConverterTests.java index a10dbbfedc..e053f15bc1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToFileConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToFileConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,13 +39,13 @@ class StringToFileConverterTests { @ConversionServiceTest void convertWhenSimpleFileReturnsFile(ConversionService conversionService) { assertThat(convert(conversionService, this.temp.getAbsolutePath() + "/test")) - .isEqualTo(new File(this.temp, "test").getAbsoluteFile()); + .isEqualTo(new File(this.temp, "test").getAbsoluteFile()); } @ConversionServiceTest void convertWhenFilePrefixedReturnsFile(ConversionService conversionService) { assertThat(convert(conversionService, "file:" + this.temp.getAbsolutePath() + "/test").getAbsoluteFile()) - .isEqualTo(new File(this.temp, "test").getAbsoluteFile()); + .isEqualTo(new File(this.temp, "test").getAbsoluteFile()); } private File convert(ConversionService conversionService, String source) { @@ -54,7 +54,7 @@ class StringToFileConverterTests { static Stream conversionServices() { return ConversionServiceArguments - .with((conversionService) -> conversionService.addConverter(new StringToFileConverter())); + .with((conversionService) -> conversionService.addConverter(new StringToFileConverter())); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/AbstractFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/AbstractFailureAnalyzerTests.java index de77ceec51..f055da41ab 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/AbstractFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/AbstractFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,14 +53,15 @@ class AbstractFailureAnalyzerTests { void findCauseWitNestedAndExactMatch() { TestException ex = new TestException(); assertThat(this.failureAnalyzer.findCause(new IllegalArgumentException(new IllegalStateException(ex)), - TestException.class)).isEqualTo(ex); + TestException.class)) + .isEqualTo(ex); } @Test void findCauseWitNestedAndSubClass() { SpecificTestException ex = new SpecificTestException(); assertThat(this.failureAnalyzer.findCause(new IOException(new IllegalStateException(ex)), TestException.class)) - .isEqualTo(ex); + .isEqualTo(ex); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java index a10da1d04f..2eaacf89f1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,8 @@ class FailureAnalyzersIntegrationTests { @Test void analysisIsPerformed(CapturedOutput output) { - assertThatExceptionOfType(Exception.class).isThrownBy( - () -> new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE).run()); + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE).run()); assertThat(output).contains("APPLICATION FAILED TO START"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java index ba6f4f6e5c..6c24467283 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,7 +58,7 @@ class BeanCurrentlyInCreationFailureAnalyzerTests { List lines = readDescriptionLines(analysis); assertThat(lines).hasSize(9); assertThat(lines.get(0)) - .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); + .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); assertThat(lines.get(1)).isEqualTo(""); assertThat(lines.get(2)).isEqualTo("┌─────┐"); assertThat(lines.get(3)).startsWith("| one defined in " + InnerInnerConfiguration.class.getName()); @@ -74,19 +74,19 @@ class BeanCurrentlyInCreationFailureAnalyzerTests { void cycleWithAutowiredFields() throws IOException { FailureAnalysis analysis = performAnalysis(CycleWithAutowiredFields.class); assertThat(analysis.getDescription()) - .startsWith("The dependencies of some of the beans in the application context form a cycle:"); + .startsWith("The dependencies of some of the beans in the application context form a cycle:"); List lines = readDescriptionLines(analysis); assertThat(lines).hasSize(9); assertThat(lines.get(0)) - .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); + .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); assertThat(lines.get(1)).isEqualTo(""); assertThat(lines.get(2)).isEqualTo("┌─────┐"); assertThat(lines.get(3)).startsWith("| three defined in " + BeanThreeConfiguration.class.getName()); assertThat(lines.get(4)).isEqualTo("↑ ↓"); assertThat(lines.get(5)).startsWith("| one defined in " + CycleWithAutowiredFields.class.getName()); assertThat(lines.get(6)).isEqualTo("↑ ↓"); - assertThat(lines.get(7)).startsWith( - "| " + BeanTwoConfiguration.class.getName() + " (field private " + BeanThree.class.getName()); + assertThat(lines.get(7)) + .startsWith("| " + BeanTwoConfiguration.class.getName() + " (field private " + BeanThree.class.getName()); assertThat(lines.get(8)).isEqualTo("└─────┘"); assertThat(analysis.getAction()).isNotNull(); } @@ -97,20 +97,20 @@ class BeanCurrentlyInCreationFailureAnalyzerTests { List lines = readDescriptionLines(analysis); assertThat(lines).hasSize(12); assertThat(lines.get(0)) - .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); + .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); assertThat(lines.get(1)).isEqualTo(""); assertThat(lines.get(2)).contains("refererOne (field " + RefererTwo.class.getName()); assertThat(lines.get(3)).isEqualTo(" ↓"); assertThat(lines.get(4)).contains("refererTwo (field " + BeanOne.class.getName()); assertThat(lines.get(5)).isEqualTo("┌─────┐"); assertThat(lines.get(6)) - .startsWith("| one defined in " + CycleReferencedViaOtherBeansConfiguration.class.getName()); + .startsWith("| one defined in " + CycleReferencedViaOtherBeansConfiguration.class.getName()); assertThat(lines.get(7)).isEqualTo("↑ ↓"); assertThat(lines.get(8)) - .startsWith("| two defined in " + CycleReferencedViaOtherBeansConfiguration.class.getName()); + .startsWith("| two defined in " + CycleReferencedViaOtherBeansConfiguration.class.getName()); assertThat(lines.get(9)).isEqualTo("↑ ↓"); assertThat(lines.get(10)) - .startsWith("| three defined in " + CycleReferencedViaOtherBeansConfiguration.class.getName()); + .startsWith("| three defined in " + CycleReferencedViaOtherBeansConfiguration.class.getName()); assertThat(lines.get(11)).isEqualTo("└─────┘"); assertThat(analysis.getAction()).isNotNull(); } @@ -121,7 +121,7 @@ class BeanCurrentlyInCreationFailureAnalyzerTests { List lines = readDescriptionLines(analysis); assertThat(lines).hasSize(5); assertThat(lines.get(0)) - .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); + .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); assertThat(lines.get(1)).isEqualTo(""); assertThat(lines.get(2)).isEqualTo("┌──->──┐"); assertThat(lines.get(3)).startsWith("| bean defined in " + SelfReferenceBeanConfiguration.class.getName()); @@ -166,7 +166,7 @@ class BeanCurrentlyInCreationFailureAnalyzerTests { try { this.context.register(configuration); AbstractAutowireCapableBeanFactory beanFactory = (AbstractAutowireCapableBeanFactory) this.context - .getBeanFactory(); + .getBeanFactory(); beanFactory.setAllowCircularReferences(allowCircularReferences); this.context.refresh(); fail("Expected failure did not occur"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzerTests.java index 4726c1275d..fea0c3df85 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,8 @@ class BeanDefinitionOverrideFailureAnalyzerTests { }); String description = analysis.getDescription(); assertThat(description) - .isEqualTo("The bean 'testBean' could not be registered. A bean with that name has already" - + " been defined and overriding is disabled."); + .isEqualTo("The bean 'testBean' could not be registered. A bean with that name has already" + + " been defined and overriding is disabled."); } private FailureAnalysis performAnalysis(Class configuration) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java index 39fa0d576b..f93bde1451 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,12 +46,12 @@ class BeanNotOfRequiredTypeFailureAnalyzerTests { FailureAnalysis analysis = performAnalysis(JdkProxyConfiguration.class); assertThat(analysis.getDescription()).startsWith("The bean 'asyncBean'"); assertThat(analysis.getDescription()) - .containsPattern("The bean is of type '" + AsyncBean.class.getPackage().getName() + ".\\$Proxy.*'"); + .containsPattern("The bean is of type '" + AsyncBean.class.getPackage().getName() + ".\\$Proxy.*'"); assertThat(analysis.getDescription()) - .contains(String.format("and implements:%n\t") + SomeInterface.class.getName()); + .contains(String.format("and implements:%n\t") + SomeInterface.class.getName()); assertThat(analysis.getDescription()).contains("Expected a bean of type '" + AsyncBean.class.getName() + "'"); assertThat(analysis.getDescription()) - .contains(String.format("which implements:%n\t") + SomeInterface.class.getName()); + .contains(String.format("which implements:%n\t") + SomeInterface.class.getName()); } private FailureAnalysis performAnalysis(Class configuration) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzerTests.java index 0bf0eb14bd..1e326608a1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,9 +42,9 @@ class InvalidConfigurationPropertyNameFailureAnalyzerTests { BeanCreationException failure = createFailure(InvalidPrefixConfiguration.class); FailureAnalysis analysis = this.analyzer.analyze(failure); assertThat(analysis.getDescription()) - .contains(String.format("%n Invalid characters: %s%n Bean: %s%n Reason: %s", "'F', 'P'", - "invalidPrefixProperties", "Canonical names should be kebab-case ('-' separated), " - + "lowercase alpha-numeric characters and must start with a letter")); + .contains(String.format("%n Invalid characters: %s%n Bean: %s%n Reason: %s", "'F', 'P'", + "invalidPrefixProperties", "Canonical names should be kebab-case ('-' separated), " + + "lowercase alpha-numeric characters and must start with a letter")); } private BeanCreationException createFailure(Class configuration) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzerTests.java index f8cf1a3e2b..6f8b468c7c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,7 +58,8 @@ class InvalidConfigurationPropertyValueFailureAnalyzerTests { assertCommonParts(failure, analysis); assertThat(analysis.getAction()).contains("Review the value of the property with the provided reason."); assertThat(analysis.getDescription()).contains("Validation failed for the following reason") - .contains("This is not valid.").doesNotContain("Additionally, this property is also set"); + .contains("This is not valid.") + .doesNotContain("Additionally, this property is also set"); } @Test @@ -70,7 +71,7 @@ class InvalidConfigurationPropertyValueFailureAnalyzerTests { FailureAnalysis analysis = performAnalysis(failure); assertThat(analysis.getAction()).contains("Review the value of the property."); assertThat(analysis.getDescription()).contains("No reason was provided.") - .doesNotContain("Additionally, this property is also set"); + .doesNotContain("Additionally, this property is also set"); } @Test @@ -88,9 +89,9 @@ class InvalidConfigurationPropertyValueFailureAnalyzerTests { assertCommonParts(failure, analysis); assertThat(analysis.getAction()).contains("Review the value of the property with the provided reason."); assertThat(analysis.getDescription()) - .contains("Additionally, this property is also set in the following property sources:") - .contains("In 'additional' with the value 'valid'") - .contains("In 'another' with the value 'test' (originating from 'TestOrigin test.property')"); + .contains("Additionally, this property is also set in the following property sources:") + .contains("In 'additional' with the value 'valid'") + .contains("In 'another' with the value 'test' (originating from 'TestOrigin test.property')"); } @Test @@ -101,8 +102,9 @@ class InvalidConfigurationPropertyValueFailureAnalyzerTests { } private void assertCommonParts(InvalidConfigurationPropertyValueException failure, FailureAnalysis analysis) { - assertThat(analysis.getDescription()).contains("test.property").contains("invalid") - .contains("TestOrigin test.property"); + assertThat(analysis.getDescription()).contains("test.property") + .contains("invalid") + .contains("TestOrigin test.property"); assertThat(analysis.getCause()).isSameAs(failure); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/JakartaApiValidationExceptionFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/JakartaApiValidationExceptionFailureAnalyzerTests.java index 0a54b31126..e09cf1c510 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/JakartaApiValidationExceptionFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/JakartaApiValidationExceptionFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,8 @@ class JakartaApiValidationExceptionFailureAnalyzerTests { @Test void validatedPropertiesTest() { assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> new AnnotationConfigApplicationContext(TestConfiguration.class).close()) - .satisfies((ex) -> assertThat(new ValidationExceptionFailureAnalyzer().analyze(ex)).isNotNull()); + .isThrownBy(() -> new AnnotationConfigApplicationContext(TestConfiguration.class).close()) + .satisfies((ex) -> assertThat(new ValidationExceptionFailureAnalyzer().analyze(ex)).isNotNull()); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/JavaxApiValidationExceptionFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/JavaxApiValidationExceptionFailureAnalyzerTests.java index a1fa0b7b42..9659d566aa 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/JavaxApiValidationExceptionFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/JavaxApiValidationExceptionFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,8 @@ class JavaxApiValidationExceptionFailureAnalyzerTests { @Test void validatedPropertiesTest() { assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> new AnnotationConfigApplicationContext(TestConfiguration.class).close()) - .satisfies((ex) -> assertThat(new ValidationExceptionFailureAnalyzer().analyze(ex)).isNotNull()); + .isThrownBy(() -> new AnnotationConfigApplicationContext(TestConfiguration.class).close()) + .satisfies((ex) -> assertThat(new ValidationExceptionFailureAnalyzer().analyze(ex)).isNotNull()); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/MutuallyExclusiveConfigurationPropertiesFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/MutuallyExclusiveConfigurationPropertiesFailureAnalyzerTests.java index a81645e36f..e53afa0e9b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/MutuallyExclusiveConfigurationPropertiesFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/MutuallyExclusiveConfigurationPropertiesFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,7 @@ class MutuallyExclusiveConfigurationPropertiesFailureAnalyzerTests { new HashSet<>(Arrays.asList("com.example.a", "com.example.b")), new HashSet<>(Arrays.asList("com.example.a", "com.example.b"))); FailureAnalysis failureAnalysis = new MutuallyExclusiveConfigurationPropertiesFailureAnalyzer(null) - .analyze(failure); + .analyze(failure); assertThat(failureAnalysis).isNull(); } @@ -81,10 +81,10 @@ class MutuallyExclusiveConfigurationPropertiesFailureAnalyzerTests { "Update your configuration so that only one of the mutually exclusive properties is configured."); assertThat(analysis.getDescription()).contains(String.format( "The following configuration properties are mutually exclusive:%n%n\tcom.example.a%n\tcom.example.b%n")) - .contains(String - .format("However, more than one of those properties has been configured at the same time:%n%n" - + "\tcom.example.a (originating from 'TestOrigin test')%n" - + "\tcom.example.b (originating from 'TestOrigin test')%n")); + .contains( + String.format("However, more than one of those properties has been configured at the same time:%n%n" + + "\tcom.example.a (originating from 'TestOrigin test')%n" + + "\tcom.example.b (originating from 'TestOrigin test')%n")); } @Test @@ -93,9 +93,9 @@ class MutuallyExclusiveConfigurationPropertiesFailureAnalyzerTests { properties.put("com.example.a", "alpha"); properties.put("com.example.b", "bravo"); this.environment.getPropertySources() - .addFirst(OriginCapablePropertySource.get(new MapPropertySource("test-one", properties))); + .addFirst(OriginCapablePropertySource.get(new MapPropertySource("test-one", properties))); this.environment.getPropertySources() - .addLast(OriginCapablePropertySource.get(new MapPropertySource("test-two", properties))); + .addLast(OriginCapablePropertySource.get(new MapPropertySource("test-two", properties))); MutuallyExclusiveConfigurationPropertiesException failure = new MutuallyExclusiveConfigurationPropertiesException( new HashSet<>(Arrays.asList("com.example.a", "com.example.b")), new HashSet<>(Arrays.asList("com.example.a", "com.example.b"))); @@ -104,12 +104,12 @@ class MutuallyExclusiveConfigurationPropertiesFailureAnalyzerTests { "Update your configuration so that only one of the mutually exclusive properties is configured."); assertThat(analysis.getDescription()).contains(String.format( "The following configuration properties are mutually exclusive:%n%n\tcom.example.a%n\tcom.example.b%n")) - .contains(String - .format("However, more than one of those properties has been configured at the same time:%n%n" - + "\tcom.example.a (originating from 'TestOrigin test-one')%n" - + "\tcom.example.a (originating from 'TestOrigin test-two')%n" - + "\tcom.example.b (originating from 'TestOrigin test-one')%n" - + "\tcom.example.b (originating from 'TestOrigin test-two')%n")); + .contains( + String.format("However, more than one of those properties has been configured at the same time:%n%n" + + "\tcom.example.a (originating from 'TestOrigin test-one')%n" + + "\tcom.example.a (originating from 'TestOrigin test-two')%n" + + "\tcom.example.b (originating from 'TestOrigin test-one')%n" + + "\tcom.example.b (originating from 'TestOrigin test-two')%n")); } private FailureAnalysis performAnalysis(MutuallyExclusiveConfigurationPropertiesException failure) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java index a185391c43..40bc98b37d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,8 @@ class NoSuchMethodFailureAnalyzerTests { + "Ljavax/servlet/ServletRegistration$Dynamic;"); assertThat(descriptor).isNotNull(); assertThat(descriptor.getErrorMessage()) - .isEqualTo("javax.servlet.ServletContext.addServlet(Ljava/lang/String;Ljavax/servlet/Servlet;)" - + "Ljavax/servlet/ServletRegistration$Dynamic;"); + .isEqualTo("javax.servlet.ServletContext.addServlet(Ljava/lang/String;Ljavax/servlet/Servlet;)" + + "Ljavax/servlet/ServletRegistration$Dynamic;"); assertThat(descriptor.getClassName()).isEqualTo("javax.servlet.ServletContext"); assertThat(descriptor.getCandidateLocations().size()).isGreaterThan(1); List typeHierarchy = descriptor.getTypeHierarchy(); @@ -66,8 +66,8 @@ class NoSuchMethodFailureAnalyzerTests { + "Ljavax/servlet/ServletRegistration$Dynamic; (loaded from file..."); assertThat(descriptor).isNotNull(); assertThat(descriptor.getErrorMessage()) - .isEqualTo("javax/servlet/ServletContext.addServlet(Ljava/lang/String;Ljavax/servlet/Servlet;)" - + "Ljavax/servlet/ServletRegistration$Dynamic;"); + .isEqualTo("javax/servlet/ServletContext.addServlet(Ljava/lang/String;Ljavax/servlet/Servlet;)" + + "Ljavax/servlet/ServletRegistration$Dynamic;"); assertThat(descriptor.getClassName()).isEqualTo("javax.servlet.ServletContext"); assertThat(descriptor.getCandidateLocations().size()).isGreaterThan(1); List typeHierarchy = descriptor.getTypeHierarchy(); @@ -82,8 +82,8 @@ class NoSuchMethodFailureAnalyzerTests { + "java.lang.String, javax.servlet.Servlet)'"); assertThat(descriptor).isNotNull(); assertThat(descriptor.getErrorMessage()) - .isEqualTo("'javax.servlet.ServletRegistration$Dynamic javax.servlet.ServletContext.addServlet(" - + "java.lang.String, javax.servlet.Servlet)'"); + .isEqualTo("'javax.servlet.ServletRegistration$Dynamic javax.servlet.ServletContext.addServlet(" + + "java.lang.String, javax.servlet.Servlet)'"); assertThat(descriptor.getClassName()).isEqualTo("javax.servlet.ServletContext"); assertThat(descriptor.getCandidateLocations().size()).isGreaterThan(1); List typeHierarchy = descriptor.getTypeHierarchy(); @@ -98,11 +98,12 @@ class NoSuchMethodFailureAnalyzerTests { FailureAnalysis analysis = new NoSuchMethodFailureAnalyzer().analyze(failure); assertThat(analysis).isNotNull(); assertThat(analysis.getDescription()) - .contains(NoSuchMethodFailureAnalyzerTests.class.getName() + ".createFailure(").contains("addServlet(") - .contains("calling method's class, " + NoSuchMethodFailureAnalyzerTests.class.getName() + ",") - .contains("called method's class, javax.servlet.ServletContext,"); + .contains(NoSuchMethodFailureAnalyzerTests.class.getName() + ".createFailure(") + .contains("addServlet(") + .contains("calling method's class, " + NoSuchMethodFailureAnalyzerTests.class.getName() + ",") + .contains("called method's class, javax.servlet.ServletContext,"); assertThat(analysis.getAction()).contains(NoSuchMethodFailureAnalyzerTests.class.getName()) - .contains("javax.servlet.ServletContext"); + .contains("javax.servlet.ServletContext"); } @Test @@ -112,12 +113,12 @@ class NoSuchMethodFailureAnalyzerTests { FailureAnalysis analysis = new NoSuchMethodFailureAnalyzer().analyze(failure); assertThat(analysis).isNotNull(); assertThat(analysis.getDescription()).contains(R2dbcMappingContext.class.getName() + ".(") - .contains(R2dbcMappingContext.class.getName() + ".setForceQuote(") - .contains("calling method's class, org.springframework.data.r2dbc.mapping.R2dbcMappingContext,") - .contains("called method's class, org.springframework.data.r2dbc.mapping.R2dbcMappingContext,") - .contains(" org.springframework.data.r2dbc.mapping.R2dbcMappingContext") - .contains(" org.springframework.data.relational.core.mapping.RelationalMappingContext") - .contains(" org.springframework.data.mapping.context.AbstractMappingContext"); + .contains(R2dbcMappingContext.class.getName() + ".setForceQuote(") + .contains("calling method's class, org.springframework.data.r2dbc.mapping.R2dbcMappingContext,") + .contains("called method's class, org.springframework.data.r2dbc.mapping.R2dbcMappingContext,") + .contains(" org.springframework.data.r2dbc.mapping.R2dbcMappingContext") + .contains(" org.springframework.data.relational.core.mapping.RelationalMappingContext") + .contains(" org.springframework.data.mapping.context.AbstractMappingContext"); assertThat(analysis.getAction()).contains("org.springframework.data.r2dbc.mapping.R2dbcMappingContext"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java index 3950d03607..35943e7ccf 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java @@ -113,9 +113,9 @@ class NoUniqueBeanDefinitionFailureAnalyzerTests { private void assertFoundBeans(FailureAnalysis analysis) { assertThat(analysis.getDescription()).contains("beanOne: defined in unknown location"); assertThat(analysis.getDescription()) - .contains("beanTwo: defined by method 'beanTwo' in " + DuplicateBeansProducer.class.getName()); + .contains("beanTwo: defined by method 'beanTwo' in " + DuplicateBeansProducer.class.getName()); assertThat(analysis.getDescription()) - .contains("beanThree: defined by method 'beanThree' in " + ParentProducer.class.getName()); + .contains("beanThree: defined by method 'beanThree' in " + ParentProducer.class.getName()); assertThat(analysis.getDescription()).contains("barTestBean"); assertThat(analysis.getDescription()).contains("fooTestBean"); assertThat(analysis.getDescription()).contains("xmlTestBean"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/PatternParseFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/PatternParseFailureAnalyzerTests.java index 8bcdd0e512..01bcf7f9dc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/PatternParseFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/PatternParseFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,8 @@ class PatternParseFailureAnalyzerTests { FailureAnalysis failureAnalysis = performAnalysis("/spring/**/framework"); assertThat(failureAnalysis.getDescription()).contains("Invalid mapping pattern detected: /spring/**/framework"); assertThat(failureAnalysis.getAction()) - .contains("Fix this pattern in your application or switch to the legacy parser" - + " implementation with 'spring.mvc.pathmatch.matching-strategy=ant_path_matcher'."); + .contains("Fix this pattern in your application or switch to the legacy parser" + + " implementation with 'spring.mvc.pathmatch.matching-strategy=ant_path_matcher'."); } private FailureAnalysis performAnalysis(String pattern) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/ConfigTreePropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/ConfigTreePropertySourceTests.java index a8660b9445..f880e5a206 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/ConfigTreePropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/ConfigTreePropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,20 +52,20 @@ class ConfigTreePropertySourceTests { @Test void createWhenNameIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigTreePropertySource(null, this.directory)) - .withMessageContaining("name must contain"); + .withMessageContaining("name must contain"); } @Test void createWhenSourceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigTreePropertySource("test", null)) - .withMessage("Property source must not be null"); + .withMessage("Property source must not be null"); } @Test void createWhenSourceDoesNotExistThrowsException() { Path missing = this.directory.resolve("missing"); assertThatIllegalArgumentException().isThrownBy(() -> new ConfigTreePropertySource("test", missing)) - .withMessage("Directory '" + missing + "' does not exist"); + .withMessage("Directory '" + missing + "' does not exist"); } @Test @@ -73,7 +73,7 @@ class ConfigTreePropertySourceTests { Path file = this.directory.resolve("file"); FileCopyUtils.copy("test".getBytes(StandardCharsets.UTF_8), file.toFile()); assertThatIllegalArgumentException().isThrownBy(() -> new ConfigTreePropertySource("test", file)) - .withMessage("File '" + file + "' is not a directory"); + .withMessage("File '" + file + "' is not a directory"); } @Test @@ -135,7 +135,7 @@ class ConfigTreePropertySourceTests { Path b = this.directory.resolve("b"); Files.delete(b); assertThatIllegalStateException().isThrownBy(() -> propertySource.getProperty("b").toString()) - .withMessage("The property file '" + b + "' no longer exists"); + .withMessage("The property file '" + b + "' no longer exists"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/EnvironmentPostProcessorsFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/EnvironmentPostProcessorsFactoryTests.java index 7682491b8f..6398bab321 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/EnvironmentPostProcessorsFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/EnvironmentPostProcessorsFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,7 @@ class EnvironmentPostProcessorsFactoryTests { @Test void ofClassesReturnsFactory() { EnvironmentPostProcessorsFactory factory = EnvironmentPostProcessorsFactory - .of(TestEnvironmentPostProcessor.class); + .of(TestEnvironmentPostProcessor.class); List processors = factory.getEnvironmentPostProcessors(this.logFactory, this.bootstrapContext); assertThat(processors).hasSize(1); @@ -61,7 +61,7 @@ class EnvironmentPostProcessorsFactoryTests { @Test void ofClassNamesReturnsFactory() { EnvironmentPostProcessorsFactory factory = EnvironmentPostProcessorsFactory - .of(TestEnvironmentPostProcessor.class.getName()); + .of(TestEnvironmentPostProcessor.class.getName()); List processors = factory.getEnvironmentPostProcessors(this.logFactory, this.bootstrapContext); assertThat(processors).hasSize(1); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java index 4192448c46..d042336804 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ class NoSnakeYamlPropertySourceLoaderTests { void load() { ByteArrayResource resource = new ByteArrayResource("foo:\n bar: spam".getBytes()); assertThatIllegalStateException().isThrownBy(() -> this.loader.load("resource", resource)) - .withMessageContaining("Attempted to load resource but snakeyaml was not found on the classpath"); + .withMessageContaining("Attempted to load resource but snakeyaml was not found on the classpath"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java index 5a591c4de2..6ab40ce486 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,8 +56,10 @@ class OriginTrackedPropertiesLoaderTests { void compareToJavaProperties() throws Exception { Properties java = PropertiesLoaderUtils.loadProperties(this.resource); Properties ours = new Properties(); - new OriginTrackedPropertiesLoader(this.resource).load(false).get(0).asMap() - .forEach((k, v) -> ours.put(k, v.getValue())); + new OriginTrackedPropertiesLoader(this.resource).load(false) + .get(0) + .asMap() + .forEach((k, v) -> ours.put(k, v.getValue())); assertThat(ours).isEqualTo(java); } @@ -94,7 +96,7 @@ class OriginTrackedPropertiesLoaderTests { // gh-12716 ClassPathResource resource = new ClassPathResource("test-properties-malformed-unicode.properties", getClass()); assertThatIllegalStateException().isThrownBy(() -> new OriginTrackedPropertiesLoader(resource).load()) - .withMessageContaining("Malformed \\uxxxx encoding"); + .withMessageContaining("Malformed \\uxxxx encoding"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/RandomValuePropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/RandomValuePropertySourceTests.java index 9df913875c..244b893f52 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/RandomValuePropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/RandomValuePropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,7 +76,7 @@ class RandomValuePropertySourceTests { @Test void intRangeWhenLowerBoundEqualsUpperBoundShouldFailWithIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.source.getProperty("random.int[4,4]")) - .withMessage("Lower bound must be less than upper bound."); + .withMessage("Lower bound must be less than upper bound."); } @Test @@ -95,13 +95,13 @@ class RandomValuePropertySourceTests { @Test void intMaxZero() { assertThatIllegalArgumentException().isThrownBy(() -> this.source.getProperty("random.int(0)")) - .withMessage("Bound must be positive."); + .withMessage("Bound must be positive."); } @Test void intNegativeBound() { assertThatIllegalArgumentException().isThrownBy(() -> this.source.getProperty("random.int(-5)")) - .withMessage("Bound must be positive."); + .withMessage("Bound must be positive."); } @Test @@ -119,7 +119,7 @@ class RandomValuePropertySourceTests { @Test void longRangeWhenLowerBoundEqualsUpperBoundShouldFailWithIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.source.getProperty("random.long[4,4]")) - .withMessage("Lower bound must be less than upper bound."); + .withMessage("Lower bound must be less than upper bound."); } @Test @@ -138,13 +138,13 @@ class RandomValuePropertySourceTests { @Test void longMaxZero() { assertThatIllegalArgumentException().isThrownBy(() -> this.source.getProperty("random.long(0)")) - .withMessage("Bound must be positive."); + .withMessage("Bound must be positive."); } @Test void longNegativeBound() { assertThatIllegalArgumentException().isThrownBy(() -> this.source.getProperty("random.long(-5)")) - .withMessage("Bound must be positive."); + .withMessage("Bound must be positive."); } @Test @@ -183,8 +183,9 @@ class RandomValuePropertySourceTests { @Test void addToEnvironmentAddsAfterSystemEnvironment() { MockEnvironment environment = new MockEnvironment(); - environment.getPropertySources().addFirst(new SystemEnvironmentPropertySource( - StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, Collections.emptyMap())); + environment.getPropertySources() + .addFirst(new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, + Collections.emptyMap())); RandomValuePropertySource.addToEnvironment(environment); assertThat(environment.getPropertySources().stream().map(PropertySource::getName)).containsExactly( StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/ReflectionEnvironmentPostProcessorsFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/ReflectionEnvironmentPostProcessorsFactoryTests.java index 982224626f..88b319cac7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/ReflectionEnvironmentPostProcessorsFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/ReflectionEnvironmentPostProcessorsFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -115,8 +115,8 @@ class ReflectionEnvironmentPostProcessorsFactoryTests { ReflectionEnvironmentPostProcessorsFactory factory = new ReflectionEnvironmentPostProcessorsFactory(null, BadEnvironmentPostProcessor.class.getName()); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.getEnvironmentPostProcessors(this.logFactory, this.bootstrapContext)) - .withMessageContaining("Unable to instantiate"); + .isThrownBy(() -> factory.getEnvironmentPostProcessors(this.logFactory, this.bootstrapContext)) + .withMessageContaining("Unable to instantiate"); } private EnvironmentPostProcessorsFactoryAssert assertThatFactory(EnvironmentPostProcessorsFactory factory) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java index 0f9178d357..c48c460a15 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,8 +53,8 @@ class SpringApplicationJsonEnvironmentPostProcessorTests { assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.application.json=foo:bar"); assertThatExceptionOfType(JsonParseException.class) - .isThrownBy(() -> this.processor.postProcessEnvironment(this.environment, null)) - .withMessageContaining("Cannot parse JSON"); + .isThrownBy(() -> this.processor.postProcessEnvironment(this.environment, null)) + .withMessageContaining("Cannot parse JSON"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessorTests.java index 5b29b01970..d90884c9ab 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +57,8 @@ class SystemEnvironmentPropertySourceEnvironmentPostProcessorTests { PropertySource original = this.environment.getPropertySources().get("systemEnvironment"); postProcessor.postProcessEnvironment(this.environment, this.application); OriginAwareSystemEnvironmentPropertySource replaced = (OriginAwareSystemEnvironmentPropertySource) this.environment - .getPropertySources().get("systemEnvironment"); + .getPropertySources() + .get("systemEnvironment"); Map originalMap = (Map) original.getSource(); Map replacedMap = replaced.getSource(); originalMap.forEach((key, value) -> { @@ -72,7 +73,8 @@ class SystemEnvironmentPropertySourceEnvironmentPostProcessorTests { SystemEnvironmentPropertySourceEnvironmentPostProcessor postProcessor = new SystemEnvironmentPropertySourceEnvironmentPostProcessor(); postProcessor.postProcessEnvironment(this.environment, this.application); OriginAwareSystemEnvironmentPropertySource replaced = (OriginAwareSystemEnvironmentPropertySource) this.environment - .getPropertySources().get("systemEnvironment"); + .getPropertySources() + .get("systemEnvironment"); assertThat(replaced.getOrigin("NON_EXISTENT")).isNull(); } @@ -80,11 +82,12 @@ class SystemEnvironmentPropertySourceEnvironmentPostProcessorTests { void replacedPropertySourceShouldResolveProperty() { SystemEnvironmentPropertySourceEnvironmentPostProcessor postProcessor = new SystemEnvironmentPropertySourceEnvironmentPostProcessor(); Map source = Collections.singletonMap("FOO_BAR_BAZ", "hello"); - this.environment.getPropertySources().replace("systemEnvironment", - new SystemEnvironmentPropertySource("systemEnvironment", source)); + this.environment.getPropertySources() + .replace("systemEnvironment", new SystemEnvironmentPropertySource("systemEnvironment", source)); postProcessor.postProcessEnvironment(this.environment, this.application); OriginAwareSystemEnvironmentPropertySource replaced = (OriginAwareSystemEnvironmentPropertySource) this.environment - .getPropertySources().get("systemEnvironment"); + .getPropertySources() + .get("systemEnvironment"); SystemEnvironmentOrigin origin = (SystemEnvironmentOrigin) replaced.getOrigin("foo.bar.baz"); assertThat(origin.getProperty()).isEqualTo("FOO_BAR_BAZ"); assertThat(replaced.getProperty("foo.bar.baz")).isEqualTo("hello"); @@ -97,7 +100,8 @@ class SystemEnvironmentPropertySourceEnvironmentPostProcessorTests { application.setEnvironmentPrefix("my"); postProcessor.postProcessEnvironment(this.environment, application); OriginAwareSystemEnvironmentPropertySource replaced = (OriginAwareSystemEnvironmentPropertySource) this.environment - .getPropertySources().get("systemEnvironment"); + .getPropertySources() + .get("systemEnvironment"); assertThat(replaced.getPrefix()).isEqualTo("my"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java index 16d10379a4..ab959cf552 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,7 +59,7 @@ class YamlPropertySourceLoaderTests { } ByteArrayResource resource = new ByteArrayResource(yaml.toString().getBytes()); EnumerablePropertySource source = (EnumerablePropertySource) this.loader.load("resource", resource) - .get(0); + .get(0); assertThat(source).isNotNull(); assertThat(source.getPropertyNames()).isEqualTo(StringUtils.toStringArray(expected)); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java index 11ffa101a0..5757304af1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -146,7 +146,7 @@ class JsonComponentModuleTests { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(module); assertThatExceptionOfType(JsonMappingException.class) - .isThrownBy(() -> mapper.readValue("{\"name\":\"spring\",\"age\":100}", NameAndAge.class)); + .isThrownBy(() -> mapper.readValue("{\"name\":\"spring\",\"age\":100}", NameAndAge.class)); NameAndCareer nameAndCareer = mapper.readValue("{\"name\":\"spring\",\"career\":\"developer\"}", NameAndCareer.class); assertThat(nameAndCareer.getName()).isEqualTo("spring"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonMixinModuleTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonMixinModuleTests.java index 7b4bc40931..bbf7e5dda9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonMixinModuleTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonMixinModuleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +57,7 @@ class JsonMixinModuleTests { @Test void createWhenContextIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new JsonMixinModule(null, Collections.emptyList())) - .withMessageContaining("Context must not be null"); + .withMessageContaining("Context must not be null"); } @Test @@ -92,8 +92,9 @@ class JsonMixinModuleTests { private void load(Class... basePackageClasses) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - List basePackages = Arrays.stream(basePackageClasses).map(ClassUtils::getPackageName) - .collect(Collectors.toList()); + List basePackages = Arrays.stream(basePackageClasses) + .map(ClassUtils::getPackageName) + .collect(Collectors.toList()); context.registerBean(JsonMixinModule.class, () -> new JsonMixinModule(context, basePackages)); context.refresh(); this.context = context; diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java index b680ce4310..99fbb67573 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,8 +68,8 @@ class JsonObjectDeserializerTests { @Test void nullSafeValueWhenClassIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.testDeserializer.testNullSafeValue(mock(JsonNode.class), null)) - .withMessageContaining("Type must not be null"); + .isThrownBy(() -> this.testDeserializer.testNullSafeValue(mock(JsonNode.class), null)) + .withMessageContaining("Type must not be null"); } @Test @@ -147,15 +147,15 @@ class JsonObjectDeserializerTests { @Test void nullSafeValueWhenClassIsUnknownShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.testDeserializer.testNullSafeValue(mock(JsonNode.class), InputStream.class)) - .withMessageContaining("Unsupported value type java.io.InputStream"); + .isThrownBy(() -> this.testDeserializer.testNullSafeValue(mock(JsonNode.class), InputStream.class)) + .withMessageContaining("Unsupported value type java.io.InputStream"); } @Test void getRequiredNodeWhenTreeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.testDeserializer.testGetRequiredNode(null, "test")) - .withMessageContaining("Tree must not be null"); + .withMessageContaining("Tree must not be null"); } @Test @@ -163,7 +163,7 @@ class JsonObjectDeserializerTests { JsonNode tree = mock(JsonNode.class); given(tree.get("test")).willReturn(null); assertThatIllegalStateException().isThrownBy(() -> this.testDeserializer.testGetRequiredNode(tree, "test")) - .withMessageContaining("Missing JSON field 'test'"); + .withMessageContaining("Missing JSON field 'test'"); } @Test @@ -171,7 +171,7 @@ class JsonObjectDeserializerTests { JsonNode tree = mock(JsonNode.class); given(tree.get("test")).willReturn(NullNode.instance); assertThatIllegalStateException().isThrownBy(() -> this.testDeserializer.testGetRequiredNode(tree, "test")) - .withMessageContaining("Missing JSON field 'test'"); + .withMessageContaining("Missing JSON field 'test'"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/AbstractDataSourceInitializerDependencyConfigurationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/AbstractDataSourceInitializerDependencyConfigurationTests.java index 474bec0266..eece623165 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/AbstractDataSourceInitializerDependencyConfigurationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/AbstractDataSourceInitializerDependencyConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,10 +43,12 @@ class AbstractDataSourceInitializerDependencyConfigurationTests { void beansThatDependOnDatabaseInitializationDependOnAbstractDataSourceInitializerBeans() { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( TestConfiguration.class)) { - assertThat(context.getBeanFactory().getBeanDefinition("factoryMethodDependsOnDatabaseInitialization") - .getDependsOn()).contains("initializer"); - assertThat(context.getBeanFactory().getBeanDefinition("beanClassDependsOnDatabaseInitialization") - .getDependsOn()).contains("initializer"); + assertThat(context.getBeanFactory() + .getBeanDefinition("factoryMethodDependsOnDatabaseInitialization") + .getDependsOn()).contains("initializer"); + assertThat(context.getBeanFactory() + .getBeanDefinition("beanClassDependsOnDatabaseInitialization") + .getDependsOn()).contains("initializer"); } } 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 442c852202..3c859d10e3 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-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -86,38 +86,49 @@ class DataSourceBuilderTests { @Test void buildWhenHikariNotAvailableReturnsTomcatDataSource() { - this.dataSource = DataSourceBuilder.create(new HidePackagesClassLoader("com.zaxxer.hikari")).url("jdbc:h2:test") - .build(); + this.dataSource = DataSourceBuilder.create(new HidePackagesClassLoader("com.zaxxer.hikari")) + .url("jdbc:h2:test") + .build(); assertThat(this.dataSource).isInstanceOf(org.apache.tomcat.jdbc.pool.DataSource.class); } @Test // gh-26633 void buildWhenTomcatDataSourceWithNullPasswordReturnsDataSource() { - this.dataSource = DataSourceBuilder.create(new HidePackagesClassLoader("com.zaxxer.hikari")).url("jdbc:h2:test") - .username("test").password(null).build(); + this.dataSource = DataSourceBuilder.create(new HidePackagesClassLoader("com.zaxxer.hikari")) + .url("jdbc:h2:test") + .username("test") + .password(null) + .build(); assertThat(this.dataSource).isInstanceOf(org.apache.tomcat.jdbc.pool.DataSource.class); } @Test void buildWhenHikariAndTomcatNotAvailableReturnsDbcp2DataSource() { this.dataSource = DataSourceBuilder - .create(new HidePackagesClassLoader("com.zaxxer.hikari", "org.apache.tomcat.jdbc.pool")) - .url("jdbc:h2:test").build(); + .create(new HidePackagesClassLoader("com.zaxxer.hikari", "org.apache.tomcat.jdbc.pool")) + .url("jdbc:h2:test") + .build(); assertThat(this.dataSource).isInstanceOf(BasicDataSource.class); } @Test // gh-26633 void buildWhenDbcp2DataSourceWithNullPasswordReturnsDbcp2DataSource() { this.dataSource = DataSourceBuilder - .create(new HidePackagesClassLoader("com.zaxxer.hikari", "org.apache.tomcat.jdbc.pool")) - .url("jdbc:h2:test").username("test").password(null).build(); + .create(new HidePackagesClassLoader("com.zaxxer.hikari", "org.apache.tomcat.jdbc.pool")) + .url("jdbc:h2:test") + .username("test") + .password(null) + .build(); assertThat(this.dataSource).isInstanceOf(BasicDataSource.class); } @Test void buildWhenHikariAndTomcatAndDbcpNotAvailableReturnsOracleUcpDataSource() { - this.dataSource = DataSourceBuilder.create(new HidePackagesClassLoader("com.zaxxer.hikari", - "org.apache.tomcat.jdbc.pool", "org.apache.commons.dbcp2")).url("jdbc:h2:test").build(); + this.dataSource = DataSourceBuilder + .create(new HidePackagesClassLoader("com.zaxxer.hikari", "org.apache.tomcat.jdbc.pool", + "org.apache.commons.dbcp2")) + .url("jdbc:h2:test") + .build(); assertThat(this.dataSource).isInstanceOf(PoolDataSourceImpl.class); } @@ -138,8 +149,11 @@ class DataSourceBuilderTests { @Test void buildWhenOracleTypeSpecifiedReturnsExpectedDataSource() throws SQLException { - this.dataSource = DataSourceBuilder.create().url("jdbc:oracle:thin:@localhost:1521:xe") - .type(OracleDataSource.class).username("test").build(); + this.dataSource = DataSourceBuilder.create() + .url("jdbc:oracle:thin:@localhost:1521:xe") + .type(OracleDataSource.class) + .username("test") + .build(); assertThat(this.dataSource).isInstanceOf(OracleDataSource.class); OracleDataSource oracleDataSource = (OracleDataSource) this.dataSource; assertThat(oracleDataSource.getURL()).isEqualTo("jdbc:oracle:thin:@localhost:1521:xe"); @@ -148,9 +162,12 @@ class DataSourceBuilderTests { @Test // gh-26631 void buildWhenOracleTypeSpecifiedWithDriverClassReturnsExpectedDataSource() throws SQLException { - this.dataSource = DataSourceBuilder.create().url("jdbc:oracle:thin:@localhost:1521:xe") - .type(OracleDataSource.class).driverClassName("oracle.jdbc.pool.OracleDataSource").username("test") - .build(); + this.dataSource = DataSourceBuilder.create() + .url("jdbc:oracle:thin:@localhost:1521:xe") + .type(OracleDataSource.class) + .driverClassName("oracle.jdbc.pool.OracleDataSource") + .username("test") + .build(); assertThat(this.dataSource).isInstanceOf(OracleDataSource.class); OracleDataSource oracleDataSource = (OracleDataSource) this.dataSource; assertThat(oracleDataSource.getURL()).isEqualTo("jdbc:oracle:thin:@localhost:1521:xe"); @@ -159,8 +176,11 @@ class DataSourceBuilderTests { @Test void buildWhenOracleUcpTypeSpecifiedReturnsExpectedDataSource() { - this.dataSource = DataSourceBuilder.create().driverClassName("org.hsqldb.jdbc.JDBCDriver") - .type(PoolDataSourceImpl.class).username("test").build(); + this.dataSource = DataSourceBuilder.create() + .driverClassName("org.hsqldb.jdbc.JDBCDriver") + .type(PoolDataSourceImpl.class) + .username("test") + .build(); assertThat(this.dataSource).isInstanceOf(PoolDataSourceImpl.class); PoolDataSourceImpl upcDataSource = (PoolDataSourceImpl) this.dataSource; assertThat(upcDataSource.getConnectionFactoryClassName()).isEqualTo("org.hsqldb.jdbc.JDBCDriver"); @@ -169,8 +189,12 @@ class DataSourceBuilderTests { @Test void buildWhenH2TypeSpecifiedReturnsExpectedDataSource() { - this.dataSource = DataSourceBuilder.create().url("jdbc:h2:test").type(JdbcDataSource.class).username("test") - .password("secret").build(); + this.dataSource = DataSourceBuilder.create() + .url("jdbc:h2:test") + .type(JdbcDataSource.class) + .username("test") + .password("secret") + .build(); assertThat(this.dataSource).isInstanceOf(JdbcDataSource.class); JdbcDataSource h2DataSource = (JdbcDataSource) this.dataSource; assertThat(h2DataSource.getUser()).isEqualTo("test"); @@ -179,8 +203,13 @@ class DataSourceBuilderTests { @Test // gh-26631 void buildWhenH2TypeSpecifiedWithDriverClassReturnsExpectedDataSource() { - this.dataSource = DataSourceBuilder.create().url("jdbc:h2:test").type(JdbcDataSource.class) - .driverClassName("org.h2.jdbcx.JdbcDataSource").username("test").password("secret").build(); + this.dataSource = DataSourceBuilder.create() + .url("jdbc:h2:test") + .type(JdbcDataSource.class) + .driverClassName("org.h2.jdbcx.JdbcDataSource") + .username("test") + .password("secret") + .build(); assertThat(this.dataSource).isInstanceOf(JdbcDataSource.class); JdbcDataSource h2DataSource = (JdbcDataSource) this.dataSource; assertThat(h2DataSource.getUser()).isEqualTo("test"); @@ -189,8 +218,11 @@ class DataSourceBuilderTests { @Test void buildWhenPostgresTypeSpecifiedReturnsExpectedDataSource() { - this.dataSource = DataSourceBuilder.create().url("jdbc:postgresql://localhost/test") - .type(PGSimpleDataSource.class).username("test").build(); + this.dataSource = DataSourceBuilder.create() + .url("jdbc:postgresql://localhost/test") + .type(PGSimpleDataSource.class) + .username("test") + .build(); assertThat(this.dataSource).isInstanceOf(PGSimpleDataSource.class); PGSimpleDataSource pgDataSource = (PGSimpleDataSource) this.dataSource; assertThat(pgDataSource.getUser()).isEqualTo("test"); @@ -198,9 +230,12 @@ class DataSourceBuilderTests { @Test // gh-26631 void buildWhenPostgresTypeSpecifiedWithDriverClassReturnsExpectedDataSource() { - this.dataSource = DataSourceBuilder.create().url("jdbc:postgresql://localhost/test") - .type(PGSimpleDataSource.class).driverClassName("org.postgresql.ds.PGSimpleDataSource").username("test") - .build(); + this.dataSource = DataSourceBuilder.create() + .url("jdbc:postgresql://localhost/test") + .type(PGSimpleDataSource.class) + .driverClassName("org.postgresql.ds.PGSimpleDataSource") + .username("test") + .build(); assertThat(this.dataSource).isInstanceOf(PGSimpleDataSource.class); PGSimpleDataSource pgDataSource = (PGSimpleDataSource) this.dataSource; assertThat(pgDataSource.getUser()).isEqualTo("test"); @@ -208,8 +243,11 @@ class DataSourceBuilderTests { @Test // gh-26647 void buildWhenSqlServerTypeSpecifiedReturnsExpectedDataSource() { - this.dataSource = DataSourceBuilder.create().url("jdbc:sqlserver://localhost/test") - .type(SQLServerDataSource.class).username("test").build(); + this.dataSource = DataSourceBuilder.create() + .url("jdbc:sqlserver://localhost/test") + .type(SQLServerDataSource.class) + .username("test") + .build(); assertThat(this.dataSource).isInstanceOf(SQLServerDataSource.class); SQLServerDataSource sqlServerDataSource = (SQLServerDataSource) this.dataSource; assertThat(sqlServerDataSource.getUser()).isEqualTo("test"); @@ -223,8 +261,11 @@ class DataSourceBuilderTests { @Test void buildWhenCustomSubclassTypeSpecifiedReturnsDataSourceWithOnlyBasePropertiesSet() { - this.dataSource = DataSourceBuilder.create().url("jdbc:h2:test").type(CustomTomcatDataSource.class) - .username("test").build(); + this.dataSource = DataSourceBuilder.create() + .url("jdbc:h2:test") + .type(CustomTomcatDataSource.class) + .username("test") + .build(); assertThat(this.dataSource).isInstanceOf(CustomTomcatDataSource.class); CustomTomcatDataSource testDataSource = (CustomTomcatDataSource) this.dataSource; assertThat(testDataSource.getUrl()).isEqualTo("jdbc:h2:test"); @@ -237,8 +278,13 @@ class DataSourceBuilderTests { @Test void buildWhenCustomTypeSpecifiedReturnsDataSourceWithPropertiesSetViaReflection() { - this.dataSource = DataSourceBuilder.create().type(CustomDataSource.class).username("test").password("secret") - .url("jdbc:h2:test").driverClassName("com.example").build(); + this.dataSource = DataSourceBuilder.create() + .type(CustomDataSource.class) + .username("test") + .password("secret") + .url("jdbc:h2:test") + .driverClassName("com.example") + .build(); assertThat(this.dataSource).isInstanceOf(CustomDataSource.class); CustomDataSource testDataSource = (CustomDataSource) this.dataSource; assertThat(testDataSource.getUrl()).isEqualTo("jdbc:h2:test"); @@ -249,8 +295,10 @@ class DataSourceBuilderTests { @Test void buildWhenCustomTypeSpecifiedAndNoSuitableOptionalSetterBuilds() { - assertThatNoException().isThrownBy(() -> DataSourceBuilder.create().type(LimitedCustomDataSource.class) - .driverClassName("com.example").build()); + assertThatNoException().isThrownBy(() -> DataSourceBuilder.create() + .type(LimitedCustomDataSource.class) + .driverClassName("com.example") + .build()); } @Test @@ -265,8 +313,9 @@ class DataSourceBuilderTests { dataSource.setUsername("test"); dataSource.setPassword("secret"); dataSource.setJdbcUrl("jdbc:h2:test"); - HikariDataSource built = (HikariDataSource) DataSourceBuilder.derivedFrom(dataSource).url("jdbc:h2:test2") - .build(); + HikariDataSource built = (HikariDataSource) DataSourceBuilder.derivedFrom(dataSource) + .url("jdbc:h2:test2") + .build(); assertThat(built.getUsername()).isEqualTo("test"); assertThat(built.getPassword()).isEqualTo("secret"); assertThat(built.getJdbcUrl()).isEqualTo("jdbc:h2:test2"); @@ -292,7 +341,7 @@ class DataSourceBuilderTests { dataSource.setPassword("secret"); dataSource.setURL("example.com"); assertThatExceptionOfType(UnsupportedDataSourcePropertyException.class) - .isThrownBy(() -> DataSourceBuilder.derivedFrom(dataSource).url("example.org").build()); + .isThrownBy(() -> DataSourceBuilder.derivedFrom(dataSource).url("example.org").build()); } @Test @@ -302,7 +351,7 @@ class DataSourceBuilderTests { dataSource.setPassword("secret"); dataSource.setURL("example.com"); assertThatExceptionOfType(UnsupportedDataSourcePropertyException.class) - .isThrownBy(() -> DataSourceBuilder.derivedFrom(dataSource).url("example.org").build()); + .isThrownBy(() -> DataSourceBuilder.derivedFrom(dataSource).url("example.org").build()); } @Test @@ -313,10 +362,13 @@ class DataSourceBuilderTests { dataSource.setURL("example.com"); DataSourceBuilder builder = DataSourceBuilder.derivedFrom(dataSource); oracle.jdbc.datasource.impl.OracleDataSource built = (oracle.jdbc.datasource.impl.OracleDataSource) builder - .username("test2").password("secret2").build(); + .username("test2") + .password("secret2") + .build(); assertThat(built.getUser()).isEqualTo("test2"); - assertThat(built).extracting("password").extracting((opaque) -> ((OpaqueString) opaque).get()) - .isEqualTo("secret2"); + assertThat(built).extracting("password") + .extracting((opaque) -> ((OpaqueString) opaque).get()) + .isEqualTo("secret2"); assertThat(built.getURL()).isEqualTo("example.com"); } @@ -329,16 +381,19 @@ class DataSourceBuilderTests { DataSourceBuilder builder = DataSourceBuilder.derivedFrom(dataSource); PoolDataSource built = (PoolDataSource) builder.username("test2").password("secret2").build(); assertThat(built.getUser()).isEqualTo("test2"); - assertThat(built).extracting("password").extracting((opaque) -> ((oracle.ucp.util.OpaqueString) opaque).get()) - .isEqualTo("secret2"); + assertThat(built).extracting("password") + .extracting((opaque) -> ((oracle.ucp.util.OpaqueString) opaque).get()) + .isEqualTo("secret2"); assertThat(built.getURL()).isEqualTo("example.com"); } @Test void buildWhenDerivedFromEmbeddedDatabase() { EmbeddedDatabase database = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL).build(); - SimpleDriverDataSource built = (SimpleDriverDataSource) DataSourceBuilder.derivedFrom(database).username("test") - .password("secret").build(); + SimpleDriverDataSource built = (SimpleDriverDataSource) DataSourceBuilder.derivedFrom(database) + .username("test") + .password("secret") + .build(); assertThat(built.getUsername()).isEqualTo("test"); assertThat(built.getPassword()).isEqualTo("secret"); assertThat(built.getUrl()).startsWith("jdbc:hsqldb:mem"); @@ -363,8 +418,9 @@ class DataSourceBuilderTests { dataSource.setUsername("test"); dataSource.setPassword("secret"); dataSource.setUrl("jdbc:postgresql://localhost:5432/postgres"); - DataSourceBuilder builder = DataSourceBuilder.derivedFrom(dataSource).username("alice") - .password("confidential"); + DataSourceBuilder builder = DataSourceBuilder.derivedFrom(dataSource) + .username("alice") + .password("confidential"); CustomDataSource testSource = (CustomDataSource) builder.build(); assertThat(testSource).isNotSameAs(dataSource); assertThat(testSource.getUsername()).isEqualTo("alice"); @@ -387,9 +443,13 @@ class DataSourceBuilderTests { @Test // gh-31920 void buildWhenC3P0TypeSpecifiedReturnsExpectedDataSource() { - this.dataSource = DataSourceBuilder.create().url("jdbc:postgresql://localhost:5432/postgres") - .type(ComboPooledDataSource.class).username("test").password("secret") - .driverClassName("com.example.Driver").build(); + this.dataSource = DataSourceBuilder.create() + .url("jdbc:postgresql://localhost:5432/postgres") + .type(ComboPooledDataSource.class) + .username("test") + .password("secret") + .driverClassName("com.example.Driver") + .build(); assertThat(this.dataSource).isInstanceOf(ComboPooledDataSource.class); ComboPooledDataSource c3p0DataSource = (ComboPooledDataSource) this.dataSource; assertThat(c3p0DataSource.getJdbcUrl()).isEqualTo("jdbc:postgresql://localhost:5432/postgres"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperNoSpringJdbcTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperNoSpringJdbcTests.java index cd3ce07f37..068ea8c6fb 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperNoSpringJdbcTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperNoSpringJdbcTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class DataSourceUnwrapperNoSpringJdbcTests { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInProxy(wrapInProxy(dataSource)); assertThat(DataSourceUnwrapper.unwrap(actual, HikariConfigMXBean.class, HikariDataSource.class)) - .isSameAs(dataSource); + .isSameAs(dataSource); } @Test @@ -50,7 +50,7 @@ class DataSourceUnwrapperNoSpringJdbcTests { org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource(); DataSource actual = wrapInProxy(wrapInProxy(dataSource)); assertThat(DataSourceUnwrapper.unwrap(actual, PoolConfiguration.class, DataSourceProxy.class)) - .isSameAs(dataSource); + .isSameAs(dataSource); } private DataSource wrapInProxy(DataSource dataSource) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperTests.java index 0f93285fdd..b93bfd07ac 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,14 +47,14 @@ class DataSourceUnwrapperTests { void unwrapWithTarget() { DataSource dataSource = new HikariDataSource(); assertThat(DataSourceUnwrapper.unwrap(dataSource, HikariConfigMXBean.class, HikariDataSource.class)) - .isSameAs(dataSource); + .isSameAs(dataSource); } @Test void unwrapWithWrongTarget() { DataSource dataSource = new HikariDataSource(); assertThat(DataSourceUnwrapper.unwrap(dataSource, SmartDataSource.class, SingleConnectionDataSource.class)) - .isNull(); + .isNull(); } @Test @@ -62,7 +62,7 @@ class DataSourceUnwrapperTests { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInDelegate(wrapInDelegate(dataSource)); assertThat(DataSourceUnwrapper.unwrap(actual, HikariConfigMXBean.class, HikariDataSource.class)) - .isSameAs(dataSource); + .isSameAs(dataSource); } @Test @@ -70,7 +70,7 @@ class DataSourceUnwrapperTests { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInProxy(wrapInProxy(dataSource)); assertThat(DataSourceUnwrapper.unwrap(actual, HikariConfigMXBean.class, HikariDataSource.class)) - .isSameAs(dataSource); + .isSameAs(dataSource); } @Test @@ -78,7 +78,7 @@ class DataSourceUnwrapperTests { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInProxy(wrapInDelegate(dataSource)); assertThat(DataSourceUnwrapper.unwrap(actual, HikariConfigMXBean.class, HikariDataSource.class)) - .isSameAs(dataSource); + .isSameAs(dataSource); } @Test @@ -86,7 +86,7 @@ class DataSourceUnwrapperTests { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInProxy(wrapInDelegate(wrapInDelegate(wrapInProxy(wrapInDelegate(dataSource))))); assertThat(DataSourceUnwrapper.unwrap(actual, HikariConfigMXBean.class, HikariDataSource.class)) - .isSameAs(dataSource); + .isSameAs(dataSource); } @Test @@ -94,7 +94,7 @@ class DataSourceUnwrapperTests { org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource(); DataSource actual = wrapInDelegate(wrapInProxy(dataSource)); assertThat(DataSourceUnwrapper.unwrap(actual, PoolConfiguration.class, DataSourceProxy.class)) - .isSameAs(dataSource); + .isSameAs(dataSource); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java index 511bc8e29b..f2bbd85bac 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,8 +45,8 @@ import static org.assertj.core.api.Assertions.assertThat; class DatabaseDriverClassNameTests { private static final Set EXCLUDED_DRIVERS = Collections - .unmodifiableSet(EnumSet.of(DatabaseDriver.UNKNOWN, DatabaseDriver.DB2_AS400, DatabaseDriver.INFORMIX, - DatabaseDriver.HANA, DatabaseDriver.PHOENIX, DatabaseDriver.TERADATA, DatabaseDriver.REDSHIFT)); + .unmodifiableSet(EnumSet.of(DatabaseDriver.UNKNOWN, DatabaseDriver.DB2_AS400, DatabaseDriver.INFORMIX, + DatabaseDriver.HANA, DatabaseDriver.PHOENIX, DatabaseDriver.TERADATA, DatabaseDriver.REDSHIFT)); @ParameterizedTest(name = "{0} {2}") @MethodSource @@ -84,9 +84,10 @@ class DatabaseDriverClassNameTests { private static Stream argumentsForType(Class clazz, Predicate predicate, Function classNameExtractor) { - return Stream.of(DatabaseDriver.values()).filter((databaseDriver) -> !EXCLUDED_DRIVERS.contains(databaseDriver)) - .filter(predicate) - .map((databaseDriver) -> Arguments.of(databaseDriver, classNameExtractor.apply(databaseDriver), clazz)); + return Stream.of(DatabaseDriver.values()) + .filter((databaseDriver) -> !EXCLUDED_DRIVERS.contains(databaseDriver)) + .filter(predicate) + .map((databaseDriver) -> Arguments.of(databaseDriver, classNameExtractor.apply(databaseDriver), clazz)); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java index d3588ef00a..7ca5f44c90 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,7 @@ class DatabaseDriverTests { @Test void failureOnMalformedJdbcUrl() { assertThatIllegalArgumentException().isThrownBy(() -> DatabaseDriver.fromJdbcUrl("malformed:url")) - .withMessageContaining("URL must start with"); + .withMessageContaining("URL must start with"); } @Test @@ -95,28 +95,28 @@ class DatabaseDriverTests { assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sqlite:sample.db")).isEqualTo(DatabaseDriver.SQLITE); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:mysql://localhost:3306/sample")).isEqualTo(DatabaseDriver.MYSQL); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:oracle:thin:@localhost:1521:orcl")) - .isEqualTo(DatabaseDriver.ORACLE); + .isEqualTo(DatabaseDriver.ORACLE); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:postgresql://127.0.0.1:5432/sample")) - .isEqualTo(DatabaseDriver.POSTGRESQL); - assertThat(DatabaseDriver.fromJdbcUrl( - "jdbc:redshift://examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com:5439/sample")) - .isEqualTo(DatabaseDriver.REDSHIFT); + .isEqualTo(DatabaseDriver.POSTGRESQL); + assertThat(DatabaseDriver + .fromJdbcUrl("jdbc:redshift://examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com:5439/sample")) + .isEqualTo(DatabaseDriver.REDSHIFT); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:jtds:sqlserver://127.0.0.1:1433/sample")) - .isEqualTo(DatabaseDriver.JTDS); + .isEqualTo(DatabaseDriver.JTDS); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sap:localhost")).isEqualTo(DatabaseDriver.HANA); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sqlserver://127.0.0.1:1433")).isEqualTo(DatabaseDriver.SQLSERVER); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:firebirdsql://localhost/sample")) - .isEqualTo(DatabaseDriver.FIREBIRD); + .isEqualTo(DatabaseDriver.FIREBIRD); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:firebird://localhost/sample")).isEqualTo(DatabaseDriver.FIREBIRD); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:db2://localhost:50000/sample ")).isEqualTo(DatabaseDriver.DB2); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:as400://localhost")).isEqualTo(DatabaseDriver.DB2_AS400); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:teradata://localhost/SAMPLE")).isEqualTo(DatabaseDriver.TERADATA); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:informix-sqli://localhost:1533/sample")) - .isEqualTo(DatabaseDriver.INFORMIX); + .isEqualTo(DatabaseDriver.INFORMIX); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:informix-direct://sample")).isEqualTo(DatabaseDriver.INFORMIX); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:phoenix:localhost")).isEqualTo(DatabaseDriver.PHOENIX); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:tc:mysql://localhost:3306/sample")) - .isEqualTo(DatabaseDriver.TESTCONTAINERS); + .isEqualTo(DatabaseDriver.TESTCONTAINERS); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java index 2e33af606b..ec0b636d1d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,13 +46,13 @@ class EmbeddedDatabaseConnectionTests { @Test void h2CustomDatabaseName() { assertThat(EmbeddedDatabaseConnection.H2.getUrl("mydb")) - .isEqualTo("jdbc:h2:mem:mydb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); + .isEqualTo("jdbc:h2:mem:mydb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); } @Test void derbyCustomDatabaseName() { assertThat(EmbeddedDatabaseConnection.DERBY.getUrl("myderbydb")) - .isEqualTo("jdbc:derby:memory:myderbydb;create=true"); + .isEqualTo("jdbc:derby:memory:myderbydb;create=true"); } @Test @@ -63,13 +63,13 @@ class EmbeddedDatabaseConnectionTests { @Test void getUrlWithNullDatabaseNameForHsqldb() { assertThatIllegalArgumentException().isThrownBy(() -> EmbeddedDatabaseConnection.HSQLDB.getUrl(null)) - .withMessageContaining("DatabaseName must not be empty"); + .withMessageContaining("DatabaseName must not be empty"); } @Test void getUrlWithEmptyDatabaseNameForHsqldb() { assertThatIllegalArgumentException().isThrownBy(() -> EmbeddedDatabaseConnection.HSQLDB.getUrl(" ")) - .withMessageContaining("DatabaseName must not be empty"); + .withMessageContaining("DatabaseName must not be empty"); } @ParameterizedTest(name = "{0} - {1}") @@ -127,8 +127,8 @@ class EmbeddedDatabaseConnectionTests { @Test void isEmbeddedWithH2File() throws SQLException { assertThat(EmbeddedDatabaseConnection - .isEmbedded(mockDataSource(EmbeddedDatabaseConnection.H2.getDriverClassName(), "jdbc:h2:~/test"))) - .isFalse(); + .isEmbedded(mockDataSource(EmbeddedDatabaseConnection.H2.getDriverClassName(), "jdbc:h2:~/test"))) + .isFalse(); } @Test @@ -139,7 +139,7 @@ class EmbeddedDatabaseConnectionTests { @Test void isEmbeddedWithMissingUrlMetadata() throws SQLException { assertThat(EmbeddedDatabaseConnection - .isEmbedded(mockDataSource(EmbeddedDatabaseConnection.H2.getDriverClassName(), null))).isTrue(); + .isEmbedded(mockDataSource(EmbeddedDatabaseConnection.H2.getDriverClassName(), null))).isTrue(); } DataSource mockDataSource(String productName, String connectionUrl) throws SQLException { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/init/DataSourceScriptDatabaseInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/init/DataSourceScriptDatabaseInitializerTests.java index 475a846b1d..19511e7a70 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/init/DataSourceScriptDatabaseInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/init/DataSourceScriptDatabaseInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,13 +44,17 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; class DataSourceScriptDatabaseInitializerTests extends AbstractScriptDatabaseInitializerTests { - private final HikariDataSource embeddedDataSource = DataSourceBuilder.create().type(HikariDataSource.class) - .url("jdbc:h2:mem:" + UUID.randomUUID()).build(); - - private final HikariDataSource standaloneDataSource = DataSourceBuilder.create().type(HikariDataSource.class) - .url("jdbc:h2:file:" + new BuildOutput(DataSourceScriptDatabaseInitializerTests.class).getRootLocation() - .getAbsolutePath() + "/" + UUID.randomUUID()) - .build(); + private final HikariDataSource embeddedDataSource = DataSourceBuilder.create() + .type(HikariDataSource.class) + .url("jdbc:h2:mem:" + UUID.randomUUID()) + .build(); + + private final HikariDataSource standaloneDataSource = DataSourceBuilder.create() + .type(HikariDataSource.class) + .url("jdbc:h2:file:" + + new BuildOutput(DataSourceScriptDatabaseInitializerTests.class).getRootLocation().getAbsolutePath() + + "/" + UUID.randomUUID()) + .build(); @AfterEach void closeDataSource() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/init/PlatformPlaceholderDatabaseDriverResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/init/PlatformPlaceholderDatabaseDriverResolverTests.java index 1dd057f814..0cbea0e61a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/init/PlatformPlaceholderDatabaseDriverResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/init/PlatformPlaceholderDatabaseDriverResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,14 +47,14 @@ class PlatformPlaceholderDatabaseDriverResolverTests { @Test void resolveAllWithPlatformWhenValueDoesNotContainPlaceholderShouldReturnValueUnchanged() { assertThat(new PlatformPlaceholderDatabaseDriverResolver().resolveAll("test", "schema.sql")) - .containsExactly("schema.sql"); + .containsExactly("schema.sql"); } @Test void resolveAllWithPlatformWhenValuesContainPlaceholdersShouldReturnValuesWithPlaceholdersReplaced() { assertThat(new PlatformPlaceholderDatabaseDriverResolver().resolveAll("postgresql", "schema.sql", - "schema-@@platform@@.sql", "data-@@platform@@.sql")).containsExactly("schema.sql", - "schema-postgresql.sql", "data-postgresql.sql"); + "schema-@@platform@@.sql", "data-@@platform@@.sql")) + .containsExactly("schema.sql", "schema-postgresql.sql", "data-postgresql.sql"); } @Test @@ -65,43 +65,43 @@ class PlatformPlaceholderDatabaseDriverResolverTests { @Test void resolveAllWithDataSourceWhenValueDoesNotContainPlaceholderShouldReturnValueUnchanged() { assertThat(new PlatformPlaceholderDatabaseDriverResolver().resolveAll(mock(DataSource.class), "schema.sql")) - .containsExactly("schema.sql"); + .containsExactly("schema.sql"); } @Test void resolveAllWithDataSourceWhenValuesContainPlaceholdersShouldReturnValuesWithPlaceholdersReplaced() throws SQLException { assertThat(new PlatformPlaceholderDatabaseDriverResolver().resolveAll(dataSourceWithProductName("PostgreSQL"), - "schema.sql", "schema-@@platform@@.sql", "data-@@platform@@.sql")).containsExactly("schema.sql", - "schema-postgresql.sql", "data-postgresql.sql"); + "schema.sql", "schema-@@platform@@.sql", "data-@@platform@@.sql")) + .containsExactly("schema.sql", "schema-postgresql.sql", "data-postgresql.sql"); } @Test void resolveAllWithDataSourceWhenDriverMappingsAreCustomizedShouldResolvePlaceholderUsingCustomMapping() throws SQLException { assertThat(new PlatformPlaceholderDatabaseDriverResolver() - .withDriverPlatform(DatabaseDriver.POSTGRESQL, "postgres") - .resolveAll(dataSourceWithProductName("PostgreSQL"), "schema-@@platform@@.sql")) - .containsExactly("schema-postgres.sql"); + .withDriverPlatform(DatabaseDriver.POSTGRESQL, "postgres") + .resolveAll(dataSourceWithProductName("PostgreSQL"), "schema-@@platform@@.sql")) + .containsExactly("schema-postgres.sql"); } @Test void resolveAllWithDataSourceWhenValueIsAnEmptyStringShouldReturnValueUnchanged() { assertThat(new PlatformPlaceholderDatabaseDriverResolver().resolveAll(mock(DataSource.class), "")) - .containsExactly(""); + .containsExactly(""); } @Test void resolveAllWithDataSourceWhenDriverIsUnknownShouldThrow() { assertThatIllegalStateException().isThrownBy(() -> new PlatformPlaceholderDatabaseDriverResolver() - .resolveAll(dataSourceWithProductName("CustomDB"), "schema-@@platform@@.sql")); + .resolveAll(dataSourceWithProductName("CustomDB"), "schema-@@platform@@.sql")); } @Test void resolveAllWithDataSourceWhenPlaceholderIsCustomizedShouldResolvePlaceholders() throws SQLException { - assertThat(new PlatformPlaceholderDatabaseDriverResolver("##platform##").resolveAll( - dataSourceWithProductName("PostgreSQL"), "schema-##platform##.sql", "schema-@@platform@@.sql")) - .containsExactly("schema-postgresql.sql", "schema-@@platform@@.sql"); + assertThat(new PlatformPlaceholderDatabaseDriverResolver("##platform##") + .resolveAll(dataSourceWithProductName("PostgreSQL"), "schema-##platform##.sql", "schema-@@platform@@.sql")) + .containsExactly("schema-postgresql.sql", "schema-@@platform@@.sql"); } private DataSource dataSourceWithProductName(String productName) throws SQLException { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java index af494307e4..4feaa9e20f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -96,8 +96,10 @@ abstract class AbstractDataSourcePoolMetadataTests initializeBuilder() { - return DataSourceBuilder.create().driverClassName("org.hsqldb.jdbc.JDBCDriver").url("jdbc:hsqldb:mem:test") - .username("sa"); + return DataSourceBuilder.create() + .driverClassName("org.hsqldb.jdbc.JDBCDriver") + .url("jdbc:hsqldb:mem:test") + .username("sa"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java index 4652be4105..75d4ac1a55 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,7 +69,7 @@ class CommonsDbcp2DataSourcePoolMetadataTests BasicDataSource dataSource = createDataSource(); dataSource.setValidationQuery("SELECT FROM FOO"); assertThat(new CommonsDbcp2DataSourcePoolMetadata(dataSource).getValidationQuery()) - .isEqualTo("SELECT FROM FOO"); + .isEqualTo("SELECT FROM FOO"); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/OracleUcpDataSourcePoolMetadataTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/OracleUcpDataSourcePoolMetadataTests.java index b8379948c0..55d47d428e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/OracleUcpDataSourcePoolMetadataTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/OracleUcpDataSourcePoolMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ class OracleUcpDataSourcePoolMetadataTests PoolDataSource dataSource = createDataSource(0, 4); dataSource.setSQLForValidateConnection("SELECT NULL FROM DUAL"); assertThat(new OracleUcpDataSourcePoolMetadata(dataSource).getValidationQuery()) - .isEqualTo("SELECT NULL FROM DUAL"); + .isEqualTo("SELECT NULL FROM DUAL"); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java index 2d1a234de4..b02a18f759 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -102,7 +102,7 @@ abstract class AbstractJsonParserTests { @Test void mapOfLists() { Map map = this.parser - .parseMap("{\"foo\":[{\"foo\":\"bar\",\"spam\":1},{\"foo\":\"baz\",\"spam\":2}]}"); + .parseMap("{\"foo\":[{\"foo\":\"bar\",\"spam\":1},{\"foo\":\"baz\",\"spam\":2}]}"); assertThat(map).hasSize(1); assertThat(((List) map.get("foo"))).hasSize(2); assertThat(map.get("foo")).asList().allMatch(Map.class::isInstance); @@ -111,8 +111,8 @@ abstract class AbstractJsonParserTests { @SuppressWarnings("unchecked") @Test void nestedLeadingAndTrailingWhitespace() { - Map map = this.parser.parseMap( - " {\"foo\": [ { \"foo\" : \"bar\" , \"spam\" : 1 } , { \"foo\" : \"baz\" , \"spam\" : 2 } ] } "); + Map map = this.parser + .parseMap(" {\"foo\": [ { \"foo\" : \"bar\" , \"spam\" : 1 } , { \"foo\" : \"baz\" , \"spam\" : 2 } ] } "); assertThat(map).hasSize(1); assertThat(((List) map.get("foo"))).hasSize(2); assertThat(map.get("foo")).asList().allMatch(Map.class::isInstance); @@ -182,7 +182,7 @@ abstract class AbstractJsonParserTests { @Test void listWithMalformedMap() { assertThatExceptionOfType(JsonParseException.class) - .isThrownBy(() -> this.parser.parseList("[tru,erqett,{\"foo\":fatrue,true,true,true,tr''ue}]")); + .isThrownBy(() -> this.parser.parseList("[tru,erqett,{\"foo\":fatrue,true,true,true,tr''ue}]")); } @Test @@ -194,8 +194,9 @@ abstract class AbstractJsonParserTests { void listWithRepeatedOpenArray() throws IOException { String input = StreamUtils.copyToString( AbstractJsonParserTests.class.getResourceAsStream("repeated-open-array.txt"), StandardCharsets.UTF_8); - assertThatExceptionOfType(JsonParseException.class).isThrownBy(() -> this.parser.parseList(input)).havingCause() - .withMessageContaining("too deeply nested"); + assertThatExceptionOfType(JsonParseException.class).isThrownBy(() -> this.parser.parseList(input)) + .havingCause() + .withMessageContaining("too deeply nested"); } @Test // gh-31869 diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/YamlJsonParserTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/YamlJsonParserTests.java index 9ce5025993..b7d22e2607 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/YamlJsonParserTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/YamlJsonParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,8 @@ class YamlJsonParserTests extends AbstractJsonParserTests { @Test void customTypesAreNotLoaded() { assertThatExceptionOfType(ConstructorException.class) - .isThrownBy(() -> getParser().parseMap("{value: !!java.net.URL [\"http://localhost:9000/\"]}")) - .withCauseInstanceOf(IllegalStateException.class); + .isThrownBy(() -> getParser().parseMap("{value: !!java.net.URL [\"http://localhost:9000/\"]}")) + .withCauseInstanceOf(IllegalStateException.class); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseChangelogMissingFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseChangelogMissingFailureAnalyzerTests.java index abb98d3623..cff43ce914 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseChangelogMissingFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseChangelogMissingFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,10 +43,10 @@ class LiquibaseChangelogMissingFailureAnalyzerTests { void changelogParseExceptionDueToChangelogNotPresent() { FailureAnalysis analysis = performAnalysis(); assertThat(analysis.getDescription()) - .isEqualTo("Liquibase failed to start because no changelog could be found at '" - + "classpath:/db/changelog/db.changelog-master.yaml'."); + .isEqualTo("Liquibase failed to start because no changelog could be found at '" + + "classpath:/db/changelog/db.changelog-master.yaml'."); assertThat(analysis.getAction()) - .isEqualTo("Make sure a Liquibase changelog is present at the configured path."); + .isEqualTo("Make sure a Liquibase changelog is present at the configured path."); } private FailureAnalysis performAnalysis() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java index f2f952217c..ee2b70cbf6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,7 +73,7 @@ class LogFileTests { logFile.applyTo(properties); assertThat(logFile.toString()).isEqualTo("logpath" + File.separatorChar + "spring.log"); assertThat(properties.getProperty(LoggingSystemProperties.LOG_FILE)) - .isEqualTo("logpath" + File.separatorChar + "spring.log"); + .isEqualTo("logpath" + File.separatorChar + "spring.log"); assertThat(properties.getProperty(LoggingSystemProperties.LOG_PATH)).isEqualTo("logpath"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java index 800b3c09d1..3fb0106d71 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,7 +62,7 @@ class LoggingSystemPropertiesTests { @Test void consoleLogPatternIsSet() { new LoggingSystemProperties(new MockEnvironment().withProperty("logging.pattern.console", "console pattern")) - .apply(null); + .apply(null); assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)).isEqualTo("console pattern"); } @@ -75,14 +75,14 @@ class LoggingSystemPropertiesTests { @Test void consoleCharsetIsSet() { new LoggingSystemProperties(new MockEnvironment().withProperty("logging.charset.console", "UTF-16")) - .apply(null); + .apply(null); assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_CHARSET)).isEqualTo("UTF-16"); } @Test void fileLogPatternIsSet() { new LoggingSystemProperties(new MockEnvironment().withProperty("logging.pattern.file", "file pattern")) - .apply(null); + .apply(null); assertThat(System.getProperty(LoggingSystemProperties.FILE_LOG_PATTERN)).isEqualTo("file pattern"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemTests.java index 5cd927e1b9..644f7c9c55 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,13 +52,13 @@ class LoggingSystemTests { @Test void getLoggerConfigurationIsUnsupported() { assertThatExceptionOfType(UnsupportedOperationException.class) - .isThrownBy(() -> new StubLoggingSystem().getLoggerConfiguration("test-logger-name")); + .isThrownBy(() -> new StubLoggingSystem().getLoggerConfiguration("test-logger-name")); } @Test void listLoggerConfigurationsIsUnsupported() { assertThatExceptionOfType(UnsupportedOperationException.class) - .isThrownBy(() -> new StubLoggingSystem().getLoggerConfigurations()); + .isThrownBy(() -> new StubLoggingSystem().getLoggerConfigurations()); } private static final class StubLoggingSystem extends LoggingSystem { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java index b17a0e6569..fd1d69abbf 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -133,8 +133,8 @@ class JavaLoggingSystemTests extends AbstractLoggingSystemTests { @Test void testNonexistentConfigLocation() { this.loggingSystem.beforeInitialize(); - assertThatIllegalStateException().isThrownBy( - () -> this.loggingSystem.initialize(null, "classpath:logging-nonexistent.properties", null)); + assertThatIllegalStateException() + .isThrownBy(() -> this.loggingSystem.initialize(null, "classpath:logging-nonexistent.properties", null)); } @Test @@ -182,7 +182,7 @@ class JavaLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(getClass().getName()); assertThat(configuration) - .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.DEBUG, LogLevel.DEBUG)); + .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.DEBUG, LogLevel.DEBUG)); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java index 50c29bb3c0..098e6d9a77 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ExtendedWhitespaceThrowablePatternConverterTests { private final ThrowablePatternConverter converter = ExtendedWhitespaceThrowablePatternConverter - .newInstance(new DefaultConfiguration(), new String[] {}); + .newInstance(new DefaultConfiguration(), new String[] {}); @Test void noStackTrace() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java index c23aa8e59d..4db75c0e93 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -141,7 +141,7 @@ class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { assertThat(output).contains("Hello world").contains(tmpDir() + "/tmp.log"); assertThat(new File(tmpDir() + "/tmp.log").exists()).isFalse(); assertThat(configuration.getConfigurationSource().getFile().getAbsolutePath()) - .contains("log4j2-nondefault.xml"); + .contains("log4j2-nondefault.xml"); assertThat(configuration.getWatchManager().getIntervalSeconds()).isEqualTo(30); } @@ -218,7 +218,7 @@ class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(getClass().getName()); assertThat(configuration) - .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.DEBUG, LogLevel.DEBUG)); + .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.DEBUG, LogLevel.DEBUG)); } @Test @@ -361,7 +361,7 @@ class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.setLogLevel("com.example.test", LogLevel.DEBUG); LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration("com.example.test"); assertThat(configuration) - .isEqualTo(new LoggerConfiguration("com.example.test", LogLevel.DEBUG, LogLevel.DEBUG)); + .isEqualTo(new LoggerConfiguration("com.example.test", LogLevel.DEBUG, LogLevel.DEBUG)); this.loggingSystem.setLogLevel("com.example.test", null); LoggerConfiguration updatedConfiguration = this.loggingSystem.getLoggerConfiguration("com.example.test"); assertThat(updatedConfiguration).isNull(); @@ -372,24 +372,25 @@ class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); - loggerContext.getConfiguration().addLogger("com.example.test", - new LoggerConfig("com.example.test", org.apache.logging.log4j.Level.INFO, false)); + loggerContext.getConfiguration() + .addLogger("com.example.test", + new LoggerConfig("com.example.test", org.apache.logging.log4j.Level.INFO, false)); this.loggingSystem.setLogLevel("com.example", LogLevel.WARN); this.loggingSystem.setLogLevel("com.example.test", LogLevel.DEBUG); LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration("com.example.test"); assertThat(configuration) - .isEqualTo(new LoggerConfiguration("com.example.test", LogLevel.DEBUG, LogLevel.DEBUG)); + .isEqualTo(new LoggerConfiguration("com.example.test", LogLevel.DEBUG, LogLevel.DEBUG)); this.loggingSystem.setLogLevel("com.example.test", null); LoggerConfiguration updatedConfiguration = this.loggingSystem.getLoggerConfiguration("com.example.test"); assertThat(updatedConfiguration) - .isEqualTo(new LoggerConfiguration("com.example.test", LogLevel.WARN, LogLevel.WARN)); + .isEqualTo(new LoggerConfiguration("com.example.test", LogLevel.WARN, LogLevel.WARN)); } @Test void shutdownHookIsDisabled() { assertThat( PropertiesUtil.getProperties().getBooleanProperty(ShutdownCallbackRegistry.SHUTDOWN_HOOK_ENABLED, true)) - .isFalse(); + .isFalse(); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4j2XmlTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4j2XmlTests.java index 98102c696e..c5dff38233 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4j2XmlTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4j2XmlTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -101,8 +101,8 @@ class Log4j2XmlTests { protected Configuration initializeConfiguration() { LoggerContext context = new LoggerContext("test"); - Configuration configuration = ConfigurationFactory.getInstance().getConfiguration(context, - configurationSource()); + Configuration configuration = ConfigurationFactory.getInstance() + .getConfiguration(context, configurationSource()); configuration.initialize(); return configuration; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootPropertySourceTests.java index 633fbf6c1f..56b96c4d4f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ class SpringBootPropertySourceTests { @Test void allDefaultMethodsAreImplemented() { assertThat(Stream.of(SpringBootPropertySource.class.getMethods()).filter((method) -> method.isDefault())) - .isEmpty(); + .isEmpty(); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java index e91ec4e2d6..ab857740fa 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat; class WhitespaceThrowablePatternConverterTests { private final ThrowablePatternConverter converter = WhitespaceThrowablePatternConverter - .newInstance(new DefaultConfiguration(), new String[] {}); + .newInstance(new DefaultConfiguration(), new String[] {}); @Test void noStackTrace() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemPropertiesTests.java index 5e4f0596d5..2ab61b672f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,7 @@ class LogbackLoggingSystemPropertiesTests { this.systemPropertyNames = new HashSet<>(System.getProperties().keySet()); this.environment = new MockEnvironment(); this.environment - .setConversionService((ConfigurableConversionService) ApplicationConversionService.getSharedInstance()); + .setConversionService((ConfigurableConversionService) ApplicationConversionService.getSharedInstance()); } @@ -74,11 +74,11 @@ class LogbackLoggingSystemPropertiesTests { this.environment.setProperty("logging.logback.rollingpolicy.max-history", "mh"); new LogbackLoggingSystemProperties(this.environment).apply(); assertThat(System.getProperties()) - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_FILE_NAME_PATTERN, "fnp") - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_CLEAN_HISTORY_ON_START, "chos") - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_MAX_FILE_SIZE, "1024") - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_TOTAL_SIZE_CAP, "2048") - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_MAX_HISTORY, "mh"); + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_FILE_NAME_PATTERN, "fnp") + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_CLEAN_HISTORY_ON_START, "chos") + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_MAX_FILE_SIZE, "1024") + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_TOTAL_SIZE_CAP, "2048") + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_MAX_HISTORY, "mh"); } @Test @@ -90,25 +90,25 @@ class LogbackLoggingSystemPropertiesTests { this.environment.setProperty("logging.file.max-history", "mh"); new LogbackLoggingSystemProperties(this.environment).apply(); assertThat(System.getProperties()) - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_FILE_NAME_PATTERN, "fnp") - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_CLEAN_HISTORY_ON_START, "chos") - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_MAX_FILE_SIZE, "1024") - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_TOTAL_SIZE_CAP, "2048") - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_MAX_HISTORY, "mh"); + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_FILE_NAME_PATTERN, "fnp") + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_CLEAN_HISTORY_ON_START, "chos") + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_MAX_FILE_SIZE, "1024") + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_TOTAL_SIZE_CAP, "2048") + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_MAX_HISTORY, "mh"); } @Test void consoleCharsetWhenNoPropertyUsesDefault() { new LoggingSystemProperties(new MockEnvironment()).apply(null); assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_CHARSET)) - .isEqualTo(Charset.defaultCharset().name()); + .isEqualTo(Charset.defaultCharset().name()); } @Test void fileCharsetWhenNoPropertyUsesDefault() { new LoggingSystemProperties(new MockEnvironment()).apply(null); assertThat(System.getProperty(LoggingSystemProperties.FILE_LOG_CHARSET)) - .isEqualTo(Charset.defaultCharset().name()); + .isEqualTo(Charset.defaultCharset().name()); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java index 18f309016b..d54f6ee71d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -156,8 +156,10 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { initialize(this.initializationContext, "classpath:logback-nondefault.xml", getLogFile(tmpDir() + "/tmp.log", null)); this.logger.info("Hello world"); - assertThat(output).doesNotContain("DEBUG").contains("Hello world").contains(tmpDir() + "/tmp.log") - .endsWith("BOOTBOOT"); + assertThat(output).doesNotContain("DEBUG") + .contains("Hello world") + .contains(tmpDir() + "/tmp.log") + .endsWith("BOOTBOOT"); assertThat(new File(tmpDir() + "/tmp.log").exists()).isFalse(); } @@ -167,8 +169,8 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { try { this.loggingSystem.beforeInitialize(); initialize(this.initializationContext, null, null); - assertThat(output).contains( - "Ignoring 'logback.configurationFile' system property. Please use 'logging.config' instead."); + assertThat(output) + .contains("Ignoring 'logback.configurationFile' system property. Please use 'logging.config' instead."); } finally { System.clearProperty("logback.configurationFile"); @@ -179,7 +181,7 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { void testNonexistentConfigLocation() { this.loggingSystem.beforeInitialize(); assertThatIllegalStateException() - .isThrownBy(() -> initialize(this.initializationContext, "classpath:logback-nonexistent.xml", null)); + .isThrownBy(() -> initialize(this.initializationContext, "classpath:logback-nonexistent.xml", null)); } @Test @@ -227,7 +229,7 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(getClass().getName()); assertThat(configuration) - .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.DEBUG, LogLevel.DEBUG)); + .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.DEBUG, LogLevel.DEBUG)); } @Test @@ -246,7 +248,7 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { logger.setLevel(Level.ALL); LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(getClass().getName()); assertThat(configuration) - .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.TRACE, LogLevel.TRACE)); + .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.TRACE, LogLevel.TRACE)); } @Test @@ -390,7 +392,7 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.logger.info("Hello world"); assertThat(getLineWithText(file, "Hello world")).contains("INFO"); assertThat(ReflectionTestUtils.getField(getRollingPolicy(), "maxFileSize").toString()) - .isEqualTo(expectedFileSize); + .isEqualTo(expectedFileSize); } @Test @@ -453,7 +455,7 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.logger.info("Hello world"); assertThat(getLineWithText(file, "Hello world")).contains("INFO"); assertThat(ReflectionTestUtils.getField(getRollingPolicy(), "totalSizeCap").toString()) - .isEqualTo(expectedFileSize); + .isEqualTo(expectedFileSize); } @Test @@ -555,7 +557,7 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { initialize(loggingInitializationContext, null, null); this.logger.info("Hello world"); assertThat(getLineWithText(output, "Hello world")) - .containsPattern("\\d{4}-\\d{2}\\-\\d{2}T\\d{2}:\\d{2}:\\d{2}"); + .containsPattern("\\d{4}-\\d{2}\\-\\d{2}T\\d{2}:\\d{2}:\\d{2}"); } @Test // gh-24835 @@ -567,7 +569,7 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { initialize(loggingInitializationContext, null, null); this.logger.info("Hello world"); assertThat(getLineWithText(output, "Hello world")) - .containsPattern("\\d{4}-\\d{2}\\-\\d{2}T\\d{2}:\\d{2}:\\d{2}"); + .containsPattern("\\d{4}-\\d{2}\\-\\d{2}T\\d{2}:\\d{2}:\\d{2}"); } @Test @@ -588,8 +590,9 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { File file = new File(tmpDir(), "logback-test.log"); LogFile logFile = getLogFile(file.getPath(), null); initialize(this.initializationContext, null, logFile); - assertThat(output).contains("LevelChangePropagator").contains("SizeAndTimeBasedFNATP") - .contains("DebugLogbackConfigurator"); + assertThat(output).contains("LevelChangePropagator") + .contains("SizeAndTimeBasedFNATP") + .contains("DebugLogbackConfigurator"); } finally { System.clearProperty("logback.debug"); @@ -649,8 +652,10 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } private String getLineWithText(CharSequence output, CharSequence outputSearch) { - return Arrays.stream(output.toString().split("\\r?\\n")).filter((line) -> line.contains(outputSearch)) - .findFirst().orElse(null); + return Arrays.stream(output.toString().split("\\r?\\n")) + .filter((line) -> line.contains(outputSearch)) + .findFirst() + .orElse(null); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/JarUriTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/JarUriTests.java index 04fdf8965c..f7ba6d72a3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/JarUriTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/JarUriTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class JarUriTests { @Test void describeRegularJar() { JarUri uri = JarUri - .from("jar:file:/home/user/project/target/project-0.0.1-SNAPSHOT.jar!/application.properties"); + .from("jar:file:/home/user/project/target/project-0.0.1-SNAPSHOT.jar!/application.properties"); assertThat(uri.getDescription()).isEqualTo("project-0.0.1-SNAPSHOT.jar"); } @@ -50,7 +50,7 @@ class JarUriTests { void getDescriptionMergedWithExisting() { JarUri uri = JarUri.from("jar:file:/project-0.0.1-SNAPSHOT.jar!/application.properties"); assertThat(uri.getDescription("classpath: [application.properties]")) - .isEqualTo("classpath: [application.properties] from project-0.0.1-SNAPSHOT.jar"); + .isEqualTo("classpath: [application.properties] from project-0.0.1-SNAPSHOT.jar"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTrackedResourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTrackedResourceTests.java index 74b10996cd..55ec2ed54b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTrackedResourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTrackedResourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -184,7 +184,7 @@ class OriginTrackedResourceTests { Resource resource = mock(WritableResource.class); Resource tracked = OriginTrackedResource.of(resource, this.origin); assertThat(tracked).isInstanceOf(WritableResource.class) - .isExactlyInstanceOf(OriginTrackedWritableResource.class); + .isExactlyInstanceOf(OriginTrackedWritableResource.class); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java index 9f1a8ee631..56eb68e34a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,20 +39,20 @@ class PropertySourceOriginTests { @Test void createWhenPropertySourceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new PropertySourceOrigin(null, "name")) - .withMessageContaining("PropertySource must not be null"); + .withMessageContaining("PropertySource must not be null"); } @Test void createWhenPropertyNameIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new PropertySourceOrigin(mock(PropertySource.class), null)) - .withMessageContaining("PropertyName must not be empty"); + .isThrownBy(() -> new PropertySourceOrigin(mock(PropertySource.class), null)) + .withMessageContaining("PropertyName must not be empty"); } @Test void createWhenPropertyNameIsEmptyShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new PropertySourceOrigin(mock(PropertySource.class), "")) - .withMessageContaining("PropertyName must not be empty"); + .withMessageContaining("PropertyName must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategyTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategyTests.java index dbcf3a4a0b..a66e3de2f6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategyTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,8 @@ class SpringPhysicalNamingStrategyTests { this.metadataSources = new MetadataSources(createServiceRegistry()); this.metadataSources.addAnnotatedClass(TelephoneNumber.class); this.metadata = this.metadataSources.getMetadataBuilder() - .applyPhysicalNamingStrategy(new SpringPhysicalNamingStrategy()).build(); + .applyPhysicalNamingStrategy(new SpringPhysicalNamingStrategy()) + .build(); } private StandardServiceRegistry createServiceRegistry() { @@ -63,7 +64,8 @@ class SpringPhysicalNamingStrategyTests { @Test void tableNameShouldNotBeLowerCaseIfCaseSensitive() { this.metadata = this.metadataSources.getMetadataBuilder() - .applyPhysicalNamingStrategy(new TestSpringPhysicalNamingStrategy()).build(); + .applyPhysicalNamingStrategy(new TestSpringPhysicalNamingStrategy()) + .build(); PersistentClass binding = this.metadata.getEntityBinding(TelephoneNumber.class.getName()); assertThat(binding.getTable().getQuotedName()).isEqualTo("Telephone_Number"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/ConnectionFactoryBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/ConnectionFactoryBuilderTests.java index ad78dc731e..e9e5e3988d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/ConnectionFactoryBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/ConnectionFactoryBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,7 +66,7 @@ class ConnectionFactoryBuilderTests { @Test void createWithEmbeddedConnectionNoneShouldFail() { assertThatIllegalArgumentException() - .isThrownBy(() -> ConnectionFactoryBuilder.withUrl(EmbeddedDatabaseConnection.NONE.getUrl("test"))); + .isThrownBy(() -> ConnectionFactoryBuilder.withUrl(EmbeddedDatabaseConnection.NONE.getUrl("test"))); } @Test @@ -80,7 +80,8 @@ class ConnectionFactoryBuilderTests { @Test void buildOptionsWithEmbeddedConnectionH2ShouldExposeOptions() { ConnectionFactoryOptions options = ConnectionFactoryBuilder - .withUrl(EmbeddedDatabaseConnection.H2.getUrl("testdb")).buildOptions(); + .withUrl(EmbeddedDatabaseConnection.H2.getUrl("testdb")) + .buildOptions(); assertThat(options.getRequiredValue(ConnectionFactoryOptions.DRIVER)).isEqualTo("h2"); assertThat(options.getRequiredValue(ConnectionFactoryOptions.PROTOCOL)).isEqualTo("mem"); assertThat(options.getRequiredValue(ConnectionFactoryOptions.DATABASE)).isEqualTo("testdb"); @@ -89,13 +90,14 @@ class ConnectionFactoryBuilderTests { assertThat(options.hasOption(ConnectionFactoryOptions.USER)).isFalse(); assertThat(options.hasOption(ConnectionFactoryOptions.PASSWORD)).isFalse(); assertThat(options.getValue(Option.valueOf("options"))) - .isEqualTo("DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); + .isEqualTo("DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); } @Test void buildOptionsWithCompleteUrlShouldExposeOptions() { ConnectionFactoryOptions options = ConnectionFactoryBuilder - .withUrl("r2dbc:simple:proto://user:password@myhost:4711/mydatabase").buildOptions(); + .withUrl("r2dbc:simple:proto://user:password@myhost:4711/mydatabase") + .buildOptions(); assertThat(options.getRequiredValue(ConnectionFactoryOptions.DRIVER)).isEqualTo("simple"); assertThat(options.getRequiredValue(ConnectionFactoryOptions.PROTOCOL)).isEqualTo("proto"); assertThat(options.getRequiredValue(ConnectionFactoryOptions.USER)).isEqualTo("user"); @@ -108,9 +110,13 @@ class ConnectionFactoryBuilderTests { @Test void buildOptionsWithSpecificSettingsShouldOverrideUrlOptions() { ConnectionFactoryOptions options = ConnectionFactoryBuilder - .withUrl("r2dbc:simple://user:password@myhost/mydatabase").username("another-user") - .password("another-password").hostname("another-host").port(1234).database("another-database") - .buildOptions(); + .withUrl("r2dbc:simple://user:password@myhost/mydatabase") + .username("another-user") + .password("another-password") + .hostname("another-host") + .port(1234) + .database("another-database") + .buildOptions(); assertThat(options.getRequiredValue(ConnectionFactoryOptions.USER)).isEqualTo("another-user"); assertThat(options.getRequiredValue(ConnectionFactoryOptions.PASSWORD)).isEqualTo("another-password"); assertThat(options.getRequiredValue(ConnectionFactoryOptions.HOST)).isEqualTo("another-host"); @@ -121,9 +127,8 @@ class ConnectionFactoryBuilderTests { @Test void buildOptionsWithDriverPropertiesShouldExposeOptions() { ConnectionFactoryOptions options = ConnectionFactoryBuilder.withUrl("r2dbc:simple://user:password@myhost") - .configure( - (o) -> o.option(Option.valueOf("simpleOne"), "one").option(Option.valueOf("simpleTwo"), "two")) - .buildOptions(); + .configure((o) -> o.option(Option.valueOf("simpleOne"), "one").option(Option.valueOf("simpleTwo"), "two")) + .buildOptions(); assertThat(options.getRequiredValue(Option.valueOf("simpleOne"))).isEqualTo("one"); assertThat(options.getRequiredValue(Option.valueOf("simpleTwo"))).isEqualTo("two"); } @@ -132,7 +137,8 @@ class ConnectionFactoryBuilderTests { void buildShouldExposeConnectionFactory() { String databaseName = UUID.randomUUID().toString(); ConnectionFactory connectionFactory = ConnectionFactoryBuilder - .withUrl(EmbeddedDatabaseConnection.H2.getUrl(databaseName)).build(); + .withUrl(EmbeddedDatabaseConnection.H2.getUrl(databaseName)) + .build(); assertThat(connectionFactory).isNotNull(); assertThat(connectionFactory.getMetadata().getName()).isEqualTo(H2ConnectionFactoryMetadata.NAME); } @@ -141,11 +147,13 @@ class ConnectionFactoryBuilderTests { void buildWhenDerivedWithNewDatabaseReturnsNewConnectionFactory() { String initialDatabaseName = UUID.randomUUID().toString(); ConnectionFactory connectionFactory = ConnectionFactoryBuilder - .withUrl(EmbeddedDatabaseConnection.H2.getUrl(initialDatabaseName)).build(); + .withUrl(EmbeddedDatabaseConnection.H2.getUrl(initialDatabaseName)) + .build(); ConnectionFactoryOptions initialOptions = ((OptionsCapableConnectionFactory) connectionFactory).getOptions(); String derivedDatabaseName = UUID.randomUUID().toString(); ConnectionFactory derived = ConnectionFactoryBuilder.derivedFrom(connectionFactory) - .database(derivedDatabaseName).build(); + .database(derivedDatabaseName) + .build(); ConnectionFactoryOptions derivedOptions = ((OptionsCapableConnectionFactory) derived).getOptions(); assertThat(derivedOptions.getRequiredValue(ConnectionFactoryOptions.DATABASE)).isEqualTo(derivedDatabaseName); assertMatchingOptions(derivedOptions, initialOptions, ConnectionFactoryOptions.CONNECT_TIMEOUT, @@ -157,10 +165,13 @@ class ConnectionFactoryBuilderTests { @Test void buildWhenDerivedWithNewCredentialsReturnsNewConnectionFactory() { ConnectionFactory connectionFactory = ConnectionFactoryBuilder - .withUrl(EmbeddedDatabaseConnection.H2.getUrl(UUID.randomUUID().toString())).build(); + .withUrl(EmbeddedDatabaseConnection.H2.getUrl(UUID.randomUUID().toString())) + .build(); ConnectionFactoryOptions initialOptions = ((OptionsCapableConnectionFactory) connectionFactory).getOptions(); - ConnectionFactory derived = ConnectionFactoryBuilder.derivedFrom(connectionFactory).username("admin") - .password("secret").build(); + ConnectionFactory derived = ConnectionFactoryBuilder.derivedFrom(connectionFactory) + .username("admin") + .password("secret") + .build(); ConnectionFactoryOptions derivedOptions = ((OptionsCapableConnectionFactory) derived).getOptions(); assertThat(derivedOptions.getRequiredValue(ConnectionFactoryOptions.USER)).isEqualTo("admin"); assertThat(derivedOptions.getRequiredValue(ConnectionFactoryOptions.PASSWORD)).isEqualTo("secret"); @@ -172,12 +183,15 @@ class ConnectionFactoryBuilderTests { @Test void buildWhenDerivedFromPoolReturnsNewNonPooledConnectionFactory() { ConnectionFactory connectionFactory = ConnectionFactoryBuilder - .withUrl(EmbeddedDatabaseConnection.H2.getUrl(UUID.randomUUID().toString())).build(); + .withUrl(EmbeddedDatabaseConnection.H2.getUrl(UUID.randomUUID().toString())) + .build(); ConnectionFactoryOptions initialOptions = ((OptionsCapableConnectionFactory) connectionFactory).getOptions(); ConnectionPoolConfiguration poolConfiguration = ConnectionPoolConfiguration.builder(connectionFactory).build(); ConnectionPool pool = new ConnectionPool(poolConfiguration); - ConnectionFactory derived = ConnectionFactoryBuilder.derivedFrom(pool).username("admin").password("secret") - .build(); + ConnectionFactory derived = ConnectionFactoryBuilder.derivedFrom(pool) + .username("admin") + .password("secret") + .build(); assertThat(derived).isNotInstanceOf(ConnectionPool.class).isInstanceOf(OptionsCapableConnectionFactory.class); ConnectionFactoryOptions derivedOptions = ((OptionsCapableConnectionFactory) derived).getOptions(); assertThat(derivedOptions.getRequiredValue(ConnectionFactoryOptions.USER)).isEqualTo("admin"); @@ -193,11 +207,12 @@ class ConnectionFactoryBuilderTests { void optionIsMappedWhenCreatingPoolConfiguration(Option option) { String url = "r2dbc:pool:h2:mem:///" + UUID.randomUUID(); ExpectedOption expectedOption = ExpectedOption.get(option); - ConnectionFactoryOptions options = ConnectionFactoryBuilder.withUrl(url).configure((builder) -> builder - .option(PoolingConnectionFactoryProvider.POOL_NAME, "defaultName").option(option, expectedOption.value)) - .buildOptions(); + ConnectionFactoryOptions options = ConnectionFactoryBuilder.withUrl(url) + .configure((builder) -> builder.option(PoolingConnectionFactoryProvider.POOL_NAME, "defaultName") + .option(option, expectedOption.value)) + .buildOptions(); ConnectionPoolConfiguration configuration = new PoolingAwareOptionsCapableWrapper() - .connectionPoolConfiguration(options, mock(ConnectionFactory.class)); + .connectionPoolConfiguration(options, mock(ConnectionFactory.class)); assertThat(configuration).extracting(expectedOption.property).isEqualTo(expectedOption.value); } @@ -212,11 +227,11 @@ class ConnectionFactoryBuilderTests { String url = "r2dbc:pool:h2:mem:///" + UUID.randomUUID(); ExpectedOption expectedOption = ExpectedOption.get(option); ConnectionFactoryOptions options = ConnectionFactoryBuilder.withUrl(url) - .configure((builder) -> builder.option(PoolingConnectionFactoryProvider.POOL_NAME, "defaultName") - .option(option, expectedOption.value.toString())) - .buildOptions(); + .configure((builder) -> builder.option(PoolingConnectionFactoryProvider.POOL_NAME, "defaultName") + .option(option, expectedOption.value.toString())) + .buildOptions(); ConnectionPoolConfiguration configuration = new PoolingAwareOptionsCapableWrapper() - .connectionPoolConfiguration(options, mock(ConnectionFactory.class)); + .connectionPoolConfiguration(options, mock(ConnectionFactory.class)); assertThat(configuration).extracting(expectedOption.property).isEqualTo(expectedOption.value); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/EmbeddedDatabaseConnectionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/EmbeddedDatabaseConnectionTests.java index a5bab4f5b4..57433751ad 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/EmbeddedDatabaseConnectionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/EmbeddedDatabaseConnectionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,50 +48,49 @@ class EmbeddedDatabaseConnectionTests { @Test void getReturnsH2ByDefault() { assertThat(EmbeddedDatabaseConnection.get(EmbeddedDatabaseConnectionTests.class.getClassLoader())) - .isEqualTo(EmbeddedDatabaseConnection.H2); + .isEqualTo(EmbeddedDatabaseConnection.H2); } @Test void getWhenH2IsNotOnTheClasspathReturnsNone() { assertThat(EmbeddedDatabaseConnection.get(new HidePackagesClassLoader("io.r2dbc.h2"))) - .isEqualTo(EmbeddedDatabaseConnection.NONE); + .isEqualTo(EmbeddedDatabaseConnection.NONE); } @Test void whenH2IsInMemoryThenIsEmbeddedReturnsTrue() { assertThat(EmbeddedDatabaseConnection - .isEmbedded(ConnectionFactoryBuilder.withUrl("r2dbc:h2:mem:///" + UUID.randomUUID()).build())).isTrue(); + .isEmbedded(ConnectionFactoryBuilder.withUrl("r2dbc:h2:mem:///" + UUID.randomUUID()).build())).isTrue(); } @Test void whenH2IsUsingFileStorageThenIsEmbeddedReturnsFalse() { assertThat(EmbeddedDatabaseConnection - .isEmbedded(ConnectionFactoryBuilder.withUrl("r2dbc:h2:file:///" + UUID.randomUUID()).build())) - .isFalse(); + .isEmbedded(ConnectionFactoryBuilder.withUrl("r2dbc:h2:file:///" + UUID.randomUUID()).build())).isFalse(); } @Test void whenPoolIsBasedByH2InMemoryThenIsEmbeddedReturnsTrue() { assertThat(EmbeddedDatabaseConnection - .isEmbedded(ConnectionFactoryBuilder.withUrl("r2dbc:pool:h2:mem:///" + UUID.randomUUID()).build())) - .isTrue(); + .isEmbedded(ConnectionFactoryBuilder.withUrl("r2dbc:pool:h2:mem:///" + UUID.randomUUID()).build())) + .isTrue(); } @Test void whenPoolIsBasedByH2WithFileStorageThenIsEmbeddedReturnsFalse() { assertThat(EmbeddedDatabaseConnection - .isEmbedded(ConnectionFactoryBuilder.withUrl("r2dbc:pool:h2:file:///" + UUID.randomUUID()).build())) - .isFalse(); + .isEmbedded(ConnectionFactoryBuilder.withUrl("r2dbc:pool:h2:file:///" + UUID.randomUUID()).build())) + .isFalse(); } @Test void whenConnectionFactoryIsNotOptionsCapableThenIsEmbeddedThrows() { assertThatIllegalArgumentException() - .isThrownBy(() -> EmbeddedDatabaseConnection - .isEmbedded(ConnectionFactories.get("r2dbc:pool:h2:mem:///" + UUID.randomUUID()))) - .withMessage("Cannot determine database's type as ConnectionFactory is not options-capable. To be " - + "options-capable, a ConnectionFactory should be created with " - + "org.springframework.boot.r2dbc.ConnectionFactoryBuilder"); + .isThrownBy(() -> EmbeddedDatabaseConnection + .isEmbedded(ConnectionFactories.get("r2dbc:pool:h2:mem:///" + UUID.randomUUID()))) + .withMessage("Cannot determine database's type as ConnectionFactory is not options-capable. To be " + + "options-capable, a ConnectionFactory should be created with " + + "org.springframework.boot.r2dbc.ConnectionFactoryBuilder"); } static Stream urlParameters() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/init/R2dbcScriptDatabaseInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/init/R2dbcScriptDatabaseInitializerTests.java index b22d4204a5..1cdb243a1e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/init/R2dbcScriptDatabaseInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/init/R2dbcScriptDatabaseInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,15 +35,17 @@ class R2dbcScriptDatabaseInitializerTests extends AbstractScriptDatabaseInitializerTests { private final ConnectionFactory embeddedConnectionFactory = ConnectionFactoryBuilder - .withUrl("r2dbc:h2:mem:///" + UUID.randomUUID() + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") - .build(); + .withUrl("r2dbc:h2:mem:///" + UUID.randomUUID() + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") + .build(); private final ConnectionFactory standaloneConnectionFactory = ConnectionFactoryBuilder - .withUrl("r2dbc:h2:file:///" - + new BuildOutput(R2dbcScriptDatabaseInitializerTests.class).getRootLocation().getAbsolutePath() + .withUrl( + "r2dbc:h2:file:///" + + new BuildOutput(R2dbcScriptDatabaseInitializerTests.class).getRootLocation() + .getAbsolutePath() .replace('\\', '/') - + "/" + UUID.randomUUID() + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") - .build(); + + "/" + UUID.randomUUID() + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") + .build(); @Override protected R2dbcScriptDatabaseInitializer createEmbeddedDatabaseInitializer( @@ -68,8 +70,12 @@ class R2dbcScriptDatabaseInitializerTests } private int numberOfRows(ConnectionFactory connectionFactory, String sql) { - return DatabaseClient.create(connectionFactory).sql(sql).map((row, metadata) -> row.get(0)).first() - .map((number) -> ((Number) number).intValue()).block(); + return DatabaseClient.create(connectionFactory) + .sql(sql) + .map((row, metadata) -> row.get(0)) + .first() + .map((number) -> ((Number) number).intValue()) + .block(); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/reactor/DebugAgentEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/reactor/DebugAgentEnvironmentPostProcessorTests.java index 034d7632f1..dd5e90ebcc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/reactor/DebugAgentEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/reactor/DebugAgentEnvironmentPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ class DebugAgentEnvironmentPostProcessorTests { InstrumentedFluxProvider fluxProvider = new InstrumentedFluxProvider(); Flux flux = fluxProvider.newFluxJust(); assertThat(Scannable.from(flux).stepName()) - .startsWith("Flux.just ⇢ at org.springframework.boot.reactor.InstrumentedFluxProvider.newFluxJust"); + .startsWith("Flux.just ⇢ at org.springframework.boot.reactor.InstrumentedFluxProvider.newFluxJust"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactoryTests.java index 4c739922fd..dfdf965fff 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -137,7 +137,7 @@ class NettyRSocketServerFactoryTests { for (int i = 0; i < customizers.length; i++) { customizers[i] = mock(RSocketServerCustomizer.class); will((invocation) -> invocation.getArgument(0)).given(customizers[i]) - .customize(any(io.rsocket.core.RSocketServer.class)); + .customize(any(io.rsocket.core.RSocketServer.class)); } factory.setRSocketServerCustomizers(Arrays.asList(customizers)); this.server = factory.create(new EchoRequestResponseAcceptor()); @@ -242,7 +242,7 @@ class NettyRSocketServerFactoryTests { String payload = "test payload"; Mono responseMono = this.requester.route("test").data(payload).retrieveMono(String.class); StepVerifier.create(responseMono) - .verifyErrorSatisfies((ex) -> assertThat(ex).isInstanceOf(ClosedChannelException.class)); + .verifyErrorSatisfies((ex) -> assertThat(ex).isInstanceOf(ClosedChannelException.class)); } private RSocketRequester createRSocketTcpClient() { @@ -259,13 +259,14 @@ class NettyRSocketServerFactoryTests { private RSocketRequester createSecureRSocketWebSocketClient() { return createRSocketRequesterBuilder() - .transport(WebsocketClientTransport.create(createSecureHttpClient(), "/")); + .transport(WebsocketClientTransport.create(createSecureHttpClient(), "/")); } private HttpClient createSecureHttpClient() { HttpClient httpClient = createHttpClient(); - Http11SslContextSpec sslContextSpec = Http11SslContextSpec.forClient().configure( - (builder) -> builder.sslProvider(SslProvider.JDK).trustManager(InsecureTrustManagerFactory.INSTANCE)); + Http11SslContextSpec sslContextSpec = Http11SslContextSpec.forClient() + .configure((builder) -> builder.sslProvider(SslProvider.JDK) + .trustManager(InsecureTrustManagerFactory.INSTANCE)); return httpClient.secure((spec) -> spec.sslContext(sslContextSpec)); } @@ -277,8 +278,9 @@ class NettyRSocketServerFactoryTests { private TcpClient createSecureTcpClient() { TcpClient tcpClient = createTcpClient(); - Http11SslContextSpec sslContextSpec = Http11SslContextSpec.forClient().configure( - (builder) -> builder.sslProvider(SslProvider.JDK).trustManager(InsecureTrustManagerFactory.INSTANCE)); + Http11SslContextSpec sslContextSpec = Http11SslContextSpec.forClient() + .configure((builder) -> builder.sslProvider(SslProvider.JDK) + .trustManager(InsecureTrustManagerFactory.INSTANCE)); return tcpClient.secure((spec) -> spec.sslContext(sslContextSpec)); } @@ -289,9 +291,11 @@ class NettyRSocketServerFactoryTests { } private RSocketRequester.Builder createRSocketRequesterBuilder() { - RSocketStrategies strategies = RSocketStrategies.builder().decoder(StringDecoder.allMimeTypes()) - .encoder(CharSequenceEncoder.allMimeTypes()) - .dataBufferFactory(new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT)).build(); + RSocketStrategies strategies = RSocketStrategies.builder() + .decoder(StringDecoder.allMimeTypes()) + .encoder(CharSequenceEncoder.allMimeTypes()) + .dataBufferFactory(new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT)) + .build(); return RSocketRequester.builder().rsocketStrategies(strategies); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java index 44955a29ec..a78ea4e37b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,8 @@ class ApplicationContextServerWebExchangeMatcherTests { @Test void createWhenContextClassIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestApplicationContextServerWebExchangeMatcher<>(null)) - .withMessageContaining("Context class must not be null"); + .isThrownBy(() -> new TestApplicationContextServerWebExchangeMatcher<>(null)) + .withMessageContaining("Context class must not be null"); } @Test @@ -58,7 +58,8 @@ class ApplicationContextServerWebExchangeMatcherTests { ServerWebExchange exchange = createExchange(); StaticApplicationContext context = (StaticApplicationContext) exchange.getApplicationContext(); assertThat(new TestApplicationContextServerWebExchangeMatcher<>(ApplicationContext.class) - .callMatchesAndReturnProvidedContext(exchange).get()).isEqualTo(context); + .callMatchesAndReturnProvidedContext(exchange) + .get()).isEqualTo(context); } @Test @@ -67,14 +68,15 @@ class ApplicationContextServerWebExchangeMatcherTests { StaticApplicationContext context = (StaticApplicationContext) exchange.getApplicationContext(); context.registerSingleton("existingBean", ExistingBean.class); assertThat(new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) - .callMatchesAndReturnProvidedContext(exchange).get()).isEqualTo(context.getBean(ExistingBean.class)); + .callMatchesAndReturnProvidedContext(exchange) + .get()).isEqualTo(context.getBean(ExistingBean.class)); } @Test void matchesWhenContextClassIsMissingBeanShouldProvideException() { ServerWebExchange exchange = createExchange(); Supplier supplier = new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) - .callMatchesAndReturnProvidedContext(exchange); + .callMatchesAndReturnProvidedContext(exchange); assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(supplier::get); } @@ -82,9 +84,9 @@ class ApplicationContextServerWebExchangeMatcherTests { void matchesWhenContextIsNull() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path").build()); assertThatIllegalStateException() - .isThrownBy(() -> new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) - .callMatchesAndReturnProvidedContext(exchange)) - .withMessageContaining("No ApplicationContext found on ServerWebExchange."); + .isThrownBy(() -> new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) + .callMatchesAndReturnProvidedContext(exchange)) + .withMessageContaining("No ApplicationContext found on ServerWebExchange."); } private ServerWebExchange createExchange() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java index 64288b66cb..aae71b3058 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,14 +48,15 @@ class ApplicationContextRequestMatcherTests { @Test void createWhenContextClassIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new TestApplicationContextRequestMatcher<>(null)) - .withMessageContaining("Context class must not be null"); + .withMessageContaining("Context class must not be null"); } @Test void matchesWhenContextClassIsApplicationContextShouldProvideContext() { StaticWebApplicationContext context = createWebApplicationContext(); assertThat(new TestApplicationContextRequestMatcher<>(ApplicationContext.class) - .callMatchesAndReturnProvidedContext(context).get()).isEqualTo(context); + .callMatchesAndReturnProvidedContext(context) + .get()).isEqualTo(context); } @Test @@ -63,14 +64,15 @@ class ApplicationContextRequestMatcherTests { StaticWebApplicationContext context = createWebApplicationContext(); context.registerSingleton("existingBean", ExistingBean.class); assertThat(new TestApplicationContextRequestMatcher<>(ExistingBean.class) - .callMatchesAndReturnProvidedContext(context).get()).isEqualTo(context.getBean(ExistingBean.class)); + .callMatchesAndReturnProvidedContext(context) + .get()).isEqualTo(context.getBean(ExistingBean.class)); } @Test void matchesWhenContextClassIsBeanThatDoesNotExistShouldSupplyException() { StaticWebApplicationContext context = createWebApplicationContext(); Supplier supplier = new TestApplicationContextRequestMatcher<>(ExistingBean.class) - .callMatchesAndReturnProvidedContext(context); + .callMatchesAndReturnProvidedContext(context); assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(supplier::get); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/sql/init/AbstractScriptDatabaseInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/sql/init/AbstractScriptDatabaseInitializerTests.java index a3854f440a..3689bca1dd 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/sql/init/AbstractScriptDatabaseInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/sql/init/AbstractScriptDatabaseInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,7 +69,7 @@ public abstract class AbstractScriptDatabaseInitializerTests assertThat(dependencies).containsExactly("alpha")); @@ -108,7 +108,7 @@ class DatabaseInitializationDependencyConfigurerTests { context.refresh(); assertThat(ConstructorInjectionDatabaseInitializerDetector.environment).isEqualTo(this.environment); assertThat(ConstructorInjectionDependsOnDatabaseInitializationDetector.environment) - .isEqualTo(this.environment); + .isEqualTo(this.environment); }); } @@ -121,16 +121,16 @@ class DatabaseInitializationDependencyConfigurerTests { context.registerBeanDefinition("alpha", alpha); context.registerBeanDefinition("bravo", bravo); given(MockDatabaseInitializerDetector.instance.detect(context.getBeanFactory())) - .willReturn(Collections.singleton("alpha")); + .willReturn(Collections.singleton("alpha")); given(MockedDependsOnDatabaseInitializationDetector.instance.detect(context.getBeanFactory())) - .willReturn(Collections.singleton("bravo")); + .willReturn(Collections.singleton("bravo")); context.register(DependencyConfigurerConfiguration.class); context.refresh(); assertThat(alpha.getAttribute(DatabaseInitializerDetector.class.getName())) - .isEqualTo(MockDatabaseInitializerDetector.class.getName()); + .isEqualTo(MockDatabaseInitializerDetector.class.getName()); assertThat(bravo.getAttribute(DatabaseInitializerDetector.class.getName())).isNull(); - then(MockDatabaseInitializerDetector.instance).should().detectionComplete(context.getBeanFactory(), - Collections.singleton("alpha")); + then(MockDatabaseInitializerDetector.instance).should() + .detectionComplete(context.getBeanFactory(), Collections.singleton("alpha")); assertThat(bravo.getDependsOn()).containsExactly("alpha"); }); } @@ -148,13 +148,13 @@ class DatabaseInitializationDependencyConfigurerTests { MockedDependsOnDatabaseInitializationDetector.class), (context) -> { given(MockDatabaseInitializerDetector.instance.detect(context.getBeanFactory())) - .willReturn(Collections.singleton("alpha")); + .willReturn(Collections.singleton("alpha")); given(OrderedNearLowestMockDatabaseInitializerDetector.instance.detect(context.getBeanFactory())) - .willReturn(new LinkedHashSet<>(Arrays.asList("bravo1", "bravo2"))); + .willReturn(new LinkedHashSet<>(Arrays.asList("bravo1", "bravo2"))); given(OrderedLowestMockDatabaseInitializerDetector.instance.detect(context.getBeanFactory())) - .willReturn(new LinkedHashSet<>(Arrays.asList("charlie"))); + .willReturn(new LinkedHashSet<>(Arrays.asList("charlie"))); given(MockedDependsOnDatabaseInitializationDetector.instance.detect(context.getBeanFactory())) - .willReturn(Collections.singleton("delta")); + .willReturn(Collections.singleton("delta")); context.registerBeanDefinition("alpha", alpha); context.registerBeanDefinition("bravo1", bravo1); context.registerBeanDefinition("bravo2", bravo2); @@ -298,7 +298,7 @@ class DatabaseInitializationDependencyConfigurerTests { } else if (DependsOnDatabaseInitializationDetector.class.isAssignableFrom(detector)) { this.dependsOnDatabaseInitializationDetectors - .add((Class) detector); + .add((Class) detector); } else { throw new IllegalArgumentException("Unsupported detector type '" + detector.getName() + "'"); @@ -314,8 +314,10 @@ class DatabaseInitializationDependencyConfigurerTests { properties.put(DatabaseInitializerDetector.class.getName(), String.join(",", this.databaseInitializerDetectors.stream().map(Class::getName).collect(Collectors.toList()))); properties.put(DependsOnDatabaseInitializationDetector.class.getName(), - String.join(",", this.dependsOnDatabaseInitializationDetectors.stream().map(Class::getName) - .collect(Collectors.toList()))); + String.join(",", + this.dependsOnDatabaseInitializationDetectors.stream() + .map(Class::getName) + .collect(Collectors.toList()))); File springFactories = new File(this.temp, "spring.factories"); try (FileWriter writer = new FileWriter(springFactories)) { properties.store(writer, ""); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java index 5f0b7262f4..1acf55f057 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,7 @@ class ApplicationPidTests { void throwIllegalStateWritingMissingPid() { ApplicationPid pid = new ApplicationPid(null); assertThatIllegalStateException().isThrownBy(() -> pid.write(new File(this.tempDir, "pid"))) - .withMessageContaining("No PID available"); + .withMessageContaining("No PID available"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationTempTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationTempTests.java index bbbcc81804..1b283a0fef 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationTempTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationTempTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,7 +87,8 @@ class ApplicationTempTests { private void assertDirectoryPermissions(Path path) throws IOException { Set permissions = Files.getFileAttributeView(path, PosixFileAttributeView.class) - .readAttributes().permissions(); + .readAttributes() + .permissions(); assertThat(permissions).containsExactlyInAnyOrder(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java index 183a491934..3b74a8db9f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,12 @@ class TaskExecutorBuilderTests { @Test void poolSettingsShouldApply() { - ThreadPoolTaskExecutor executor = this.builder.queueCapacity(10).corePoolSize(4).maxPoolSize(8) - .allowCoreThreadTimeOut(true).keepAlive(Duration.ofMinutes(1)).build(); + ThreadPoolTaskExecutor executor = this.builder.queueCapacity(10) + .corePoolSize(4) + .maxPoolSize(8) + .allowCoreThreadTimeOut(true) + .keepAlive(Duration.ofMinutes(1)) + .build(); assertThat(executor).hasFieldOrPropertyWithValue("queueCapacity", 10); assertThat(executor.getCorePoolSize()).isEqualTo(4); assertThat(executor.getMaxPoolSize()).isEqualTo(8); @@ -81,14 +85,14 @@ class TaskExecutorBuilderTests { @Test void customizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.builder.customizers((TaskExecutorCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .withMessageContaining("Customizers must not be null"); } @Test void customizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.customizers((Set) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.customizers((Set) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -102,19 +106,26 @@ class TaskExecutorBuilderTests { void customizersShouldBeAppliedLast() { TaskDecorator taskDecorator = mock(TaskDecorator.class); ThreadPoolTaskExecutor executor = spy(new ThreadPoolTaskExecutor()); - this.builder.queueCapacity(10).corePoolSize(4).maxPoolSize(8).allowCoreThreadTimeOut(true) - .keepAlive(Duration.ofMinutes(1)).awaitTermination(true).awaitTerminationPeriod(Duration.ofSeconds(30)) - .threadNamePrefix("test-").taskDecorator(taskDecorator).additionalCustomizers((taskExecutor) -> { - then(taskExecutor).should().setQueueCapacity(10); - then(taskExecutor).should().setCorePoolSize(4); - then(taskExecutor).should().setMaxPoolSize(8); - then(taskExecutor).should().setAllowCoreThreadTimeOut(true); - then(taskExecutor).should().setKeepAliveSeconds(60); - then(taskExecutor).should().setWaitForTasksToCompleteOnShutdown(true); - then(taskExecutor).should().setAwaitTerminationSeconds(30); - then(taskExecutor).should().setThreadNamePrefix("test-"); - then(taskExecutor).should().setTaskDecorator(taskDecorator); - }); + this.builder.queueCapacity(10) + .corePoolSize(4) + .maxPoolSize(8) + .allowCoreThreadTimeOut(true) + .keepAlive(Duration.ofMinutes(1)) + .awaitTermination(true) + .awaitTerminationPeriod(Duration.ofSeconds(30)) + .threadNamePrefix("test-") + .taskDecorator(taskDecorator) + .additionalCustomizers((taskExecutor) -> { + then(taskExecutor).should().setQueueCapacity(10); + then(taskExecutor).should().setCorePoolSize(4); + then(taskExecutor).should().setMaxPoolSize(8); + then(taskExecutor).should().setAllowCoreThreadTimeOut(true); + then(taskExecutor).should().setKeepAliveSeconds(60); + then(taskExecutor).should().setWaitForTasksToCompleteOnShutdown(true); + then(taskExecutor).should().setAwaitTerminationSeconds(30); + then(taskExecutor).should().setThreadNamePrefix("test-"); + then(taskExecutor).should().setTaskDecorator(taskDecorator); + }); this.builder.configure(executor); } @@ -123,7 +134,8 @@ class TaskExecutorBuilderTests { TaskExecutorCustomizer customizer1 = mock(TaskExecutorCustomizer.class); TaskExecutorCustomizer customizer2 = mock(TaskExecutorCustomizer.class); ThreadPoolTaskExecutor executor = this.builder.customizers(customizer1) - .customizers(Collections.singleton(customizer2)).build(); + .customizers(Collections.singleton(customizer2)) + .build(); then(customizer1).shouldHaveNoInteractions(); then(customizer2).should().customize(executor); } @@ -131,23 +143,24 @@ class TaskExecutorBuilderTests { @Test void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalCustomizers((TaskExecutorCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.additionalCustomizers((TaskExecutorCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalCustomizers((Set) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.additionalCustomizers((Set) null)) + .withMessageContaining("Customizers must not be null"); } @Test void additionalCustomizersShouldAddToExisting() { TaskExecutorCustomizer customizer1 = mock(TaskExecutorCustomizer.class); TaskExecutorCustomizer customizer2 = mock(TaskExecutorCustomizer.class); - ThreadPoolTaskExecutor executor = this.builder.customizers(customizer1).additionalCustomizers(customizer2) - .build(); + ThreadPoolTaskExecutor executor = this.builder.customizers(customizer1) + .additionalCustomizers(customizer2) + .build(); then(customizer1).should().customize(executor); then(customizer2).should().customize(executor); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java index b9f8786f43..d4988199aa 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,15 +67,15 @@ class TaskSchedulerBuilderTests { @Test void customizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.customizers((TaskSchedulerCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.customizers((TaskSchedulerCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test void customizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.customizers((Set) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.customizers((Set) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -100,7 +100,8 @@ class TaskSchedulerBuilderTests { TaskSchedulerCustomizer customizer1 = mock(TaskSchedulerCustomizer.class); TaskSchedulerCustomizer customizer2 = mock(TaskSchedulerCustomizer.class); ThreadPoolTaskScheduler scheduler = this.builder.customizers(customizer1) - .customizers(Collections.singleton(customizer2)).build(); + .customizers(Collections.singleton(customizer2)) + .build(); then(customizer1).shouldHaveNoInteractions(); then(customizer2).should().customize(scheduler); } @@ -108,23 +109,24 @@ class TaskSchedulerBuilderTests { @Test void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalCustomizers((TaskSchedulerCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.additionalCustomizers((TaskSchedulerCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalCustomizers((Set) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.additionalCustomizers((Set) null)) + .withMessageContaining("Customizers must not be null"); } @Test void additionalCustomizersShouldAddToExisting() { TaskSchedulerCustomizer customizer1 = mock(TaskSchedulerCustomizer.class); TaskSchedulerCustomizer customizer2 = mock(TaskSchedulerCustomizer.class); - ThreadPoolTaskScheduler scheduler = this.builder.customizers(customizer1).additionalCustomizers(customizer2) - .build(); + ThreadPoolTaskScheduler scheduler = this.builder.customizers(customizer1) + .additionalCustomizers(customizer2) + .build(); then(customizer1).should().customize(scheduler); then(customizer2).should().customize(scheduler); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/InstantiatorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/InstantiatorTests.java index 25c6f944b7..ca007c7ea6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/InstantiatorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/InstantiatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -83,7 +83,8 @@ class InstantiatorTests { @Test void instantiateTypesCreatesInstance() { WithDefaultConstructor instance = createInstantiator(WithDefaultConstructor.class) - .instantiateTypes(Collections.singleton(WithDefaultConstructor.class)).get(0); + .instantiateTypes(Collections.singleton(WithDefaultConstructor.class)) + .get(0); assertThat(instance).isInstanceOf(WithDefaultConstructor.class); } @@ -99,25 +100,26 @@ class InstantiatorTests { }; WithDefaultConstructor instance = createInstantiator(WithDefaultConstructor.class) - .instantiate(classLoader, Collections.singleton(WithDefaultConstructorSubclass.class.getName())).get(0); + .instantiate(classLoader, Collections.singleton(WithDefaultConstructorSubclass.class.getName())) + .get(0); assertThat(instance.getClass().getClassLoader()).isSameAs(classLoader); } @Test void createWhenWrongTypeThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> createInstantiator(WithDefaultConstructor.class) - .instantiate(Collections.singleton(WithAdditionalConstructor.class.getName()))) - .withMessageContaining("Unable to instantiate"); + .isThrownBy(() -> createInstantiator(WithDefaultConstructor.class) + .instantiate(Collections.singleton(WithAdditionalConstructor.class.getName()))) + .withMessageContaining("Unable to instantiate"); } @Test void createWithFailureHandlerInvokesFailureHandler() { assertThatIllegalStateException() - .isThrownBy(() -> new Instantiator<>(WithDefaultConstructor.class, (availableParameters) -> { - }, new CustomFailureHandler()) - .instantiate(Collections.singleton(WithAdditionalConstructor.class.getName()))) - .withMessageContaining("custom failure handler message"); + .isThrownBy(() -> new Instantiator<>(WithDefaultConstructor.class, (availableParameters) -> { + }, new CustomFailureHandler()) + .instantiate(Collections.singleton(WithAdditionalConstructor.class.getName()))) + .withMessageContaining("custom failure handler message"); } private T createInstance(Class type) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java index 374642980e..0c3c50f531 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,13 +46,13 @@ class LambdaSafeTests { @Test void callbackWhenCallbackTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> LambdaSafe.callback(null, new Object(), null)) - .withMessageContaining("CallbackType must not be null"); + .withMessageContaining("CallbackType must not be null"); } @Test void callbackWhenCallbackInstanceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> LambdaSafe.callback(Object.class, null, null)) - .withMessageContaining("CallbackInstance must not be null"); + .withMessageContaining("CallbackInstance must not be null"); } @Test @@ -104,7 +104,7 @@ class LambdaSafeTests { GenericMultiArgCallback callbackInstance = (n, s, b) -> fail("Should not get here"); String argument = "foo"; LambdaSafe.callback(GenericMultiArgCallback.class, callbackInstance, argument) - .invoke((c) -> c.handle(1, argument, false)); + .invoke((c) -> c.handle(1, argument, false)); } @Test @@ -113,7 +113,7 @@ class LambdaSafeTests { String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(123); InvocationResult result = LambdaSafe.callback(NonGenericFactory.class, callbackInstance, argument) - .invokeAnd((c) -> c.handle(argument)); + .invokeAnd((c) -> c.handle(argument)); assertThat(result.hasResult()).isTrue(); assertThat(result.get()).isEqualTo(123); } @@ -125,7 +125,7 @@ class LambdaSafeTests { String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(123); InvocationResult result = LambdaSafe.callback(GenericFactory.class, callbackInstance, argument) - .invokeAnd((c) -> c.handle(argument)); + .invokeAnd((c) -> c.handle(argument)); assertThat(result.hasResult()).isTrue(); assertThat(result.get()).isEqualTo(123); } @@ -137,7 +137,7 @@ class LambdaSafeTests { String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(null); InvocationResult result = LambdaSafe.callback(GenericFactory.class, callbackInstance, argument) - .invokeAnd((c) -> c.handle(argument)); + .invokeAnd((c) -> c.handle(argument)); assertThat(result.hasResult()).isTrue(); assertThat(result.get()).isNull(); } @@ -149,7 +149,7 @@ class LambdaSafeTests { StringBuilder argument = new StringBuilder("foo"); given(callbackInstance.handle(any(StringBuilder.class))).willReturn(123); InvocationResult result = LambdaSafe.callback(GenericFactory.class, callbackInstance, argument) - .invokeAnd((c) -> c.handle(argument)); + .invokeAnd((c) -> c.handle(argument)); then(callbackInstance).should().handle(argument); assertThat(result.hasResult()).isTrue(); assertThat(result.get()).isEqualTo(123); @@ -161,7 +161,7 @@ class LambdaSafeTests { GenericFactory callbackInstance = mock(StringBuilderFactory.class); String argument = "foo"; InvocationResult result = LambdaSafe.callback(GenericFactory.class, callbackInstance, argument) - .invokeAnd((c) -> c.handle(argument)); + .invokeAnd((c) -> c.handle(argument)); assertThat(result.hasResult()).isFalse(); then(callbackInstance).shouldHaveNoInteractions(); } @@ -175,7 +175,7 @@ class LambdaSafeTests { }; String argument = "foo"; InvocationResult result = LambdaSafe.callback(GenericFactory.class, callbackInstance, argument) - .invokeAnd((c) -> c.handle(argument)); + .invokeAnd((c) -> c.handle(argument)); assertThat(result.hasResult()).isFalse(); } @@ -188,7 +188,7 @@ class LambdaSafeTests { }; String argument = "foo"; InvocationResult result = LambdaSafe.callback(GenericMultiArgFactory.class, callbackInstance, argument) - .invokeAnd((c) -> c.handle(1, argument, false)); + .invokeAnd((c) -> c.handle(1, argument, false)); assertThat(result.hasResult()).isFalse(); } @@ -197,7 +197,7 @@ class LambdaSafeTests { NonGenericCallback callbackInstance = mock(NonGenericCallback.class); String argument = "foo"; LambdaSafe.callbacks(NonGenericCallback.class, Collections.singleton(callbackInstance), argument) - .invoke((c) -> c.handle(argument)); + .invoke((c) -> c.handle(argument)); then(callbackInstance).should().handle(argument); } @@ -207,7 +207,7 @@ class LambdaSafeTests { StringCallback callbackInstance = mock(StringCallback.class); String argument = "foo"; LambdaSafe.callbacks(GenericCallback.class, Collections.singleton(callbackInstance), argument) - .invoke((c) -> c.handle(argument)); + .invoke((c) -> c.handle(argument)); then(callbackInstance).should().handle(argument); } @@ -217,7 +217,7 @@ class LambdaSafeTests { StringBuilderCallback callbackInstance = mock(StringBuilderCallback.class); StringBuilder argument = new StringBuilder("foo"); LambdaSafe.callbacks(GenericCallback.class, Collections.singleton(callbackInstance), argument) - .invoke((c) -> c.handle(argument)); + .invoke((c) -> c.handle(argument)); then(callbackInstance).should().handle(argument); } @@ -227,7 +227,7 @@ class LambdaSafeTests { GenericCallback callbackInstance = mock(StringBuilderCallback.class); String argument = "foo"; LambdaSafe.callbacks(GenericCallback.class, Collections.singleton(callbackInstance), argument) - .invoke((c) -> c.handle(null)); + .invoke((c) -> c.handle(null)); then(callbackInstance).shouldHaveNoInteractions(); } @@ -237,7 +237,7 @@ class LambdaSafeTests { GenericCallback callbackInstance = (s) -> fail("Should not get here"); String argument = "foo"; LambdaSafe.callbacks(GenericCallback.class, Collections.singleton(callbackInstance), argument) - .invoke((c) -> c.handle(argument)); + .invoke((c) -> c.handle(argument)); } @Test @@ -246,7 +246,7 @@ class LambdaSafeTests { GenericMultiArgCallback callbackInstance = (n, s, b) -> fail("Should not get here"); String argument = "foo"; LambdaSafe.callbacks(GenericMultiArgCallback.class, Collections.singleton(callbackInstance), argument) - .invoke((c) -> c.handle(1, argument, false)); + .invoke((c) -> c.handle(1, argument, false)); } @Test @@ -255,8 +255,8 @@ class LambdaSafeTests { String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(123); Stream result = LambdaSafe - .callbacks(NonGenericFactory.class, Collections.singleton(callbackInstance), argument) - .invokeAnd((c) -> c.handle(argument)); + .callbacks(NonGenericFactory.class, Collections.singleton(callbackInstance), argument) + .invokeAnd((c) -> c.handle(argument)); assertThat(result).containsExactly(123); } @@ -267,8 +267,8 @@ class LambdaSafeTests { String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(123); Stream result = LambdaSafe - .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) - .invokeAnd((c) -> c.handle(argument)); + .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) + .invokeAnd((c) -> c.handle(argument)); assertThat(result).containsExactly(123); } @@ -279,8 +279,8 @@ class LambdaSafeTests { String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(null); Stream result = LambdaSafe - .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) - .invokeAnd((c) -> c.handle(argument)); + .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) + .invokeAnd((c) -> c.handle(argument)); assertThat(result).containsExactly((Integer) null); } @@ -291,8 +291,8 @@ class LambdaSafeTests { StringBuilder argument = new StringBuilder("foo"); given(callbackInstance.handle(any(StringBuilder.class))).willReturn(123); Stream result = LambdaSafe - .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) - .invokeAnd((c) -> c.handle(argument)); + .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) + .invokeAnd((c) -> c.handle(argument)); assertThat(result).containsExactly(123); } @@ -302,8 +302,8 @@ class LambdaSafeTests { GenericFactory callbackInstance = mock(StringBuilderFactory.class); String argument = "foo"; Stream result = LambdaSafe - .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) - .invokeAnd((c) -> c.handle(argument)); + .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) + .invokeAnd((c) -> c.handle(argument)); assertThat(result).isEmpty(); } @@ -316,8 +316,8 @@ class LambdaSafeTests { }; String argument = "foo"; Stream result = LambdaSafe - .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) - .invokeAnd((c) -> (c).handle(argument)); + .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) + .invokeAnd((c) -> (c).handle(argument)); assertThat(result).isEmpty(); } @@ -330,8 +330,8 @@ class LambdaSafeTests { }; String argument = "foo"; Stream result = LambdaSafe - .callbacks(GenericMultiArgFactory.class, Collections.singleton(callbackInstance), argument) - .invokeAnd((c) -> c.handle(1, argument, false)); + .callbacks(GenericMultiArgFactory.class, Collections.singleton(callbackInstance), argument) + .invokeAnd((c) -> c.handle(1, argument, false)); assertThat(result).isEmpty(); } @@ -353,7 +353,7 @@ class LambdaSafeTests { callbackInstances.add(callback5); String argument = "foo"; Stream result = LambdaSafe.callbacks(GenericFactory.class, callbackInstances, argument) - .invokeAnd((c) -> c.handle(argument)); + .invokeAnd((c) -> c.handle(argument)); assertThat(result).containsExactly(1, 2, 4); } @@ -362,8 +362,9 @@ class LambdaSafeTests { void callbackWithFilterShouldUseFilter() { GenericCallback callbackInstance = mock(StringBuilderCallback.class); String argument = "foo"; - LambdaSafe.callback(GenericCallback.class, callbackInstance, argument).withFilter(Filter.allowAll()) - .invoke((c) -> c.handle(null)); + LambdaSafe.callback(GenericCallback.class, callbackInstance, argument) + .withFilter(Filter.allowAll()) + .invoke((c) -> c.handle(null)); then(callbackInstance).should().handle(null); } @@ -374,11 +375,12 @@ class LambdaSafeTests { given(logger.isDebugEnabled()).willReturn(true); GenericCallback callbackInstance = (s) -> fail("Should not get here"); String argument = "foo"; - LambdaSafe.callback(GenericCallback.class, callbackInstance, argument).withLogger(logger) - .invoke((c) -> c.handle(argument)); - then(logger).should().debug( - contains("Non-matching CharSequence type for callback LambdaSafeTests.GenericCallback"), - any(Throwable.class)); + LambdaSafe.callback(GenericCallback.class, callbackInstance, argument) + .withLogger(logger) + .invoke((c) -> c.handle(argument)); + then(logger).should() + .debug(contains("Non-matching CharSequence type for callback LambdaSafeTests.GenericCallback"), + any(Throwable.class)); } interface NonGenericCallback { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryTests.java index e45c92679c..e6024535b0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ class MessageInterpolatorFactoryTests { assertThat(interpolator).isInstanceOf(MessageSourceMessageInterpolator.class); assertThat(interpolator).hasFieldOrPropertyWithValue("messageSource", messageSource); assertThat(ReflectionTestUtils.getField(interpolator, "messageInterpolator")) - .isInstanceOf(ResourceBundleMessageInterpolator.class); + .isInstanceOf(ResourceBundleMessageInterpolator.class); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java index 817c3586fc..91beb0462e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,8 @@ class MessageInterpolatorFactoryWithoutElIntegrationTests { void defaultMessageInterpolatorShouldFail() { // Sanity test assertThatExceptionOfType(ValidationException.class) - .isThrownBy(Validation.byDefaultProvider().configure()::getDefaultMessageInterpolator) - .withMessageContaining("javax.el.ExpressionFactory"); + .isThrownBy(Validation.byDefaultProvider().configure()::getDefaultMessageInterpolator) + .withMessageContaining("javax.el.ExpressionFactory"); } @Test @@ -61,7 +61,7 @@ class MessageInterpolatorFactoryWithoutElIntegrationTests { assertThat(interpolator).isInstanceOf(MessageSourceMessageInterpolator.class); assertThat(interpolator).hasFieldOrPropertyWithValue("messageSource", messageSource); assertThat(ReflectionTestUtils.getField(interpolator, "messageInterpolator")) - .isInstanceOf(ParameterMessageInterpolator.class); + .isInstanceOf(ParameterMessageInterpolator.class); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorIntegrationTests.java index 9d0809e03e..c44082d00a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,7 +87,7 @@ class MessageSourceMessageInterpolatorIntegrationTests { @Test void recursion() { assertThatThrownBy(() -> validate("recursion")) - .hasStackTraceContaining("Circular reference '{recursion -> middle -> recursion}'"); + .hasStackTraceContaining("Circular reference '{recursion -> middle -> recursion}'"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorTests.java index f9fd339466..f2cf5e7ae4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,7 +56,7 @@ class MessageSourceMessageInterpolatorTests { void interpolateWhenParametersAreUnknownShouldLeaveThemUnchanged() { this.messageSource.addMessage("top", Locale.getDefault(), "{child}+{child}"); assertThat(this.interpolator.interpolate("{foo}{top}{bar}", this.context)) - .isEqualTo("{foo}{child}+{child}{bar}"); + .isEqualTo("{foo}{child}+{child}{bar}"); } @Test @@ -64,7 +64,7 @@ class MessageSourceMessageInterpolatorTests { this.messageSource.setUseCodeAsDefaultMessage(true); this.messageSource.addMessage("top", Locale.getDefault(), "{child}+{child}"); assertThat(this.interpolator.interpolate("{foo}{top}{bar}", this.context)) - .isEqualTo("{foo}{child}+{child}{bar}"); + .isEqualTo("{foo}{child}+{child}{bar}"); } @Test @@ -108,7 +108,7 @@ class MessageSourceMessageInterpolatorTests { this.messageSource.addMessage("b", Locale.getDefault(), "{c}"); this.messageSource.addMessage("c", Locale.getDefault(), "{a}"); assertThatIllegalArgumentException().isThrownBy(() -> this.interpolator.interpolate("{a}", this.context)) - .withMessage("Circular reference '{a -> b -> c -> a}'"); + .withMessage("Circular reference '{a -> b -> c -> a}'"); } private static final class IdentityMessageInterpolator implements MessageInterpolator { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderClientHttpRequestInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderClientHttpRequestInitializerTests.java index b8b4ae2ab5..5e7ff9a91b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderClientHttpRequestInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderClientHttpRequestInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,8 @@ class RestTemplateBuilderClientHttpRequestInitializerTests { @Test void createRequestWhenHasBasicAuthAndNoAuthHeaderAddsHeader() { new RestTemplateBuilderClientHttpRequestInitializer(new BasicAuthentication("spring", "boot", null), - Collections.emptyMap(), Collections.emptySet()).initialize(this.request); + Collections.emptyMap(), Collections.emptySet()) + .initialize(this.request); assertThat(this.request.getHeaders().get(HttpHeaders.AUTHORIZATION)).containsExactly("Basic c3ByaW5nOmJvb3Q="); } @@ -57,7 +58,8 @@ class RestTemplateBuilderClientHttpRequestInitializerTests { void createRequestWhenHasBasicAuthAndExistingAuthHeaderDoesNotAddHeader() { this.request.getHeaders().setBasicAuth("boot", "spring"); new RestTemplateBuilderClientHttpRequestInitializer(new BasicAuthentication("spring", "boot", null), - Collections.emptyMap(), Collections.emptySet()).initialize(this.request); + Collections.emptyMap(), Collections.emptySet()) + .initialize(this.request); assertThat(this.request.getHeaders().get(HttpHeaders.AUTHORIZATION)).doesNotContain("Basic c3ByaW5nOmJvb3Q="); } @@ -69,7 +71,7 @@ class RestTemplateBuilderClientHttpRequestInitializerTests { defaultHeaders.put("two", Arrays.asList("2", "3")); defaultHeaders.put("three", Collections.singletonList("4")); new RestTemplateBuilderClientHttpRequestInitializer(null, defaultHeaders, Collections.emptySet()) - .initialize(this.request); + .initialize(this.request); assertThat(this.request.getHeaders().get("one")).containsExactly("existing"); assertThat(this.request.getHeaders().get("two")).containsExactly("2", "3"); assertThat(this.request.getHeaders().get("three")).containsExactly("4"); @@ -83,7 +85,7 @@ class RestTemplateBuilderClientHttpRequestInitializerTests { customizers.add(mock(RestTemplateRequestCustomizer.class)); customizers.add(mock(RestTemplateRequestCustomizer.class)); new RestTemplateBuilderClientHttpRequestInitializer(null, Collections.emptyMap(), customizers) - .initialize(this.request); + .initialize(this.request); InOrder inOrder = inOrder(customizers.toArray()); for (RestTemplateRequestCustomizer customizer : customizers) { inOrder.verify((RestTemplateRequestCustomizer) customizer).customize(this.request); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java index 230b9c9306..f2f77a2767 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -91,7 +91,7 @@ class RestTemplateBuilderTests { void createWhenCustomizersAreNullShouldThrowException() { RestTemplateCustomizer[] customizers = null; assertThatIllegalArgumentException().isThrownBy(() -> new RestTemplateBuilder(customizers)) - .withMessageContaining("Customizers must not be null"); + .withMessageContaining("Customizers must not be null"); } @Test @@ -125,8 +125,9 @@ class RestTemplateBuilderTests { @Test void rootUriShouldApplyAfterUriTemplateHandler() { UriTemplateHandler uriTemplateHandler = mock(UriTemplateHandler.class); - RestTemplate template = this.builder.uriTemplateHandler(uriTemplateHandler).rootUri("https://example.com") - .build(); + RestTemplate template = this.builder.uriTemplateHandler(uriTemplateHandler) + .rootUri("https://example.com") + .build(); UriTemplateHandler handler = template.getUriTemplateHandler(); handler.expand("/hello"); assertThat(handler).isInstanceOf(RootUriTemplateHandler.class); @@ -136,15 +137,15 @@ class RestTemplateBuilderTests { @Test void messageConvertersWhenConvertersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.messageConverters((HttpMessageConverter[]) null)) - .withMessageContaining("MessageConverters must not be null"); + .isThrownBy(() -> this.builder.messageConverters((HttpMessageConverter[]) null)) + .withMessageContaining("MessageConverters must not be null"); } @Test void messageConvertersCollectionWhenConvertersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.messageConverters((Set>) null)) - .withMessageContaining("MessageConverters must not be null"); + .isThrownBy(() -> this.builder.messageConverters((Set>) null)) + .withMessageContaining("MessageConverters must not be null"); } @Test @@ -156,29 +157,31 @@ class RestTemplateBuilderTests { @Test void messageConvertersShouldReplaceExisting() { RestTemplate template = this.builder.messageConverters(new ResourceHttpMessageConverter()) - .messageConverters(Collections.singleton(this.messageConverter)).build(); + .messageConverters(Collections.singleton(this.messageConverter)) + .build(); assertThat(template.getMessageConverters()).containsOnly(this.messageConverter); } @Test void additionalMessageConvertersWhenConvertersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalMessageConverters((HttpMessageConverter[]) null)) - .withMessageContaining("MessageConverters must not be null"); + .isThrownBy(() -> this.builder.additionalMessageConverters((HttpMessageConverter[]) null)) + .withMessageContaining("MessageConverters must not be null"); } @Test void additionalMessageConvertersCollectionWhenConvertersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalMessageConverters((Set>) null)) - .withMessageContaining("MessageConverters must not be null"); + .isThrownBy(() -> this.builder.additionalMessageConverters((Set>) null)) + .withMessageContaining("MessageConverters must not be null"); } @Test void additionalMessageConvertersShouldAddToExisting() { HttpMessageConverter resourceConverter = new ResourceHttpMessageConverter(); RestTemplate template = this.builder.messageConverters(resourceConverter) - .additionalMessageConverters(this.messageConverter).build(); + .additionalMessageConverters(this.messageConverter) + .build(); assertThat(template.getMessageConverters()).containsOnly(resourceConverter, this.messageConverter); } @@ -199,15 +202,15 @@ class RestTemplateBuilderTests { @Test void interceptorsWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.interceptors((ClientHttpRequestInterceptor[]) null)) - .withMessageContaining("interceptors must not be null"); + .isThrownBy(() -> this.builder.interceptors((ClientHttpRequestInterceptor[]) null)) + .withMessageContaining("interceptors must not be null"); } @Test void interceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.interceptors((Set) null)) - .withMessageContaining("interceptors must not be null"); + .isThrownBy(() -> this.builder.interceptors((Set) null)) + .withMessageContaining("interceptors must not be null"); } @Test @@ -219,22 +222,23 @@ class RestTemplateBuilderTests { @Test void interceptorsShouldReplaceExisting() { RestTemplate template = this.builder.interceptors(mock(ClientHttpRequestInterceptor.class)) - .interceptors(Collections.singleton(this.interceptor)).build(); + .interceptors(Collections.singleton(this.interceptor)) + .build(); assertThat(template.getInterceptors()).containsOnly(this.interceptor); } @Test void additionalInterceptorsWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalInterceptors((ClientHttpRequestInterceptor[]) null)) - .withMessageContaining("interceptors must not be null"); + .isThrownBy(() -> this.builder.additionalInterceptors((ClientHttpRequestInterceptor[]) null)) + .withMessageContaining("interceptors must not be null"); } @Test void additionalInterceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalInterceptors((Set) null)) - .withMessageContaining("interceptors must not be null"); + .isThrownBy(() -> this.builder.additionalInterceptors((Set) null)) + .withMessageContaining("interceptors must not be null"); } @Test @@ -247,8 +251,8 @@ class RestTemplateBuilderTests { @Test void requestFactoryClassWhenFactoryIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.requestFactory((Class) null)) - .withMessageContaining("RequestFactory must not be null"); + .isThrownBy(() -> this.builder.requestFactory((Class) null)) + .withMessageContaining("RequestFactory must not be null"); } @Test @@ -266,8 +270,8 @@ class RestTemplateBuilderTests { @Test void requestFactoryWhenSupplierIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.requestFactory((Supplier) null)) - .withMessageContaining("RequestFactory Supplier must not be null"); + .isThrownBy(() -> this.builder.requestFactory((Supplier) null)) + .withMessageContaining("RequestFactory Supplier must not be null"); } @Test @@ -280,7 +284,7 @@ class RestTemplateBuilderTests { @Test void uriTemplateHandlerWhenHandlerIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.builder.uriTemplateHandler(null)) - .withMessageContaining("UriTemplateHandler must not be null"); + .withMessageContaining("UriTemplateHandler must not be null"); } @Test @@ -293,7 +297,7 @@ class RestTemplateBuilderTests { @Test void errorHandlerWhenHandlerIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.builder.errorHandler(null)) - .withMessageContaining("ErrorHandler must not be null"); + .withMessageContaining("ErrorHandler must not be null"); } @Test @@ -338,7 +342,8 @@ class RestTemplateBuilderTests { @Test void requestCustomizersAddsCustomizers() { RestTemplate template = this.builder - .requestCustomizers((request) -> request.getHeaders().add("spring", "framework")).build(); + .requestCustomizers((request) -> request.getHeaders().add("spring", "framework")) + .build(); ClientHttpRequest request = createRequest(template); assertThat(request.getHeaders()).contains(entry("spring", Collections.singletonList("framework"))); } @@ -346,24 +351,25 @@ class RestTemplateBuilderTests { @Test void additionalRequestCustomizersAddsCustomizers() { RestTemplate template = this.builder - .requestCustomizers((request) -> request.getHeaders().add("spring", "framework")) - .additionalRequestCustomizers((request) -> request.getHeaders().add("for", "java")).build(); + .requestCustomizers((request) -> request.getHeaders().add("spring", "framework")) + .additionalRequestCustomizers((request) -> request.getHeaders().add("for", "java")) + .build(); ClientHttpRequest request = createRequest(template); assertThat(request.getHeaders()).contains(entry("spring", Collections.singletonList("framework"))) - .contains(entry("for", Collections.singletonList("java"))); + .contains(entry("for", Collections.singletonList("java"))); } @Test void customizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.builder.customizers((RestTemplateCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .withMessageContaining("Customizers must not be null"); } @Test void customizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.customizers((Set) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.customizers((Set) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -385,8 +391,9 @@ class RestTemplateBuilderTests { void customizersShouldReplaceExisting() { RestTemplateCustomizer customizer1 = mock(RestTemplateCustomizer.class); RestTemplateCustomizer customizer2 = mock(RestTemplateCustomizer.class); - RestTemplate template = this.builder.customizers(customizer1).customizers(Collections.singleton(customizer2)) - .build(); + RestTemplate template = this.builder.customizers(customizer1) + .customizers(Collections.singleton(customizer2)) + .build(); then(customizer1).shouldHaveNoInteractions(); then(customizer2).should().customize(template); } @@ -394,15 +401,15 @@ class RestTemplateBuilderTests { @Test void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalCustomizers((RestTemplateCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.additionalCustomizers((RestTemplateCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalCustomizers((Set) null)) - .withMessageContaining("RestTemplateCustomizers must not be null"); + .isThrownBy(() -> this.builder.additionalCustomizers((Set) null)) + .withMessageContaining("RestTemplateCustomizers must not be null"); } @Test @@ -419,18 +426,23 @@ class RestTemplateBuilderTests { void customizerShouldBeAppliedAtTheEnd() { ResponseErrorHandler errorHandler = mock(ResponseErrorHandler.class); ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); - this.builder.interceptors(this.interceptor).messageConverters(this.messageConverter) - .rootUri("http://localhost:8080").errorHandler(errorHandler).basicAuthentication("spring", "boot") - .requestFactory(() -> requestFactory).customizers((restTemplate) -> { - assertThat(restTemplate.getInterceptors()).hasSize(1); - assertThat(restTemplate.getMessageConverters()).contains(this.messageConverter); - assertThat(restTemplate.getUriTemplateHandler()).isInstanceOf(RootUriTemplateHandler.class); - assertThat(restTemplate.getErrorHandler()).isEqualTo(errorHandler); - ClientHttpRequestFactory actualRequestFactory = restTemplate.getRequestFactory(); - assertThat(actualRequestFactory).isInstanceOf(InterceptingClientHttpRequestFactory.class); - ClientHttpRequestInitializer initializer = restTemplate.getClientHttpRequestInitializers().get(0); - assertThat(initializer).isInstanceOf(RestTemplateBuilderClientHttpRequestInitializer.class); - }).build(); + this.builder.interceptors(this.interceptor) + .messageConverters(this.messageConverter) + .rootUri("http://localhost:8080") + .errorHandler(errorHandler) + .basicAuthentication("spring", "boot") + .requestFactory(() -> requestFactory) + .customizers((restTemplate) -> { + assertThat(restTemplate.getInterceptors()).hasSize(1); + assertThat(restTemplate.getMessageConverters()).contains(this.messageConverter); + assertThat(restTemplate.getUriTemplateHandler()).isInstanceOf(RootUriTemplateHandler.class); + assertThat(restTemplate.getErrorHandler()).isEqualTo(errorHandler); + ClientHttpRequestFactory actualRequestFactory = restTemplate.getRequestFactory(); + assertThat(actualRequestFactory).isInstanceOf(InterceptingClientHttpRequestFactory.class); + ClientHttpRequestInitializer initializer = restTemplate.getClientHttpRequestInitializers().get(0); + assertThat(initializer).isInstanceOf(RestTemplateBuilderClientHttpRequestInitializer.class); + }) + .build(); } @Test @@ -455,70 +467,91 @@ class RestTemplateBuilderTests { @Test void connectTimeoutCanBeNullToUseDefault() { ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) - .setConnectTimeout(null).build().getRequestFactory(); + .setConnectTimeout(null) + .build() + .getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("connectTimeout", -1); } @Test void readTimeoutCanBeNullToUseDefault() { ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) - .setReadTimeout(null).build().getRequestFactory(); + .setReadTimeout(null) + .build() + .getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("readTimeout", -1); } @Test void connectTimeoutCanBeConfiguredOnHttpComponentsRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(HttpComponentsClientHttpRequestFactory.class).setConnectTimeout(Duration.ofMillis(1234)) - .build().getRequestFactory(); + .requestFactory(HttpComponentsClientHttpRequestFactory.class) + .setConnectTimeout(Duration.ofMillis(1234)) + .build() + .getRequestFactory(); assertThat(((RequestConfig) ReflectionTestUtils.getField(requestFactory, "requestConfig")).getConnectTimeout()) - .isEqualTo(1234); + .isEqualTo(1234); } @Test void readTimeoutCanBeConfiguredOnHttpComponentsRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(HttpComponentsClientHttpRequestFactory.class).setReadTimeout(Duration.ofMillis(1234)) - .build().getRequestFactory(); + .requestFactory(HttpComponentsClientHttpRequestFactory.class) + .setReadTimeout(Duration.ofMillis(1234)) + .build() + .getRequestFactory(); assertThat(((RequestConfig) ReflectionTestUtils.getField(requestFactory, "requestConfig")).getSocketTimeout()) - .isEqualTo(1234); + .isEqualTo(1234); } @Test void bufferRequestBodyCanBeConfiguredOnHttpComponentsRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(HttpComponentsClientHttpRequestFactory.class).setBufferRequestBody(false).build() - .getRequestFactory(); + .requestFactory(HttpComponentsClientHttpRequestFactory.class) + .setBufferRequestBody(false) + .build() + .getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", false); requestFactory = this.builder.requestFactory(HttpComponentsClientHttpRequestFactory.class) - .setBufferRequestBody(true).build().getRequestFactory(); + .setBufferRequestBody(true) + .build() + .getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", true); - requestFactory = this.builder.requestFactory(HttpComponentsClientHttpRequestFactory.class).build() - .getRequestFactory(); + requestFactory = this.builder.requestFactory(HttpComponentsClientHttpRequestFactory.class) + .build() + .getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", true); } @Test void connectTimeoutCanBeConfiguredOnSimpleRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) - .setConnectTimeout(Duration.ofMillis(1234)).build().getRequestFactory(); + .setConnectTimeout(Duration.ofMillis(1234)) + .build() + .getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("connectTimeout", 1234); } @Test void readTimeoutCanBeConfiguredOnSimpleRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) - .setReadTimeout(Duration.ofMillis(1234)).build().getRequestFactory(); + .setReadTimeout(Duration.ofMillis(1234)) + .build() + .getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("readTimeout", 1234); } @Test void bufferRequestBodyCanBeConfiguredOnSimpleRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) - .setBufferRequestBody(false).build().getRequestFactory(); + .setBufferRequestBody(false) + .build() + .getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", false); - requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class).setBufferRequestBody(true) - .build().getRequestFactory(); + requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) + .setBufferRequestBody(true) + .build() + .getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", true); requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class).build().getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", true); @@ -527,32 +560,41 @@ class RestTemplateBuilderTests { @Test void connectTimeoutCanBeConfiguredOnOkHttpRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder.requestFactory(OkHttp3ClientHttpRequestFactory.class) - .setConnectTimeout(Duration.ofMillis(1234)).build().getRequestFactory(); + .setConnectTimeout(Duration.ofMillis(1234)) + .build() + .getRequestFactory(); assertThat(requestFactory).extracting("client", InstanceOfAssertFactories.type(OkHttpClient.class)) - .extracting(OkHttpClient::connectTimeoutMillis).isEqualTo(1234); + .extracting(OkHttpClient::connectTimeoutMillis) + .isEqualTo(1234); } @Test void readTimeoutCanBeConfiguredOnOkHttp3RequestFactory() { ClientHttpRequestFactory requestFactory = this.builder.requestFactory(OkHttp3ClientHttpRequestFactory.class) - .setReadTimeout(Duration.ofMillis(1234)).build().getRequestFactory(); + .setReadTimeout(Duration.ofMillis(1234)) + .build() + .getRequestFactory(); assertThat(requestFactory).extracting("client", InstanceOfAssertFactories.type(OkHttpClient.class)) - .extracting(OkHttpClient::readTimeoutMillis).isEqualTo(1234); + .extracting(OkHttpClient::readTimeoutMillis) + .isEqualTo(1234); } @Test void bufferRequestBodyCanNotBeConfiguredOnOkHttp3RequestFactory() { assertThatIllegalStateException() - .isThrownBy(() -> this.builder.requestFactory(OkHttp3ClientHttpRequestFactory.class) - .setBufferRequestBody(false).build().getRequestFactory()) - .withMessageContaining(OkHttp3ClientHttpRequestFactory.class.getName()); + .isThrownBy(() -> this.builder.requestFactory(OkHttp3ClientHttpRequestFactory.class) + .setBufferRequestBody(false) + .build() + .getRequestFactory()) + .withMessageContaining(OkHttp3ClientHttpRequestFactory.class.getName()); } @Test void connectTimeoutCanBeConfiguredOnAWrappedRequestFactory() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)) - .setConnectTimeout(Duration.ofMillis(1234)).build(); + .setConnectTimeout(Duration.ofMillis(1234)) + .build(); assertThat(requestFactory).hasFieldOrPropertyWithValue("connectTimeout", 1234); } @@ -560,7 +602,8 @@ class RestTemplateBuilderTests { void readTimeoutCanBeConfiguredOnAWrappedRequestFactory() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)) - .setReadTimeout(Duration.ofMillis(1234)).build(); + .setReadTimeout(Duration.ofMillis(1234)) + .build(); assertThat(requestFactory).hasFieldOrPropertyWithValue("readTimeout", 1234); } @@ -568,10 +611,12 @@ class RestTemplateBuilderTests { void bufferRequestBodyCanBeConfiguredOnAWrappedRequestFactory() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)) - .setBufferRequestBody(false).build(); + .setBufferRequestBody(false) + .build(); assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", false); this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)) - .setBufferRequestBody(true).build(); + .setBufferRequestBody(true) + .build(); assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", true); this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)).build(); assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", true); @@ -581,7 +626,7 @@ class RestTemplateBuilderTests { void unwrappingDoesNotAffectRequestFactoryThatIsSetOnTheBuiltTemplate() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); RestTemplate template = this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)) - .build(); + .build(); assertThat(template.getRequestFactory()).isInstanceOf(BufferingClientHttpRequestFactory.class); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTestsOkHttp3Tests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTestsOkHttp3Tests.java index 24b6c20e19..32e54bb480 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTestsOkHttp3Tests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTestsOkHttp3Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,25 +42,33 @@ class RestTemplateBuilderTestsOkHttp3Tests { @Test void connectTimeoutCanBeConfiguredOnOkHttpRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder.requestFactory(OkHttp3ClientHttpRequestFactory.class) - .setConnectTimeout(Duration.ofMillis(1234)).build().getRequestFactory(); + .setConnectTimeout(Duration.ofMillis(1234)) + .build() + .getRequestFactory(); assertThat(requestFactory).extracting("client", InstanceOfAssertFactories.type(OkHttpClient.class)) - .extracting(OkHttpClient::connectTimeoutMillis).isEqualTo(1234); + .extracting(OkHttpClient::connectTimeoutMillis) + .isEqualTo(1234); } @Test void readTimeoutCanBeConfiguredOnOkHttpRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder.requestFactory(OkHttp3ClientHttpRequestFactory.class) - .setReadTimeout(Duration.ofMillis(1234)).build().getRequestFactory(); + .setReadTimeout(Duration.ofMillis(1234)) + .build() + .getRequestFactory(); assertThat(requestFactory).extracting("client", InstanceOfAssertFactories.type(OkHttpClient.class)) - .extracting(OkHttpClient::readTimeoutMillis).isEqualTo(1234); + .extracting(OkHttpClient::readTimeoutMillis) + .isEqualTo(1234); } @Test void bufferRequestBodyCanNotBeConfiguredOnOkHttpRequestFactory() { assertThatIllegalStateException() - .isThrownBy(() -> this.builder.requestFactory(OkHttp3ClientHttpRequestFactory.class) - .setBufferRequestBody(false).build().getRequestFactory()) - .withMessageContaining(OkHttp3ClientHttpRequestFactory.class.getName()); + .isThrownBy(() -> this.builder.requestFactory(OkHttp3ClientHttpRequestFactory.class) + .setBufferRequestBody(false) + .build() + .getRequestFactory()) + .withMessageContaining(OkHttp3ClientHttpRequestFactory.class.getName()); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java index f75da6468b..2e81400089 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,13 +61,13 @@ class RootUriTemplateHandlerTests { @Test void createWithNullRootUriShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new RootUriTemplateHandler((String) null)) - .withMessageContaining("RootUri must not be null"); + .withMessageContaining("RootUri must not be null"); } @Test void createWithNullHandlerShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new RootUriTemplateHandler("https://example.com", null)) - .withMessageContaining("Handler must not be null"); + .withMessageContaining("Handler must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java index e6a93f8033..a7e7fa341c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,15 +57,15 @@ class JettyReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactor void setNullServerCustomizersShouldThrowException() { JettyReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setServerCustomizers(null)) - .withMessageContaining("Customizers must not be null"); + .withMessageContaining("Customizers must not be null"); } @Test void addNullServerCustomizersShouldThrowException() { JettyReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addServerCustomizers((JettyServerCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> factory.addServerCustomizers((JettyServerCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test 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 bed60b0209..9b3de453dc 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -322,8 +322,9 @@ class JettyServletWebServerFactoryTests extends AbstractServletWebServerFactoryT response = request.get(); assertThat(response).isInstanceOf(HttpResponse.class); assertThat(((HttpResponse) response).getStatusLine().getStatusCode()).isEqualTo(200); - assertThat(((HttpResponse) response).getFirstHeader("Connection")).isNotNull().extracting(Header::getValue) - .isEqualTo("close"); + assertThat(((HttpResponse) response).getFirstHeader("Connection")).isNotNull() + .extracting(Header::getValue) + .isEqualTo("close"); this.webServer.stop(); } @@ -424,7 +425,7 @@ class JettyServletWebServerFactoryTests extends AbstractServletWebServerFactoryT threadPool.setMinThreads(2); }); assertThatExceptionOfType(WebServerException.class).isThrownBy(factory.getWebServer()::start) - .withCauseInstanceOf(IllegalStateException.class); + .withCauseInstanceOf(IllegalStateException.class); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java index 4122e0e5b2..bd00d201fb 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,7 +58,7 @@ class SslServerCustomizerTests { assertThat(server.getConnectors()).hasSize(1); List factories = new ArrayList<>(server.getConnectors()[0].getConnectionFactories()); assertThat(factories).extracting((factory) -> (Class) factory.getClass()) - .containsExactly(SslConnectionFactory.class, HttpConnectionFactory.class); + .containsExactly(SslConnectionFactory.class, HttpConnectionFactory.class); } @Test @@ -71,9 +71,9 @@ class SslServerCustomizerTests { Server server = createCustomizedServer(http2); assertThat(server.getConnectors()).hasSize(1); List factories = new ArrayList<>(server.getConnectors()[0].getConnectionFactories()); - assertThat(factories).extracting((factory) -> (Class) factory.getClass()).containsExactly( - SslConnectionFactory.class, ALPNServerConnectionFactory.class, HTTP2ServerConnectionFactory.class, - HttpConnectionFactory.class); + assertThat(factories).extracting((factory) -> (Class) factory.getClass()) + .containsExactly(SslConnectionFactory.class, ALPNServerConnectionFactory.class, + HTTP2ServerConnectionFactory.class, HttpConnectionFactory.class); } @Test @@ -93,11 +93,11 @@ class SslServerCustomizerTests { Ssl ssl = new Ssl(); SslServerCustomizer customizer = new SslServerCustomizer(null, ssl, null, null); assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> customizer.configureSsl(new SslContextFactory.Server(), ssl, null)) - .satisfies((ex) -> { - assertThat(ex).isInstanceOf(WebServerException.class); - assertThat(ex).hasMessageContaining("Could not load key store 'null'"); - }); + .isThrownBy(() -> customizer.configureSsl(new SslContextFactory.Server(), ssl, null)) + .satisfies((ex) -> { + assertThat(ex).isInstanceOf(WebServerException.class); + assertThat(ex).hasMessageContaining("Could not load key store 'null'"); + }); } @Test @@ -109,8 +109,8 @@ class SslServerCustomizerTests { ssl.setKeyPassword("password"); SslServerCustomizer customizer = new SslServerCustomizer(null, ssl, null, null); assertThatIllegalStateException() - .isThrownBy(() -> customizer.configureSsl(new SslContextFactory.Server(), ssl, null)) - .withMessageContaining("must be empty or null for PKCS11 key stores"); + .isThrownBy(() -> customizer.configureSsl(new SslContextFactory.Server(), ssl, null)) + .withMessageContaining("must be empty or null for PKCS11 key stores"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java index 899fa38155..983317ccf6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,7 +67,8 @@ class NettyReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactor this.webServer.start(); factory.setPort(this.webServer.getPort()); assertThatExceptionOfType(PortInUseException.class).isThrownBy(factory.getWebServer(new EchoHandler())::start) - .satisfies(this::portMatchesRequirement).withCauseInstanceOf(Throwable.class); + .satisfies(this::portMatchesRequirement) + .withCauseInstanceOf(Throwable.class); } @Test @@ -147,10 +148,16 @@ class NettyReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactor this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); ReactorClientHttpConnector connector = buildTrustAllSslConnector(); - WebClient client = WebClient.builder().baseUrl("https://localhost:" + this.webServer.getPort()) - .clientConnector(connector).build(); - return client.post().uri("/test").contentType(MediaType.TEXT_PLAIN).body(BodyInserters.fromValue("Hello World")) - .retrieve().bodyToMono(String.class); + WebClient client = WebClient.builder() + .baseUrl("https://localhost:" + this.webServer.getPort()) + .clientConnector(connector) + .build(); + return client.post() + .uri("/test") + .contentType(MediaType.TEXT_PLAIN) + .body(BodyInserters.fromValue("Hello World")) + .retrieve() + .bodyToMono(String.class); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java index 0c82384386..25dda5d4be 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,8 @@ class SslServerCustomizerTests { ssl.setKeyStoreProvider("com.example.KeyStoreProvider"); SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null); assertThatIllegalStateException().isThrownBy(() -> customizer.getKeyManagerFactory(ssl, null)) - .withCauseInstanceOf(NoSuchProviderException.class) - .withMessageContaining("com.example.KeyStoreProvider"); + .withCauseInstanceOf(NoSuchProviderException.class) + .withMessageContaining("com.example.KeyStoreProvider"); } @Test @@ -59,8 +59,8 @@ class SslServerCustomizerTests { ssl.setTrustStoreProvider("com.example.TrustStoreProvider"); SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null); assertThatIllegalStateException().isThrownBy(() -> customizer.getTrustManagerFactory(ssl, null)) - .withCauseInstanceOf(NoSuchProviderException.class) - .withMessageContaining("com.example.TrustStoreProvider"); + .withCauseInstanceOf(NoSuchProviderException.class) + .withMessageContaining("com.example.TrustStoreProvider"); } @Test @@ -68,7 +68,8 @@ class SslServerCustomizerTests { Ssl ssl = new Ssl(); SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null); assertThatIllegalStateException().isThrownBy(() -> customizer.getKeyManagerFactory(ssl, null)) - .withCauseInstanceOf(WebServerException.class).withMessageContaining("Could not load key store 'null'"); + .withCauseInstanceOf(WebServerException.class) + .withMessageContaining("Could not load key store 'null'"); } @Test @@ -80,8 +81,8 @@ class SslServerCustomizerTests { ssl.setKeyPassword("password"); SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null); assertThatIllegalStateException().isThrownBy(() -> customizer.getKeyManagerFactory(ssl, null)) - .withCauseInstanceOf(IllegalStateException.class) - .withMessageContaining("must be empty or null for PKCS11 key stores"); + .withCauseInstanceOf(IllegalStateException.class) + .withMessageContaining("must be empty or null for PKCS11 key stores"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java index 6634d1c164..53c6973f45 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -185,8 +185,8 @@ class SslConnectorCustomizerTests { @Test void customizeWhenSslIsEnabledWithNoKeyStoreAndNotPkcs11ThrowsException() { assertThatExceptionOfType(WebServerException.class) - .isThrownBy(() -> new SslConnectorCustomizer(new Ssl(), null).customize(this.tomcat.getConnector())) - .withMessageContaining("Could not load key store 'null'"); + .isThrownBy(() -> new SslConnectorCustomizer(new Ssl(), null).customize(this.tomcat.getConnector())) + .withMessageContaining("Could not load key store 'null'"); } @Test @@ -198,7 +198,7 @@ class SslConnectorCustomizerTests { ssl.setKeyPassword("password"); SslConnectorCustomizer customizer = new SslConnectorCustomizer(ssl, null); assertThatIllegalStateException().isThrownBy(() -> customizer.customize(this.tomcat.getConnector())) - .withMessageContaining("must be empty or null for PKCS11 key stores"); + .withMessageContaining("must be empty or null for PKCS11 key stores"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoaderTests.java index cb4be3552b..7dd30e2735 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,7 @@ class TomcatEmbeddedWebappClassLoaderTests { void getResourceFindsResourceFromParentClassLoader() throws Exception { File war = createWar(); withWebappClassLoader(war, (classLoader) -> assertThat(classLoader.getResource("test.txt")) - .isEqualTo(new URL(webInfClassesUrlString(war) + "test.txt"))); + .isEqualTo(new URL(webInfClassesUrlString(war) + "test.txt"))); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java index 0368235f60..42235365d5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -123,30 +123,30 @@ class TomcatReactiveWebServerFactoryTests extends AbstractReactiveWebServerFacto void setNullConnectorCustomizersShouldThrowException() { TomcatReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatConnectorCustomizers(null)) - .withMessageContaining("Customizers must not be null"); + .withMessageContaining("Customizers must not be null"); } @Test void addNullAddConnectorCustomizersShouldThrowException() { TomcatReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addConnectorCustomizers((TomcatConnectorCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> factory.addConnectorCustomizers((TomcatConnectorCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test void setNullProtocolHandlerCustomizersShouldThrowException() { TomcatReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatProtocolHandlerCustomizers(null)) - .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); + .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); } @Test void addNullProtocolHandlerCustomizersShouldThrowException() { TomcatReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addProtocolHandlerCustomizers((TomcatProtocolHandlerCustomizer[]) null)) - .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); + .isThrownBy(() -> factory.addProtocolHandlerCustomizers((TomcatProtocolHandlerCustomizer[]) null)) + .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); } @Test @@ -195,7 +195,7 @@ class TomcatReactiveWebServerFactoryTests extends AbstractReactiveWebServerFacto void addNullAdditionalConnectorsThrows() { TomcatReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.addAdditionalTomcatConnectors((Connector[]) null)) - .withMessageContaining("Connectors must not be null"); + .withMessageContaining("Connectors must not be null"); } @Test 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 a0e2b7e38e..dcb2ada8b4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -216,7 +216,7 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory void tomcatProtocolHandlerCanBeCustomized() { TomcatServletWebServerFactory factory = getFactory(); TomcatProtocolHandlerCustomizer> customizer = (protocolHandler) -> protocolHandler - .setProcessorCache(250); + .setProcessorCache(250); factory.addProtocolHandlerCustomizers(customizer); Tomcat tomcat = getTomcat(factory); Connector connector = ((TomcatWebServer) this.webServer).getServiceConnectors().get(tomcat.getService())[0]; @@ -239,7 +239,7 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory void addNullAdditionalConnectorThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.addAdditionalTomcatConnectors((Connector[]) null)) - .withMessageContaining("Connectors must not be null"); + .withMessageContaining("Connectors must not be null"); } @Test @@ -276,45 +276,45 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory void setNullTomcatContextCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatContextCustomizers(null)) - .withMessageContaining("TomcatContextCustomizers must not be null"); + .withMessageContaining("TomcatContextCustomizers must not be null"); } @Test void addNullContextCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addContextCustomizers((TomcatContextCustomizer[]) null)) - .withMessageContaining("TomcatContextCustomizers must not be null"); + .isThrownBy(() -> factory.addContextCustomizers((TomcatContextCustomizer[]) null)) + .withMessageContaining("TomcatContextCustomizers must not be null"); } @Test void setNullTomcatConnectorCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatConnectorCustomizers(null)) - .withMessageContaining("TomcatConnectorCustomizers must not be null"); + .withMessageContaining("TomcatConnectorCustomizers must not be null"); } @Test void addNullConnectorCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addConnectorCustomizers((TomcatConnectorCustomizer[]) null)) - .withMessageContaining("TomcatConnectorCustomizers must not be null"); + .isThrownBy(() -> factory.addConnectorCustomizers((TomcatConnectorCustomizer[]) null)) + .withMessageContaining("TomcatConnectorCustomizers must not be null"); } @Test void setNullTomcatProtocolHandlerCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatProtocolHandlerCustomizers(null)) - .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); + .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); } @Test void addNullTomcatProtocolHandlerCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addProtocolHandlerCustomizers((TomcatProtocolHandlerCustomizer[]) null)) - .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); + .isThrownBy(() -> factory.addProtocolHandlerCustomizers((TomcatProtocolHandlerCustomizer[]) null)) + .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); } @Test @@ -411,7 +411,7 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory this.webServer = factory.getWebServer(); // override defaults, see org.apache.catalina.util.CharsetMapperDefault.properties Properties charsetMapperDefault = PropertiesLoaderUtils - .loadProperties(new ClassPathResource("CharsetMapperDefault.properties", CharsetMapper.class)); + .loadProperties(new ClassPathResource("CharsetMapperDefault.properties", CharsetMapper.class)); for (String language : charsetMapperDefault.stringPropertyNames()) { assertThat(getCharset(new Locale(language))).isEqualTo(StandardCharsets.UTF_8); } @@ -481,7 +481,7 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory } }); this.webServer = factory - .getWebServer((context) -> context.addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); + .getWebServer((context) -> context.addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); assertThatExceptionOfType(WebServerException.class).isThrownBy(this.webServer::start); } @@ -494,7 +494,7 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory } }); this.webServer = factory - .getWebServer((context) -> context.addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); + .getWebServer((context) -> context.addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); this.webServer.start(); } @@ -591,9 +591,9 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory blockingServlet.awaitQueue(); this.webServer.shutDownGracefully((result) -> { }); - Object unconnectableRequest = Awaitility.await().until( - () -> initiateGetRequest(HttpClients.createDefault(), port, "/").get(), - (result) -> result instanceof Exception); + Object unconnectableRequest = Awaitility.await() + .until(() -> initiateGetRequest(HttpClients.createDefault(), port, "/").get(), + (result) -> result instanceof Exception); assertThat(unconnectableRequest).isInstanceOf(HttpHostConnectException.class); blockingServlet.admitOne(); assertThat(request.get()).isInstanceOf(HttpResponse.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java index c0bcf88840..d06092bb48 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,8 @@ class SslBuilderCustomizerTests { ssl.setKeyStore("src/test/resources/test.jks"); SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); KeyManager[] keyManagers = ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null); - Class name = Class.forName( - "org.springframework.boot.web.embedded.undertow.SslBuilderCustomizer$ConfigurableAliasKeyManager"); + Class name = Class + .forName("org.springframework.boot.web.embedded.undertow.SslBuilderCustomizer$ConfigurableAliasKeyManager"); assertThat(keyManagers[0]).isNotInstanceOf(name); } @@ -63,9 +63,9 @@ class SslBuilderCustomizerTests { ssl.setKeyStoreProvider("com.example.KeyStoreProvider"); SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); assertThatIllegalStateException() - .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null)) - .withCauseInstanceOf(NoSuchProviderException.class) - .withMessageContaining("com.example.KeyStoreProvider"); + .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null)) + .withCauseInstanceOf(NoSuchProviderException.class) + .withMessageContaining("com.example.KeyStoreProvider"); } @Test @@ -76,9 +76,9 @@ class SslBuilderCustomizerTests { ssl.setTrustStoreProvider("com.example.TrustStoreProvider"); SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); assertThatIllegalStateException() - .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getTrustManagers", ssl, null)) - .withCauseInstanceOf(NoSuchProviderException.class) - .withMessageContaining("com.example.TrustStoreProvider"); + .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getTrustManagers", ssl, null)) + .withCauseInstanceOf(NoSuchProviderException.class) + .withMessageContaining("com.example.TrustStoreProvider"); } @Test @@ -86,8 +86,9 @@ class SslBuilderCustomizerTests { Ssl ssl = new Ssl(); SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); assertThatIllegalStateException() - .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null)) - .withCauseInstanceOf(WebServerException.class).withMessageContaining("Could not load key store 'null'"); + .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null)) + .withCauseInstanceOf(WebServerException.class) + .withMessageContaining("Could not load key store 'null'"); } @Test @@ -99,9 +100,9 @@ class SslBuilderCustomizerTests { ssl.setKeyPassword("password"); SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); assertThatIllegalStateException() - .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null)) - .withCauseInstanceOf(IllegalArgumentException.class) - .withMessageContaining("Input keystore location is not valid for keystore type 'PKCS11'"); + .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null)) + .withCauseInstanceOf(IllegalArgumentException.class) + .withMessageContaining("Input keystore location is not valid for keystore type 'PKCS11'"); } @Test @@ -112,7 +113,7 @@ class SslBuilderCustomizerTests { ssl.setKeyStorePassword("1234"); SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); assertThatNoException() - .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null)); + .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null)); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java index 2b0cba9e30..28e3e7af69 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,15 +62,15 @@ class UndertowReactiveWebServerFactoryTests extends AbstractReactiveWebServerFac void setNullBuilderCustomizersShouldThrowException() { UndertowReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setBuilderCustomizers(null)) - .withMessageContaining("Customizers must not be null"); + .withMessageContaining("Customizers must not be null"); } @Test void addNullBuilderCustomizersShouldThrowException() { UndertowReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addBuilderCustomizers((UndertowBuilderCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> factory.addBuilderCustomizers((UndertowBuilderCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -139,8 +139,12 @@ class UndertowReactiveWebServerFactoryTests extends AbstractReactiveWebServerFac this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); WebClient client = getWebClient(this.webServer.getPort()).build(); - Mono result = client.post().uri("/test").contentType(MediaType.TEXT_PLAIN) - .body(BodyInserters.fromValue("Hello World")).retrieve().bodyToMono(String.class); + Mono result = client.post() + .uri("/test") + .contentType(MediaType.TEXT_PLAIN) + .body(BodyInserters.fromValue("Hello World")) + .retrieve() + .bodyToMono(String.class); assertThat(result.block(Duration.ofSeconds(30))).isEqualTo("Hello World"); File accessLog = new File(accessLogDirectory, expectedFile); awaitFile(accessLog); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java index e833dd92b2..78ce2b4e59 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -96,15 +96,15 @@ class UndertowServletWebServerFactoryTests extends AbstractServletWebServerFacto void setNullBuilderCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setBuilderCustomizers(null)) - .withMessageContaining("Customizers must not be null"); + .withMessageContaining("Customizers must not be null"); } @Test void addNullAddBuilderCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addBuilderCustomizers((UndertowBuilderCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> factory.addBuilderCustomizers((UndertowBuilderCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -125,15 +125,15 @@ class UndertowServletWebServerFactoryTests extends AbstractServletWebServerFacto void setNullDeploymentInfoCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setDeploymentInfoCustomizers(null)) - .withMessageContaining("Customizers must not be null"); + .withMessageContaining("Customizers must not be null"); } @Test void addNullAddDeploymentInfoCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addDeploymentInfoCustomizers((UndertowDeploymentInfoCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> factory.addDeploymentInfoCustomizers((UndertowDeploymentInfoCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -208,7 +208,7 @@ class UndertowServletWebServerFactoryTests extends AbstractServletWebServerFacto Object rejectedResult = initiateGetRequest(port, "/").get(); assertThat(rejectedResult).isInstanceOf(HttpResponse.class); assertThat(((HttpResponse) rejectedResult).getStatusLine().getStatusCode()) - .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE.value()); + .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE.value()); this.webServer.stop(); } @@ -232,23 +232,23 @@ class UndertowServletWebServerFactoryTests extends AbstractServletWebServerFacto @Override protected void addConnector(int port, AbstractServletWebServerFactory factory) { ((UndertowServletWebServerFactory) factory) - .addBuilderCustomizers((builder) -> builder.addHttpListener(port, "0.0.0.0")); + .addBuilderCustomizers((builder) -> builder.addHttpListener(port, "0.0.0.0")); } @Test void sslRestrictedProtocolsEmptyCipherFailure() { assertThatIOException() - .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.2" }, - new String[] { "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" })) - .isInstanceOfAny(SSLException.class, SSLHandshakeException.class, SocketException.class); + .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.2" }, + new String[] { "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" })) + .isInstanceOfAny(SSLException.class, SSLHandshakeException.class, SocketException.class); } @Test void sslRestrictedProtocolsECDHETLS1Failure() { assertThatIOException() - .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1" }, - new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" })) - .isInstanceOfAny(SSLException.class, SocketException.class); + .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1" }, + new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" })) + .isInstanceOfAny(SSLException.class, SocketException.class); } @Test @@ -266,9 +266,9 @@ class UndertowServletWebServerFactoryTests extends AbstractServletWebServerFacto @Test void sslRestrictedProtocolsRSATLS11Failure() { assertThatIOException() - .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.1" }, - new String[] { "TLS_RSA_WITH_AES_128_CBC_SHA256" })) - .isInstanceOfAny(SSLException.class, SocketException.class); + .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.1" }, + new String[] { "TLS_RSA_WITH_AES_128_CBC_SHA256" })) + .isInstanceOfAny(SSLException.class, SocketException.class); } @Override @@ -292,14 +292,16 @@ class UndertowServletWebServerFactoryTests extends AbstractServletWebServerFacto @Override protected Map getActualMimeMappings() { - return ((UndertowServletWebServer) this.webServer).getDeploymentManager().getDeployment() - .getMimeExtensionMappings(); + return ((UndertowServletWebServer) this.webServer).getDeploymentManager() + .getDeployment() + .getMimeExtensionMappings(); } @Override protected Charset getCharset(Locale locale) { - DeploymentInfo info = ((UndertowServletWebServer) this.webServer).getDeploymentManager().getDeployment() - .getDeploymentInfo(); + DeploymentInfo info = ((UndertowServletWebServer) this.webServer).getDeploymentManager() + .getDeployment() + .getDeploymentInfo(); String charsetName = info.getLocaleCharsetMapping().get(locale.toString()); return (charsetName != null) ? Charset.forName(charsetName) : null; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/ReactiveWebServerApplicationContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/ReactiveWebServerApplicationContextTests.java index 13ae884265..2abe19d394 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/ReactiveWebServerApplicationContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/ReactiveWebServerApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,15 +60,15 @@ class ReactiveWebServerApplicationContextTests { @Test void whenThereIsNoWebServerFactoryBeanThenContextRefreshWillFail() { assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh()) - .withMessageContaining( - "Unable to start ReactiveWebServerApplicationContext due to missing ReactiveWebServerFactory bean"); + .withMessageContaining( + "Unable to start ReactiveWebServerApplicationContext due to missing ReactiveWebServerFactory bean"); } @Test void whenThereIsNoHttpHandlerBeanThenContextRefreshWillFail() { addWebServerFactoryBean(); assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh()) - .withMessageContaining("Unable to start ReactiveWebApplicationContext due to missing HttpHandler bean"); + .withMessageContaining("Unable to start ReactiveWebApplicationContext due to missing HttpHandler bean"); } @Test @@ -76,8 +76,8 @@ class ReactiveWebServerApplicationContextTests { addWebServerFactoryBean(); addWebServerFactoryBean("anotherWebServerFactory"); assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh()) - .withMessageContaining( - "Unable to start ReactiveWebApplicationContext due to multiple ReactiveWebServerFactory beans"); + .withMessageContaining( + "Unable to start ReactiveWebApplicationContext due to multiple ReactiveWebServerFactory beans"); } @Test @@ -86,8 +86,7 @@ class ReactiveWebServerApplicationContextTests { addHttpHandlerBean("httpHandler1"); addHttpHandlerBean("httpHandler2"); assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh()) - .withMessageContaining( - "Unable to start ReactiveWebApplicationContext due to multiple HttpHandler beans"); + .withMessageContaining("Unable to start ReactiveWebApplicationContext due to multiple HttpHandler beans"); } @Test @@ -98,8 +97,9 @@ class ReactiveWebServerApplicationContextTests { this.context.addApplicationListener(listener); this.context.refresh(); List events = listener.receivedEvents(); - assertThat(events).hasSize(2).extracting("class").containsExactly(ReactiveWebServerInitializedEvent.class, - ContextRefreshedEvent.class); + assertThat(events).hasSize(2) + .extracting("class") + .containsExactly(ReactiveWebServerInitializedEvent.class, ContextRefreshedEvent.class); ReactiveWebServerInitializedEvent initializedEvent = (ReactiveWebServerInitializedEvent) events.get(0); assertThat(initializedEvent.getSource().getPort()).isGreaterThanOrEqualTo(0); assertThat(initializedEvent.getApplicationContext()).isEqualTo(this.context); @@ -136,10 +136,11 @@ class ReactiveWebServerApplicationContextTests { this.context.addApplicationListener(listener); this.context.close(); List events = listener.receivedEvents(); - assertThat(events).hasSize(2).extracting("class").contains(AvailabilityChangeEvent.class, - ContextClosedEvent.class); + assertThat(events).hasSize(2) + .extracting("class") + .contains(AvailabilityChangeEvent.class, ContextClosedEvent.class); assertThat(((AvailabilityChangeEvent) events.get(0)).getState()) - .isEqualTo(ReadinessState.REFUSING_TRAFFIC); + .isEqualTo(ReadinessState.REFUSING_TRAFFIC); } @Test @@ -160,7 +161,7 @@ class ReactiveWebServerApplicationContextTests { addHttpHandlerBean(); this.context.refresh(); assertThatIllegalStateException().isThrownBy(() -> this.context.refresh()) - .withMessageContaining("multiple refresh attempts"); + .withMessageContaining("multiple refresh attempts"); } private void addHttpHandlerBean() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java index fed54a45da..8903c74536 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,8 +64,8 @@ class DefaultErrorAttributesTests { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/test").build()); ServerRequest request = ServerRequest.create(exchange, this.readers); assertThatIllegalStateException() - .isThrownBy(() -> this.errorAttributes.getErrorAttributes(request, ErrorAttributeOptions.defaults())) - .withMessageContaining("Missing exception attribute in ServerWebExchange"); + .isThrownBy(() -> this.errorAttributes.getErrorAttributes(request, ErrorAttributeOptions.defaults())) + .withMessageContaining("Missing exception attribute in ServerWebExchange"); } @Test @@ -243,9 +243,9 @@ class DefaultErrorAttributesTests { Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, ex), ErrorAttributeOptions.of(Include.MESSAGE, Include.BINDING_ERRORS)); assertThat(attributes.get("message")).asString() - .startsWith("Validation failed for argument at index 0 in method: " - + "int org.springframework.boot.web.reactive.error.DefaultErrorAttributesTests" - + ".method(java.lang.String), with 1 error(s)"); + .startsWith("Validation failed for argument at index 0 in method: " + + "int org.springframework.boot.web.reactive.error.DefaultErrorAttributesTests" + + ".method(java.lang.String), with 1 error(s)"); assertThat(attributes.get("errors")).isEqualTo(bindingResult.getAllErrors()); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewTests.java index cecfd57d9a..b4add7efcf 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,9 +52,10 @@ class MustacheViewTests { view.setCharset(StandardCharsets.UTF_8.displayName()); view.setApplicationContext(this.context); view.render(Collections.singletonMap("World", "Spring"), MediaType.TEXT_HTML, exchange) - .block(Duration.ofSeconds(30)); + .block(Duration.ofSeconds(30)); StepVerifier.create(exchange.getResponse().getBodyAsString()) - .assertNext((body) -> assertThat(body).isEqualToIgnoringWhitespace("Hello Spring")).verifyComplete(); + .assertNext((body) -> assertThat(body).isEqualToIgnoringWhitespace("Hello Spring")) + .verifyComplete(); } } 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 0bf2ecbd5a..5e0d79b1ff 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -112,9 +112,13 @@ public abstract class AbstractReactiveWebServerFactoryTests { this.webServer.start(); return this.webServer.getPort(); }); - Mono result = getWebClient(this.webServer.getPort()).build().post().uri("/test") - .contentType(MediaType.TEXT_PLAIN).body(BodyInserters.fromValue("Hello World")).retrieve() - .bodyToMono(String.class); + Mono result = getWebClient(this.webServer.getPort()).build() + .post() + .uri("/test") + .contentType(MediaType.TEXT_PLAIN) + .body(BodyInserters.fromValue("Hello World")) + .retrieve() + .bodyToMono(String.class); assertThat(result.block(Duration.ofSeconds(30))).isEqualTo("Hello World"); assertThat(this.webServer.getPort()).isEqualTo(specificPort); } @@ -150,10 +154,16 @@ public abstract class AbstractReactiveWebServerFactoryTests { this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); ReactorClientHttpConnector connector = buildTrustAllSslConnector(); - WebClient client = WebClient.builder().baseUrl("https://localhost:" + this.webServer.getPort()) - .clientConnector(connector).build(); - Mono result = client.post().uri("/test").contentType(MediaType.TEXT_PLAIN) - .body(BodyInserters.fromValue("Hello World")).retrieve().bodyToMono(String.class); + WebClient client = WebClient.builder() + .baseUrl("https://localhost:" + this.webServer.getPort()) + .clientConnector(connector) + .build(); + Mono result = client.post() + .uri("/test") + .contentType(MediaType.TEXT_PLAIN) + .body(BodyInserters.fromValue("Hello World")) + .retrieve() + .bodyToMono(String.class); assertThat(result.block(Duration.ofSeconds(30))).isEqualTo("Hello World"); } @@ -171,11 +181,17 @@ public abstract class AbstractReactiveWebServerFactoryTests { this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); ReactorClientHttpConnector connector = buildTrustAllSslConnector(); - WebClient client = WebClient.builder().baseUrl("https://localhost:" + this.webServer.getPort()) - .clientConnector(connector).build(); - - Mono result = client.post().uri("/test").contentType(MediaType.TEXT_PLAIN) - .body(BodyInserters.fromValue("Hello World")).retrieve().bodyToMono(String.class); + WebClient client = WebClient.builder() + .baseUrl("https://localhost:" + this.webServer.getPort()) + .clientConnector(connector) + .build(); + + Mono result = client.post() + .uri("/test") + .contentType(MediaType.TEXT_PLAIN) + .body(BodyInserters.fromValue("Hello World")) + .retrieve() + .bodyToMono(String.class); StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); StepVerifier.create(result).expectNext("Hello World").verifyComplete(); @@ -199,8 +215,9 @@ public abstract class AbstractReactiveWebServerFactoryTests { } protected ReactorClientHttpConnector buildTrustAllSslConnector() { - Http11SslContextSpec sslContextSpec = Http11SslContextSpec.forClient().configure( - (builder) -> builder.sslProvider(SslProvider.JDK).trustManager(InsecureTrustManagerFactory.INSTANCE)); + Http11SslContextSpec sslContextSpec = Http11SslContextSpec.forClient() + .configure((builder) -> builder.sslProvider(SslProvider.JDK) + .trustManager(InsecureTrustManagerFactory.INSTANCE)); HttpClient client = HttpClient.create().wiretap(true).secure((spec) -> spec.sslContext(sslContextSpec)); return new ReactorClientHttpConnector(client); } @@ -234,12 +251,13 @@ public abstract class AbstractReactiveWebServerFactoryTests { clientKeyStore.load(stream, "secret".toCharArray()); } KeyManagerFactory clientKeyManagerFactory = KeyManagerFactory - .getInstance(KeyManagerFactory.getDefaultAlgorithm()); + .getInstance(KeyManagerFactory.getDefaultAlgorithm()); clientKeyManagerFactory.init(clientKeyStore, keyStorePassword.toCharArray()); Http11SslContextSpec sslContextSpec = Http11SslContextSpec.forClient() - .configure((builder) -> builder.sslProvider(SslProvider.JDK) - .trustManager(InsecureTrustManagerFactory.INSTANCE).keyManager(clientKeyManagerFactory)); + .configure((builder) -> builder.sslProvider(SslProvider.JDK) + .trustManager(InsecureTrustManagerFactory.INSTANCE) + .keyManager(clientKeyManagerFactory)); HttpClient client = HttpClient.create().wiretap(true).secure((spec) -> spec.sslContext(sslContextSpec)); return new ReactorClientHttpConnector(client); } @@ -249,10 +267,16 @@ public abstract class AbstractReactiveWebServerFactoryTests { factory.setSsl(sslConfiguration); this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); - WebClient client = WebClient.builder().baseUrl("https://localhost:" + this.webServer.getPort()) - .clientConnector(clientConnector).build(); - Mono result = client.post().uri("/test").contentType(MediaType.TEXT_PLAIN) - .body(BodyInserters.fromValue("Hello World")).retrieve().bodyToMono(String.class); + WebClient client = WebClient.builder() + .baseUrl("https://localhost:" + this.webServer.getPort()) + .clientConnector(clientConnector) + .build(); + Mono result = client.post() + .uri("/test") + .contentType(MediaType.TEXT_PLAIN) + .body(BodyInserters.fromValue("Hello World")) + .retrieve() + .bodyToMono(String.class); assertThat(result.block(Duration.ofSeconds(30))).isEqualTo("Hello World"); } @@ -293,10 +317,16 @@ public abstract class AbstractReactiveWebServerFactoryTests { factory.setSsl(sslConfiguration); this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); - WebClient client = WebClient.builder().baseUrl("https://localhost:" + this.webServer.getPort()) - .clientConnector(clientConnector).build(); - Mono result = client.post().uri("/test").contentType(MediaType.TEXT_PLAIN) - .body(BodyInserters.fromValue("Hello World")).retrieve().bodyToMono(String.class); + WebClient client = WebClient.builder() + .baseUrl("https://localhost:" + this.webServer.getPort()) + .clientConnector(clientConnector) + .build(); + Mono result = client.post() + .uri("/test") + .contentType(MediaType.TEXT_PLAIN) + .body(BodyInserters.fromValue("Hello World")) + .retrieve() + .bodyToMono(String.class); StepVerifier.create(result).expectError(WebClientRequestException.class).verify(Duration.ofSeconds(10)); } @@ -350,8 +380,11 @@ public abstract class AbstractReactiveWebServerFactoryTests { compression.setEnabled(true); compression.setExcludedUserAgents(new String[] { "testUserAgent" }); WebClient client = prepareCompressionTest(compression); - ResponseEntity response = client.get().header("User-Agent", "testUserAgent").retrieve().toBodilessEntity() - .block(Duration.ofSeconds(30)); + ResponseEntity response = client.get() + .header("User-Agent", "testUserAgent") + .retrieve() + .toBodilessEntity() + .block(Duration.ofSeconds(30)); assertResponseIsNotCompressed(response); } @@ -368,7 +401,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { @Test void whenSslIsEnabledAndNoKeyStoreIsConfiguredThenServerFailsToStart() { assertThatThrownBy(() -> testBasicSslWithKeyStore(null, null)) - .hasMessageContaining("Could not load key store 'null'"); + .hasMessageContaining("Could not load key store 'null'"); } @Test @@ -390,8 +423,10 @@ public abstract class AbstractReactiveWebServerFactoryTests { BlockingHandler blockingHandler = new BlockingHandler(); this.webServer = factory.getWebServer(blockingHandler); this.webServer.start(); - Mono> request = getWebClient(this.webServer.getPort()).build().get().retrieve() - .toBodilessEntity(); + Mono> request = getWebClient(this.webServer.getPort()).build() + .get() + .retrieve() + .toBodilessEntity(); AtomicReference> responseReference = new AtomicReference<>(); CountDownLatch responseLatch = new CountDownLatch(1); request.subscribe((response) -> { @@ -415,8 +450,10 @@ public abstract class AbstractReactiveWebServerFactoryTests { BlockingHandler blockingHandler = new BlockingHandler(); this.webServer = factory.getWebServer(blockingHandler); this.webServer.start(); - Mono> request = getWebClient(this.webServer.getPort()).build().get().retrieve() - .toBodilessEntity(); + Mono> request = getWebClient(this.webServer.getPort()).build() + .get() + .retrieve() + .toBodilessEntity(); AtomicReference> responseReference = new AtomicReference<>(); CountDownLatch responseLatch = new CountDownLatch(1); request.subscribe((response) -> { @@ -434,8 +471,9 @@ public abstract class AbstractReactiveWebServerFactoryTests { // Continue } System.out.println("Stopped"); - Awaitility.await().atMost(Duration.ofSeconds(5)) - .until(() -> GracefulShutdownResult.REQUESTS_ACTIVE == result.get()); + Awaitility.await() + .atMost(Duration.ofSeconds(5)) + .until(() -> GracefulShutdownResult.REQUESTS_ACTIVE == result.get()); blockingHandler.completeOne(); } @@ -446,8 +484,10 @@ public abstract class AbstractReactiveWebServerFactoryTests { BlockingHandler blockingHandler = new BlockingHandler(); this.webServer = factory.getWebServer(blockingHandler); this.webServer.start(); - Mono> request = getWebClient(this.webServer.getPort()).build().get().retrieve() - .toBodilessEntity(); + Mono> request = getWebClient(this.webServer.getPort()).build() + .get() + .retrieve() + .toBodilessEntity(); AtomicReference> responseReference = new AtomicReference<>(); CountDownLatch responseLatch = new CountDownLatch(1); request.subscribe((response) -> { @@ -458,8 +498,9 @@ public abstract class AbstractReactiveWebServerFactoryTests { AtomicReference result = new AtomicReference<>(); this.webServer.shutDownGracefully(result::set); this.webServer.stop(); - Awaitility.await().atMost(Duration.ofSeconds(30)) - .until(() -> GracefulShutdownResult.REQUESTS_ACTIVE == result.get()); + Awaitility.await() + .atMost(Duration.ofSeconds(30)) + .until(() -> GracefulShutdownResult.REQUESTS_ACTIVE == result.get()); blockingHandler.completeOne(); } @@ -469,8 +510,10 @@ public abstract class AbstractReactiveWebServerFactoryTests { BlockingHandler blockingHandler = new BlockingHandler(); this.webServer = factory.getWebServer(blockingHandler); this.webServer.start(); - Mono> request = getWebClient(this.webServer.getPort()).build().get().retrieve() - .toBodilessEntity(); + Mono> request = getWebClient(this.webServer.getPort()).build() + .get() + .retrieve() + .toBodilessEntity(); AtomicReference> responseReference = new AtomicReference<>(); CountDownLatch responseLatch = new CountDownLatch(1); request.subscribe((response) -> { @@ -500,7 +543,8 @@ public abstract class AbstractReactiveWebServerFactoryTests { client.start(); try { ContentResponse response = client.POST("http://localhost:" + this.webServer.getPort()) - .content(new StringContentProvider("Hello World"), "text/plain").send(); + .content(new StringContentProvider("Hello World"), "text/plain") + .send(); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); assertThat(response.getContentAsString()).isEqualTo("Hello World"); } @@ -517,9 +561,13 @@ public abstract class AbstractReactiveWebServerFactoryTests { factory.setHttp2(http2); this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); - Mono result = getWebClient(this.webServer.getPort()).build().post().uri("/test") - .contentType(MediaType.TEXT_PLAIN).body(BodyInserters.fromValue("Hello World")).retrieve() - .bodyToMono(String.class); + Mono result = getWebClient(this.webServer.getPort()).build() + .post() + .uri("/test") + .contentType(MediaType.TEXT_PLAIN) + .body(BodyInserters.fromValue("Hello World")) + .retrieve() + .bodyToMono(String.class); assertThat(result.block(Duration.ofSeconds(30))).isEqualTo("Hello World"); } @@ -539,9 +587,12 @@ public abstract class AbstractReactiveWebServerFactoryTests { this.webServer = factory.getWebServer(new CharsHandler(3000, responseContentType)); this.webServer.start(); - HttpClient client = HttpClient.create().wiretap(true).compress(true) - .doOnConnected((connection) -> connection.channel().pipeline().addBefore(NettyPipeline.HttpDecompressor, - "CompressionTest", new CompressionDetectionHandler())); + HttpClient client = HttpClient.create() + .wiretap(true) + .compress(true) + .doOnConnected((connection) -> connection.channel() + .pipeline() + .addBefore(NettyPipeline.HttpDecompressor, "CompressionTest", new CompressionDetectionHandler())); return getWebClient(client, this.webServer.getPort()).build(); } @@ -558,8 +609,12 @@ public abstract class AbstractReactiveWebServerFactoryTests { protected void assertForwardHeaderIsUsed(AbstractReactiveWebServerFactory factory) { this.webServer = factory.getWebServer(new XForwardedHandler()); this.webServer.start(); - String body = getWebClient(this.webServer.getPort()).build().get().header("X-Forwarded-Proto", "https") - .retrieve().bodyToMono(String.class).block(Duration.ofSeconds(30)); + String body = getWebClient(this.webServer.getPort()).build() + .get() + .header("X-Forwarded-Proto", "https") + .retrieve() + .bodyToMono(String.class) + .block(Duration.ofSeconds(30)); assertThat(body).isEqualTo("https"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/CertificateParserTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/CertificateParserTests.java index 7107c1ae7b..107154ed4e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/CertificateParserTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/CertificateParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,7 @@ class CertificateParserTests { void parseWithInvalidPathWillThrowException() { String path = "file:///bad/path/cert.pem"; assertThatIllegalStateException().isThrownBy(() -> CertificateParser.parse("file:///bad/path/cert.pem")) - .withMessageContaining(path); + .withMessageContaining(path); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/MimeMappingsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/MimeMappingsTests.java index b28a8e5dcc..43ea09452b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/MimeMappingsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/MimeMappingsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ class MimeMappingsTests { @Test void defaultsCannotBeModified() { assertThatExceptionOfType(UnsupportedOperationException.class) - .isThrownBy(() -> MimeMappings.DEFAULT.add("foo", "foo/bar")); + .isThrownBy(() -> MimeMappings.DEFAULT.add("foo", "foo/bar")); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/PrivateKeyParserTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/PrivateKeyParserTests.java index 31a5474803..390fb1b2b6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/PrivateKeyParserTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/PrivateKeyParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ class PrivateKeyParserTests { void parseWithNonKeyFileWillThrowException() { String path = "classpath:test-banner.txt"; assertThatIllegalStateException().isThrownBy(() -> PrivateKeyParser.parse("file://" + path)) - .withMessageContaining(path); + .withMessageContaining(path); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/SslConfigurationValidatorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/SslConfigurationValidatorTests.java index aef81cb9ca..95672ce2d9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/SslConfigurationValidatorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/SslConfigurationValidatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,16 +66,16 @@ class SslConfigurationValidatorTests { @Test void validateKeyAliasWhenAliasNotFoundShouldThrowException() { assertThatThrownBy(() -> SslConfigurationValidator.validateKeyAlias(this.keyStore, INVALID_ALIAS)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Keystore does not contain specified alias '" + INVALID_ALIAS + "'"); + .isInstanceOf(IllegalStateException.class) + .hasMessage("Keystore does not contain specified alias '" + INVALID_ALIAS + "'"); } @Test void validateKeyAliasWhenKeyStoreThrowsExceptionOnContains() throws KeyStoreException { KeyStore uninitializedKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); assertThatThrownBy(() -> SslConfigurationValidator.validateKeyAlias(uninitializedKeyStore, "alias")) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Could not determine if keystore contains alias 'alias'"); + .isInstanceOf(IllegalStateException.class) + .hasMessage("Could not determine if keystore contains alias 'alias'"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java index eb0adb7233..e4dc7cd22f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,8 +56,7 @@ class WebServerFactoryCustomizerBeanPostProcessorTests { @Test void setBeanFactoryWhenNotListableShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.processor.setBeanFactory(mock(BeanFactory.class))) - .withMessageContaining( - "WebServerCustomizerBeanPostProcessor can only be used with a ListableBeanFactory"); + .withMessageContaining("WebServerCustomizerBeanPostProcessor can only be used with a ListableBeanFactory"); } @Test @@ -153,7 +152,7 @@ class WebServerFactoryCustomizerBeanPostProcessorTests { @SuppressWarnings({ "unchecked", "rawtypes" }) private void addMockBeans(Map beans) { given(this.beanFactory.getBeansOfType(WebServerFactoryCustomizer.class, false, false)) - .willReturn((Map) beans); + .willReturn((Map) beans); } private void postProcessBeforeInitialization(Class type) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java index 998d376256..fa67944786 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,10 +87,10 @@ abstract class AbstractFilterRegistrationBeanTests { expectedInitParameters.put("a", "b"); expectedInitParameters.put("c", "d"); then(this.registration).should().setInitParameters(expectedInitParameters); - then(this.registration).should().addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/a", "/b", - "/c"); - then(this.registration).should().addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), true, "s4", "s5", - "s1", "s2", "s3"); + then(this.registration).should() + .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/a", "/b", "/c"); + then(this.registration).should() + .addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), true, "s4", "s5", "s1", "s2", "s3"); } @Test @@ -120,15 +120,15 @@ abstract class AbstractFilterRegistrationBeanTests { void setServletRegistrationBeanMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); assertThatIllegalArgumentException().isThrownBy(() -> bean.setServletRegistrationBeans(null)) - .withMessageContaining("ServletRegistrationBeans must not be null"); + .withMessageContaining("ServletRegistrationBeans must not be null"); } @Test void addServletRegistrationBeanMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); assertThatIllegalArgumentException() - .isThrownBy(() -> bean.addServletRegistrationBeans((ServletRegistrationBean[]) null)) - .withMessageContaining("ServletRegistrationBeans must not be null"); + .isThrownBy(() -> bean.addServletRegistrationBeans((ServletRegistrationBean[]) null)) + .withMessageContaining("ServletRegistrationBeans must not be null"); } @Test @@ -155,28 +155,28 @@ abstract class AbstractFilterRegistrationBeanTests { void setUrlPatternMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); assertThatIllegalArgumentException().isThrownBy(() -> bean.setUrlPatterns(null)) - .withMessageContaining("UrlPatterns must not be null"); + .withMessageContaining("UrlPatterns must not be null"); } @Test void addUrlPatternMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); assertThatIllegalArgumentException().isThrownBy(() -> bean.addUrlPatterns((String[]) null)) - .withMessageContaining("UrlPatterns must not be null"); + .withMessageContaining("UrlPatterns must not be null"); } @Test void setServletNameMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); assertThatIllegalArgumentException().isThrownBy(() -> bean.setServletNames(null)) - .withMessageContaining("ServletNames must not be null"); + .withMessageContaining("ServletNames must not be null"); } @Test void addServletNameMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); assertThatIllegalArgumentException().isThrownBy(() -> bean.addServletNames((String[]) null)) - .withMessageContaining("ServletNames must not be null"); + .withMessageContaining("ServletNames must not be null"); } @Test @@ -186,7 +186,7 @@ abstract class AbstractFilterRegistrationBeanTests { bean.setDispatcherTypes(DispatcherType.INCLUDE, DispatcherType.FORWARD); bean.onStartup(this.servletContext); then(this.registration).should() - .addMappingForUrlPatterns(EnumSet.of(DispatcherType.INCLUDE, DispatcherType.FORWARD), false, "/*"); + .addMappingForUrlPatterns(EnumSet.of(DispatcherType.INCLUDE, DispatcherType.FORWARD), false, "/*"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java index 10450eb49e..0934543a32 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,13 +52,13 @@ class DelegatingFilterProxyRegistrationBeanTests extends AbstractFilterRegistrat @Test void targetBeanNameMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingFilterProxyRegistrationBean(null)) - .withMessageContaining("TargetBeanName must not be null or empty"); + .withMessageContaining("TargetBeanName must not be null or empty"); } @Test void targetBeanNameMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingFilterProxyRegistrationBean("")) - .withMessageContaining("TargetBeanName must not be null or empty"); + .withMessageContaining("TargetBeanName must not be null or empty"); } @Test @@ -89,9 +89,8 @@ class DelegatingFilterProxyRegistrationBeanTests extends AbstractFilterRegistrat @Test void createServletRegistrationBeanMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy( - () -> new DelegatingFilterProxyRegistrationBean("mockFilter", (ServletRegistrationBean[]) null)) - .withMessageContaining("ServletRegistrationBeans must not be null"); + .isThrownBy(() -> new DelegatingFilterProxyRegistrationBean("mockFilter", (ServletRegistrationBean[]) null)) + .withMessageContaining("ServletRegistrationBeans must not be null"); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java index 17faa28d7a..83f39bfb28 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,20 +69,20 @@ class FilterRegistrationBeanTests extends AbstractFilterRegistrationBeanTests { void setFilterMustNotBeNull() { FilterRegistrationBean bean = new FilterRegistrationBean<>(); assertThatIllegalArgumentException().isThrownBy(() -> bean.onStartup(this.servletContext)) - .withMessageContaining("Filter must not be null"); + .withMessageContaining("Filter must not be null"); } @Test void constructFilterMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new FilterRegistrationBean<>(null)) - .withMessageContaining("Filter must not be null"); + .withMessageContaining("Filter must not be null"); } @Test void createServletRegistrationBeanMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new FilterRegistrationBean<>(this.filter, (ServletRegistrationBean[]) null)) - .withMessageContaining("ServletRegistrationBeans must not be null"); + .isThrownBy(() -> new FilterRegistrationBean<>(this.filter, (ServletRegistrationBean[]) null)) + .withMessageContaining("ServletRegistrationBeans must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java index a19452c8d2..8f3b41b0ac 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ class ServletComponentScanRegistrarTests { void packagesConfiguredWithValue() { this.context = new AnnotationConfigApplicationContext(ValuePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context - .getBean(ServletComponentRegisteringPostProcessor.class); + .getBean(ServletComponentRegisteringPostProcessor.class); assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", "com.example.bar"); } @@ -57,7 +57,7 @@ class ServletComponentScanRegistrarTests { this.context.registerBeanDefinition("valuePackages", new RootBeanDefinition(ValuePackages.class.getName())); this.context.refresh(); ServletComponentRegisteringPostProcessor postProcessor = this.context - .getBean(ServletComponentRegisteringPostProcessor.class); + .getBean(ServletComponentRegisteringPostProcessor.class); assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", "com.example.bar"); } @@ -65,7 +65,7 @@ class ServletComponentScanRegistrarTests { void packagesConfiguredWithBackPackages() { this.context = new AnnotationConfigApplicationContext(BasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context - .getBean(ServletComponentRegisteringPostProcessor.class); + .getBean(ServletComponentRegisteringPostProcessor.class); assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", "com.example.bar"); } @@ -73,23 +73,25 @@ class ServletComponentScanRegistrarTests { void packagesConfiguredWithBasePackageClasses() { this.context = new AnnotationConfigApplicationContext(BasePackageClasses.class); ServletComponentRegisteringPostProcessor postProcessor = this.context - .getBean(ServletComponentRegisteringPostProcessor.class); + .getBean(ServletComponentRegisteringPostProcessor.class); assertThat(postProcessor.getPackagesToScan()).contains(getClass().getPackage().getName()); } @Test void packagesConfiguredWithBothValueAndBasePackages() { assertThatExceptionOfType(AnnotationConfigurationException.class) - .isThrownBy(() -> this.context = new AnnotationConfigApplicationContext(ValueAndBasePackages.class)) - .withMessageContaining("'value'").withMessageContaining("'basePackages'") - .withMessageContaining("com.example.foo").withMessageContaining("com.example.bar"); + .isThrownBy(() -> this.context = new AnnotationConfigApplicationContext(ValueAndBasePackages.class)) + .withMessageContaining("'value'") + .withMessageContaining("'basePackages'") + .withMessageContaining("com.example.foo") + .withMessageContaining("com.example.bar"); } @Test void packagesFromMultipleAnnotationsAreMerged() { this.context = new AnnotationConfigApplicationContext(BasePackages.class, AdditionalPackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context - .getBean(ServletComponentRegisteringPostProcessor.class); + .getBean(ServletComponentRegisteringPostProcessor.class); assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", "com.example.bar", "com.example.baz"); } @@ -97,7 +99,7 @@ class ServletComponentScanRegistrarTests { void withNoBasePackagesScanningUsesBasePackageOfAnnotatedClass() { this.context = new AnnotationConfigApplicationContext(NoBasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context - .getBean(ServletComponentRegisteringPostProcessor.class); + .getBean(ServletComponentRegisteringPostProcessor.class); assertThat(postProcessor.getPackagesToScan()).containsExactly("org.springframework.boot.web.servlet"); } @@ -105,7 +107,7 @@ class ServletComponentScanRegistrarTests { void noBasePackageAndBasePackageAreCombinedCorrectly() { this.context = new AnnotationConfigApplicationContext(NoBasePackages.class, BasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context - .getBean(ServletComponentRegisteringPostProcessor.class); + .getBean(ServletComponentRegisteringPostProcessor.class); assertThat(postProcessor.getPackagesToScan()).containsExactlyInAnyOrder("org.springframework.boot.web.servlet", "com.example.foo", "com.example.bar"); } @@ -114,7 +116,7 @@ class ServletComponentScanRegistrarTests { void basePackageAndNoBasePackageAreCombinedCorrectly() { this.context = new AnnotationConfigApplicationContext(BasePackages.class, NoBasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context - .getBean(ServletComponentRegisteringPostProcessor.class); + .getBean(ServletComponentRegisteringPostProcessor.class); assertThat(postProcessor.getPackagesToScan()).containsExactlyInAnyOrder("org.springframework.boot.web.servlet", "com.example.foo", "com.example.bar"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java index 319c7e525a..4002829469 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,9 +77,10 @@ class ServletContextInitializerBeansTests { ServletContextInitializerBeans initializerBeans = new ServletContextInitializerBeans( this.context.getBeanFactory()); assertThat(initializerBeans).hasSize(1); - assertThat(initializerBeans).first().isInstanceOf(ServletListenerRegistrationBean.class) - .extracting((initializer) -> ((ServletListenerRegistrationBean) initializer).getListener()) - .isInstanceOf(HttpSessionIdListener.class); + assertThat(initializerBeans).first() + .isInstanceOf(ServletListenerRegistrationBean.class) + .extracting((initializer) -> ((ServletListenerRegistrationBean) initializer).getListener()) + .isInstanceOf(HttpSessionIdListener.class); } private void load(Class... configuration) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java index b934637bc1..740f26585e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,9 +65,10 @@ class ServletListenerRegistrationBeanTests { @Test void cannotRegisterUnsupportedType() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ServletListenerRegistrationBean<>(new EventListener() { + .isThrownBy(() -> new ServletListenerRegistrationBean<>(new EventListener() { - })).withMessageContaining("Listener is not of a supported type"); + })) + .withMessageContaining("Listener is not of a supported type"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java index f6a2d46080..3613756722 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -132,34 +132,34 @@ class ServletRegistrationBeanTests { void setServletMustNotBeNull() { ServletRegistrationBean bean = new ServletRegistrationBean<>(); assertThatIllegalArgumentException().isThrownBy(() -> bean.onStartup(this.servletContext)) - .withMessageContaining("Servlet must not be null"); + .withMessageContaining("Servlet must not be null"); } @Test void createServletMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ServletRegistrationBean(null)) - .withMessageContaining("Servlet must not be null"); + .withMessageContaining("Servlet must not be null"); } @Test void setMappingMustNotBeNull() { ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet); assertThatIllegalArgumentException().isThrownBy(() -> bean.setUrlMappings(null)) - .withMessageContaining("UrlMappings must not be null"); + .withMessageContaining("UrlMappings must not be null"); } @Test void createMappingMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ServletRegistrationBean<>(this.servlet, (String[]) null)) - .withMessageContaining("UrlMappings must not be null"); + .isThrownBy(() -> new ServletRegistrationBean<>(this.servlet, (String[]) null)) + .withMessageContaining("UrlMappings must not be null"); } @Test void addMappingMustNotBeNull() { ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet); assertThatIllegalArgumentException().isThrownBy(() -> bean.addUrlMappings((String[]) null)) - .withMessageContaining("UrlMappings must not be null"); + .withMessageContaining("UrlMappings must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java index 5174ee38ec..2356867f79 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,11 +60,11 @@ class WebFilterHandlerTests { AnnotatedBeanDefinition definition = createBeanDefinition(DefaultConfigurationFilter.class); this.handler.handle(definition, this.registry); BeanDefinition filterRegistrationBean = this.registry - .getBeanDefinition(DefaultConfigurationFilter.class.getName()); + .getBeanDefinition(DefaultConfigurationFilter.class.getName()); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); assertThat(propertyValues.get("asyncSupported")).isEqualTo(false); assertThat((EnumSet) propertyValues.get("dispatcherTypes")) - .containsExactly(DispatcherType.REQUEST); + .containsExactly(DispatcherType.REQUEST); assertThat(((Map) propertyValues.get("initParameters"))).isEmpty(); assertThat((String[]) propertyValues.get("servletNames")).isEmpty(); assertThat((String[]) propertyValues.get("urlPatterns")).isEmpty(); @@ -103,7 +103,7 @@ class WebFilterHandlerTests { BeanDefinition filterRegistrationBean = handleBeanDefinitionForClass(InitParametersFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); assertThat((Map) propertyValues.get("initParameters")).containsEntry("a", "alpha") - .containsEntry("b", "bravo"); + .containsEntry("b", "bravo"); } @Test @@ -130,8 +130,8 @@ class WebFilterHandlerTests { @Test void urlPatternsDeclaredTwice() { assertThatIllegalStateException() - .isThrownBy(() -> handleBeanDefinitionForClass(UrlPatternsDeclaredTwiceFilter.class)) - .withMessageContaining("The urlPatterns and value attributes are mutually exclusive."); + .isThrownBy(() -> handleBeanDefinitionForClass(UrlPatternsDeclaredTwiceFilter.class)) + .withMessageContaining("The urlPatterns and value attributes are mutually exclusive."); } private AnnotatedBeanDefinition createBeanDefinition(Class filterClass) throws IOException { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java index f787927469..a6914243bb 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,8 +46,9 @@ class WebListenerHandlerTests { void listener() throws IOException { AnnotatedBeanDefinition definition = mock(AnnotatedBeanDefinition.class); given(definition.getBeanClassName()).willReturn(TestListener.class.getName()); - given(definition.getMetadata()).willReturn(new SimpleMetadataReaderFactory() - .getMetadataReader(TestListener.class.getName()).getAnnotationMetadata()); + given(definition.getMetadata()) + .willReturn(new SimpleMetadataReaderFactory().getMetadataReader(TestListener.class.getName()) + .getAnnotationMetadata()); this.handler.handle(definition, this.registry); this.registry.getBeanDefinition(TestListener.class.getName() + "Registrar"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java index 8ecee00645..9b9e315b41 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ class WebServletHandlerTests { AnnotatedBeanDefinition servletDefinition = createBeanDefinition(DefaultConfigurationServlet.class); this.handler.handle(servletDefinition, this.registry); BeanDefinition servletRegistrationBean = this.registry - .getBeanDefinition(DefaultConfigurationServlet.class.getName()); + .getBeanDefinition(DefaultConfigurationServlet.class.getName()); MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); assertThat(propertyValues.get("asyncSupported")).isEqualTo(false); assertThat(((Map) propertyValues.get("initParameters"))).isEmpty(); @@ -85,7 +85,7 @@ class WebServletHandlerTests { BeanDefinition servletRegistrationBean = handleBeanDefinitionForClass(InitParametersServlet.class); MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); assertThat((Map) propertyValues.get("initParameters")).containsEntry("a", "alpha") - .containsEntry("b", "bravo"); + .containsEntry("b", "bravo"); } @Test @@ -105,8 +105,8 @@ class WebServletHandlerTests { @Test void urlPatternsDeclaredTwice() { assertThatIllegalStateException() - .isThrownBy(() -> handleBeanDefinitionForClass(UrlPatternsDeclaredTwiceServlet.class)) - .withMessageContaining("The urlPatterns and value attributes are mutually exclusive."); + .isThrownBy(() -> handleBeanDefinitionForClass(UrlPatternsDeclaredTwiceServlet.class)) + .withMessageContaining("The urlPatterns and value attributes are mutually exclusive."); } private AnnotatedBeanDefinition createBeanDefinition(Class servletClass) throws IOException { 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 418fd529d1..e60c376f04 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -114,10 +114,10 @@ class ServletWebServerApplicationContextTests { // Ensure that the context has been set up assertThat(this.context.getServletContext()).isEqualTo(factory.getServletContext()); then(factory.getServletContext()).should() - .setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); + .setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); // Ensure WebApplicationContextUtils.registerWebApplicationScopes was called assertThat(this.context.getBeanFactory().getRegisteredScope(WebApplicationContext.SCOPE_SESSION)) - .isInstanceOf(SessionScope.class); + .isInstanceOf(SessionScope.class); // Ensure WebApplicationContextUtils.registerEnvironmentBeans was called assertThat(this.context.containsBean(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME)).isTrue(); } @@ -138,8 +138,9 @@ class ServletWebServerApplicationContextTests { this.context.registerBeanDefinition("listener", new RootBeanDefinition(TestApplicationListener.class)); this.context.refresh(); List events = this.context.getBean(TestApplicationListener.class).receivedEvents(); - assertThat(events).hasSize(2).extracting("class").containsExactly(ServletWebServerInitializedEvent.class, - ContextRefreshedEvent.class); + assertThat(events).hasSize(2) + .extracting("class") + .containsExactly(ServletWebServerInitializedEvent.class, ContextRefreshedEvent.class); ServletWebServerInitializedEvent initializedEvent = (ServletWebServerInitializedEvent) events.get(0); assertThat(initializedEvent.getSource().getPort() >= 0).isTrue(); assertThat(initializedEvent.getApplicationContext()).isEqualTo(this.context); @@ -171,8 +172,9 @@ class ServletWebServerApplicationContextTests { this.context.refresh(); this.context.addApplicationListener(listener); this.context.close(); - assertThat(listener.receivedEvents()).hasSize(2).extracting("class").contains(AvailabilityChangeEvent.class, - ContextClosedEvent.class); + assertThat(listener.receivedEvents()).hasSize(2) + .extracting("class") + .contains(AvailabilityChangeEvent.class, ContextClosedEvent.class); } @Test @@ -205,8 +207,8 @@ class ServletWebServerApplicationContextTests { @Test void missingServletWebServerFactory() { assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh()) - .withMessageContaining("Unable to start ServletWebServerApplicationContext due to missing " - + "ServletWebServerFactory bean"); + .withMessageContaining("Unable to start ServletWebServerApplicationContext due to missing " + + "ServletWebServerFactory bean"); } @Test @@ -215,8 +217,8 @@ class ServletWebServerApplicationContextTests { this.context.registerBeanDefinition("webServerFactory2", new RootBeanDefinition(MockServletWebServerFactory.class)); assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh()) - .withMessageContaining("Unable to start ServletWebServerApplicationContext due to " - + "multiple ServletWebServerFactory beans"); + .withMessageContaining("Unable to start ServletWebServerApplicationContext due to " + + "multiple ServletWebServerFactory beans"); } @@ -305,9 +307,9 @@ class ServletWebServerApplicationContextTests { then(factory.getServletContext()).should(ordered).addFilter("filterBean1", filter1); then(factory.getServletContext()).should(ordered).addFilter("filterBean2", filter2); then(factory.getRegisteredFilter(0).getRegistration()).should() - .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*"); + .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*"); then(factory.getRegisteredFilter(1).getRegistration()).should() - .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*"); + .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*"); } @Test @@ -409,8 +411,8 @@ class ServletWebServerApplicationContextTests { // the delegate proxy will trigger creation and an exception assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> { this.filterCaptor.getValue().init(new MockFilterConfig()); - this.filterCaptor.getValue().doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), - new MockFilterChain()); + this.filterCaptor.getValue() + .doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain()); }).withMessageContaining("Create FilterBean Failure"); } @@ -464,7 +466,7 @@ class ServletWebServerApplicationContextTests { addWebServerFactoryBean(); this.context.refresh(); assertThat(this.context.getBeanFactory().getRegisteredScope(WebApplicationContext.SCOPE_APPLICATION)) - .isNotNull(); + .isNotNull(); } private void addWebServerFactoryBean() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContextTests.java index 04e0ea8749..87cb1f4e68 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,9 @@ import static org.mockito.BDDMockito.then; */ class XmlServletWebServerApplicationContextTests { - private static final String PATH = XmlServletWebServerApplicationContextTests.class.getPackage().getName() - .replace('.', '/') + "/"; + private static final String PATH = XmlServletWebServerApplicationContextTests.class.getPackage() + .getName() + .replace('.', '/') + "/"; private static final String FILE = "exampleEmbeddedWebApplicationConfiguration.xml"; diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributesTests.java index 6658819dd3..596e8a9226 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -90,7 +90,7 @@ class DefaultErrorAttributesTests { ErrorAttributeOptions.of(Include.MESSAGE)); assertThat(this.errorAttributes.getError(this.webRequest)).isSameAs(ex); assertThat(this.webRequest.getAttribute(ErrorAttributes.ERROR_ATTRIBUTE, WebRequest.SCOPE_REQUEST)) - .isSameAs(ex); + .isSameAs(ex); assertThat(modelAndView).isNull(); assertThat(attributes).doesNotContainKey("exception"); assertThat(attributes.get("message")).isEqualTo("Test"); @@ -104,7 +104,7 @@ class DefaultErrorAttributesTests { ErrorAttributeOptions.of(Include.MESSAGE)); assertThat(this.errorAttributes.getError(this.webRequest)).isSameAs(ex); assertThat(this.webRequest.getAttribute(ErrorAttributes.ERROR_ATTRIBUTE, WebRequest.SCOPE_REQUEST)) - .isSameAs(ex); + .isSameAs(ex); assertThat(attributes).doesNotContainKey("exception"); assertThat(attributes.get("message")).isEqualTo("Test"); } @@ -117,7 +117,7 @@ class DefaultErrorAttributesTests { ErrorAttributeOptions.defaults()); assertThat(this.errorAttributes.getError(this.webRequest)).isSameAs(ex); assertThat(this.webRequest.getAttribute(ErrorAttributes.ERROR_ATTRIBUTE, WebRequest.SCOPE_REQUEST)) - .isSameAs(ex); + .isSameAs(ex); assertThat(attributes).doesNotContainKey("exception"); assertThat(attributes).doesNotContainKey("message"); } @@ -168,7 +168,7 @@ class DefaultErrorAttributesTests { ErrorAttributeOptions.of(Include.MESSAGE)); assertThat(this.errorAttributes.getError(this.webRequest)).isSameAs(wrapped); assertThat(this.webRequest.getAttribute(ErrorAttributes.ERROR_ATTRIBUTE, WebRequest.SCOPE_REQUEST)) - .isSameAs(wrapped); + .isSameAs(wrapped); assertThat(attributes).doesNotContainKey("exception"); assertThat(attributes.get("message")).isEqualTo("Test"); } @@ -181,7 +181,7 @@ class DefaultErrorAttributesTests { ErrorAttributeOptions.of(Include.MESSAGE)); assertThat(this.errorAttributes.getError(this.webRequest)).isSameAs(error); assertThat(this.webRequest.getAttribute(ErrorAttributes.ERROR_ATTRIBUTE, WebRequest.SCOPE_REQUEST)) - .isSameAs(error); + .isSameAs(error); assertThat(attributes).doesNotContainKey("exception"); assertThat(attributes.get("message")).isEqualTo("Test error"); } @@ -217,7 +217,7 @@ class DefaultErrorAttributesTests { Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, options); if (options.isIncluded(Include.MESSAGE)) { assertThat(attributes.get("message")) - .isEqualTo("Validation failed for object='objectName'. Error count: 1"); + .isEqualTo("Validation failed for object='objectName'. Error count: 1"); } else { assertThat(attributes).doesNotContainKey("message"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/filter/ErrorPageSecurityFilterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/filter/ErrorPageSecurityFilterTests.java index 3bae2d22f5..69e3d7b226 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/filter/ErrorPageSecurityFilterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/filter/ErrorPageSecurityFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -157,7 +157,7 @@ class ErrorPageSecurityFilterTests { method.getName(), method.getParameterTypes()); assertThat(securityFilterMethod).isNotNull(); assertThat(securityFilterMethod.getDeclaringClass()).as(method.getName()) - .isEqualTo(ErrorPageSecurityFilter.class); + .isEqualTo(ErrorPageSecurityFilter.class); } } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java index 6ee488482d..f0a4be2796 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -178,23 +178,23 @@ public abstract class AbstractServletWebServerFactoryTests { private final HttpClientContext httpClientContext = HttpClientContext.create(); private final Supplier httpClientBuilder = () -> HttpClients.custom() - .setRetryHandler(new StandardHttpRequestRetryHandler(10, false) { - - @Override - public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { - boolean retry = super.retryRequest(exception, executionCount, context); - if (retry) { - try { - Thread.sleep(200); - } - catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } + .setRetryHandler(new StandardHttpRequestRetryHandler(10, false) { + + @Override + public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { + boolean retry = super.retryRequest(exception, executionCount, context); + if (retry) { + try { + Thread.sleep(200); + } + catch (InterruptedException ex) { + Thread.currentThread().interrupt(); } - return retry; } + return retry; + } - }); + }); @AfterEach void tearDown() { @@ -287,7 +287,7 @@ public abstract class AbstractServletWebServerFactoryTests { AbstractServletWebServerFactory factory = getFactory(); final InitCountingServlet servlet = new InitCountingServlet(); this.webServer = factory - .getWebServer((servletContext) -> servletContext.addServlet("test", servlet).setLoadOnStartup(1)); + .getWebServer((servletContext) -> servletContext.addServlet("test", servlet).setLoadOnStartup(1)); assertThat(servlet.getInitCount()).isEqualTo(0); this.webServer.start(); assertThat(servlet.getInitCount()).isEqualTo(1); @@ -337,19 +337,19 @@ public abstract class AbstractServletWebServerFactoryTests { @Test void contextPathMustStartWithSlash() { assertThatIllegalArgumentException().isThrownBy(() -> getFactory().setContextPath("missingslash")) - .withMessageContaining("ContextPath must start with '/' and not end with '/'"); + .withMessageContaining("ContextPath must start with '/' and not end with '/'"); } @Test void contextPathMustNotEndWithSlash() { assertThatIllegalArgumentException().isThrownBy(() -> getFactory().setContextPath("extraslash/")) - .withMessageContaining("ContextPath must start with '/' and not end with '/'"); + .withMessageContaining("ContextPath must start with '/' and not end with '/'"); } @Test void contextRootPathMustNotBeSlash() { assertThatIllegalArgumentException().isThrownBy(() -> getFactory().setContextPath("/")) - .withMessageContaining("Root ContextPath must be specified using an empty string"); + .withMessageContaining("Root ContextPath must be specified using an empty string"); } @Test @@ -435,7 +435,7 @@ public abstract class AbstractServletWebServerFactoryTests { HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); assertThatExceptionOfType(SSLException.class) - .isThrownBy(() -> getResponse(getLocalUrl("https", "/hello"), requestFactory)); + .isThrownBy(() -> getResponse(getLocalUrl("https", "/hello"), requestFactory)); } @Test @@ -462,8 +462,9 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer.start(); TrustStrategy trustStrategy = new SerialNumberValidatingTrustSelfSignedStrategy("3a3aaec8"); SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build(); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)) - .build(); + HttpClient httpClient = HttpClients.custom() + .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)) + .build(); String response = getResponse(getLocalUrl("https", "/hello"), new HttpComponentsClientHttpRequestFactory(httpClient)); assertThat(response).contains("scheme=https"); @@ -507,8 +508,10 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = this.httpClientBuilder.get().setSSLSocketFactory(socketFactory) - .setRetryHandler(new DefaultHttpRequestRetryHandler(10, false)).build(); + HttpClient httpClient = this.httpClientBuilder.get() + .setSSLSocketFactory(socketFactory) + .setRetryHandler(new DefaultHttpRequestRetryHandler(10, false)) + .build(); ClientHttpResponse response = getClientResponse(getLocalUrl("https", "/hello"), HttpMethod.GET, new HttpComponentsClientHttpRequestFactory(httpClient)); assertThat(response.getHeaders().get("Server")).containsExactly("MyServer"); @@ -538,7 +541,8 @@ public abstract class AbstractServletWebServerFactoryTests { loadStore(keyStore, new FileSystemResource("src/test/resources/test.p12")); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .loadKeyMaterial(keyStore, "secret".toCharArray()).build()); + .loadKeyMaterial(keyStore, "secret".toCharArray()) + .build()); HttpClient httpClient = this.httpClientBuilder.get().setSSLSocketFactory(socketFactory).build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); @@ -555,7 +559,8 @@ public abstract class AbstractServletWebServerFactoryTests { loadStore(keyStore, new FileSystemResource("src/test/resources/test.p12")); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .loadKeyMaterial(keyStore, "secret".toCharArray()).build()); + .loadKeyMaterial(keyStore, "secret".toCharArray()) + .build()); HttpClient httpClient = this.httpClientBuilder.get().setSSLSocketFactory(socketFactory).build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); @@ -573,7 +578,8 @@ public abstract class AbstractServletWebServerFactoryTests { loadStore(keyStore, new FileSystemResource("src/test/resources/test.jks")); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .loadKeyMaterial(keyStore, "password".toCharArray()).build()); + .loadKeyMaterial(keyStore, "password".toCharArray()) + .build()); HttpClient httpClient = this.httpClientBuilder.get().setSSLSocketFactory(socketFactory).build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); @@ -598,15 +604,16 @@ public abstract class AbstractServletWebServerFactoryTests { void sslWantsClientAuthenticationSucceedsWithClientCertificate() throws Exception { AbstractServletWebServerFactory factory = getFactory(); addTestTxtFile(factory); - factory.setSsl( - getSsl(ClientAuth.WANT, "password", "classpath:test.jks", null, new String[] { "TLSv1.2" }, null)); + factory + .setSsl(getSsl(ClientAuth.WANT, "password", "classpath:test.jks", null, new String[] { "TLSv1.2" }, null)); this.webServer = factory.getWebServer(); this.webServer.start(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); loadStore(keyStore, new FileSystemResource("src/test/resources/test.jks")); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .loadKeyMaterial(keyStore, "password".toCharArray()).build()); + .loadKeyMaterial(keyStore, "password".toCharArray()) + .build()); HttpClient httpClient = this.httpClientBuilder.get().setSSLSocketFactory(socketFactory).build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); @@ -644,7 +651,8 @@ public abstract class AbstractServletWebServerFactoryTests { loadStore(keyStore, new FileSystemResource("src/test/resources/test.jks")); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .loadKeyMaterial(keyStore, "password".toCharArray()).build()); + .loadKeyMaterial(keyStore, "password".toCharArray()) + .build()); HttpClient httpClient = this.httpClientBuilder.get().setSSLSocketFactory(socketFactory).build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); @@ -798,7 +806,7 @@ public abstract class AbstractServletWebServerFactoryTests { file.createNewFile(); factory.getSession().setStoreDir(file); assertThatIllegalStateException().isThrownBy(() -> factory.getValidSessionStoreDir(false)) - .withMessageContaining("points to a file"); + .withMessageContaining("points to a file"); } @Test @@ -886,7 +894,7 @@ public abstract class AbstractServletWebServerFactoryTests { AtomicReference contextReference = new AtomicReference<>(); this.webServer = factory.getWebServer(contextReference::set); assertThat(contextReference.get().getEffectiveSessionTrackingModes()) - .isEqualTo(EnumSet.of(javax.servlet.SessionTrackingMode.SSL)); + .isEqualTo(EnumSet.of(javax.servlet.SessionTrackingMode.SSL)); } @Test @@ -936,8 +944,8 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer = factory.getWebServer(); Map configuredMimeMappings = getActualMimeMappings(); Collection expectedMimeMappings = MimeMappings.DEFAULT.getAll(); - configuredMimeMappings.forEach( - (key, value) -> assertThat(expectedMimeMappings).contains(new MimeMappings.Mapping(key, value))); + configuredMimeMappings + .forEach((key, value) -> assertThat(expectedMimeMappings).contains(new MimeMappings.Mapping(key, value))); for (MimeMappings.Mapping mapping : expectedMimeMappings) { assertThat(configuredMimeMappings).containsEntry(mapping.getExtension(), mapping.getMimeType()); } @@ -1086,7 +1094,7 @@ public abstract class AbstractServletWebServerFactoryTests { factory.getWebServer(contextReference::set).start(); ServletContext servletContext = contextReference.get(); assertThat(servletContext.getEffectiveSessionTrackingModes()) - .isEqualTo(EnumSet.of(javax.servlet.SessionTrackingMode.COOKIE, javax.servlet.SessionTrackingMode.URL)); + .isEqualTo(EnumSet.of(javax.servlet.SessionTrackingMode.COOKIE, javax.servlet.SessionTrackingMode.URL)); assertThat(servletContext.getSessionCookieConfig().getName()).isEqualTo("testname"); assertThat(servletContext.getSessionCookieConfig().getDomain()).isEqualTo("testdomain"); assertThat(servletContext.getSessionCookieConfig().getPath()).isEqualTo("/testpath"); @@ -1109,9 +1117,9 @@ public abstract class AbstractServletWebServerFactoryTests { void exceptionThrownOnLoadFailureIsRethrown() { AbstractServletWebServerFactory factory = getFactory(); this.webServer = factory - .getWebServer((context) -> context.addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); + .getWebServer((context) -> context.addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); assertThatExceptionOfType(WebServerException.class).isThrownBy(this.webServer::start) - .satisfies(this::wrapsFailingServletException); + .satisfies(this::wrapsFailingServletException); } @Test @@ -1176,7 +1184,7 @@ public abstract class AbstractServletWebServerFactoryTests { AbstractServletWebServerFactory factory = getFactory(); BlockingServlet blockingServlet = new BlockingServlet(); this.webServer = factory - .getWebServer((context) -> context.addServlet("blockingServlet", blockingServlet).addMapping("/")); + .getWebServer((context) -> context.addServlet("blockingServlet", blockingServlet).addMapping("/")); this.webServer.start(); int port = this.webServer.getPort(); initiateGetRequest(port, "/"); @@ -1228,7 +1236,7 @@ public abstract class AbstractServletWebServerFactoryTests { factory.setShutdown(Shutdown.GRACEFUL); BlockingServlet blockingServlet = new BlockingServlet(); this.webServer = factory - .getWebServer((context) -> context.addServlet("blockingServlet", blockingServlet).addMapping("/")); + .getWebServer((context) -> context.addServlet("blockingServlet", blockingServlet).addMapping("/")); this.webServer.start(); int port = this.webServer.getPort(); initiateGetRequest(port, "/"); @@ -1237,7 +1245,7 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer.shutDownGracefully(result::set); this.webServer.stop(); assertThat(Awaitility.await().atMost(Duration.ofSeconds(30)).until(result::get, Objects::nonNull)) - .isEqualTo(GracefulShutdownResult.REQUESTS_ACTIVE); + .isEqualTo(GracefulShutdownResult.REQUESTS_ACTIVE); try { blockingServlet.admitOne(); } @@ -1294,8 +1302,10 @@ public abstract class AbstractServletWebServerFactoryTests { TestGzipInputStreamFactory inputStreamFactory = new TestGzipInputStreamFactory(); Map contentDecoderMap = Collections.singletonMap("gzip", inputStreamFactory); String response = getResponse(getLocalUrl("/test.txt"), method, - new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create().setUserAgent("testUserAgent") - .setContentDecoderRegistry(contentDecoderMap).build())); + new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create() + .setUserAgent("testUserAgent") + .setContentDecoderRegistry(contentDecoderMap) + .build())); assertThat(response).isEqualTo(testContent); return inputStreamFactory.wasCompressionUsed(); } @@ -1408,7 +1418,7 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer = factory.getWebServer(new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); this.webServer.start(); assertThat(getResponse(getLocalUrl("/hello"), "X-Forwarded-For:140.211.11.130")) - .contains("remoteaddr=140.211.11.130"); + .contains("remoteaddr=140.211.11.130"); } protected abstract AbstractServletWebServerFactory getFactory(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/CookieSameSiteSupplierTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/CookieSameSiteSupplierTests.java index f676d86217..3732260418 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/CookieSameSiteSupplierTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/CookieSameSiteSupplierTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,14 +40,14 @@ class CookieSameSiteSupplierTests { void whenHasNameWhenNameIsNullThrowsException() { CookieSameSiteSupplier supplier = (cookie) -> SameSite.LAX; assertThatIllegalArgumentException().isThrownBy(() -> supplier.whenHasName((String) null)) - .withMessage("Name must not be empty"); + .withMessage("Name must not be empty"); } @Test void whenHasNameWhenNameIsEmptyThrowsException() { CookieSameSiteSupplier supplier = (cookie) -> SameSite.LAX; assertThatIllegalArgumentException().isThrownBy(() -> supplier.whenHasName("")) - .withMessage("Name must not be empty"); + .withMessage("Name must not be empty"); } @Test @@ -66,7 +66,7 @@ class CookieSameSiteSupplierTests { void whenHasSuppliedNameWhenNameIsNullThrowsException() { CookieSameSiteSupplier supplier = (cookie) -> SameSite.LAX; assertThatIllegalArgumentException().isThrownBy(() -> supplier.whenHasName((Supplier) null)) - .withMessage("NameSupplier must not be empty"); + .withMessage("NameSupplier must not be empty"); } @Test @@ -85,14 +85,14 @@ class CookieSameSiteSupplierTests { void whenHasNameMatchingRegexWhenRegexIsNullThrowsException() { CookieSameSiteSupplier supplier = (cookie) -> SameSite.LAX; assertThatIllegalArgumentException().isThrownBy(() -> supplier.whenHasNameMatching((String) null)) - .withMessage("Regex must not be empty"); + .withMessage("Regex must not be empty"); } @Test void whenHasNameMatchingRegexWhenRegexIsEmptyThrowsException() { CookieSameSiteSupplier supplier = (cookie) -> SameSite.LAX; assertThatIllegalArgumentException().isThrownBy(() -> supplier.whenHasNameMatching("")) - .withMessage("Regex must not be empty"); + .withMessage("Regex must not be empty"); } @Test @@ -111,14 +111,14 @@ class CookieSameSiteSupplierTests { void whenHasNameMatchingPatternWhenPatternIsNullThrowsException() { CookieSameSiteSupplier supplier = (cookie) -> SameSite.LAX; assertThatIllegalArgumentException().isThrownBy(() -> supplier.whenHasNameMatching((Pattern) null)) - .withMessage("Pattern must not be null"); + .withMessage("Pattern must not be null"); } @Test void whenHasNameMatchingPatternWhenNameMatchesCallsGetSameSite() { CookieSameSiteSupplier supplier = (cookie) -> SameSite.LAX; assertThat(supplier.whenHasNameMatching(Pattern.compile("te.*")).getSameSite(new Cookie("test", "x"))) - .isEqualTo(SameSite.LAX); + .isEqualTo(SameSite.LAX); } @Test @@ -131,21 +131,21 @@ class CookieSameSiteSupplierTests { void whenWhenPredicateIsNullThrowsException() { CookieSameSiteSupplier supplier = (cookie) -> SameSite.LAX; assertThatIllegalArgumentException().isThrownBy(() -> supplier.when(null)) - .withMessage("Predicate must not be null"); + .withMessage("Predicate must not be null"); } @Test void whenWhenPredicateMatchesCallsGetSameSite() { CookieSameSiteSupplier supplier = (cookie) -> SameSite.LAX; assertThat(supplier.when((cookie) -> cookie.getName().equals("test")).getSameSite(new Cookie("test", "x"))) - .isEqualTo(SameSite.LAX); + .isEqualTo(SameSite.LAX); } @Test void whenWhenPredicateDoesNotMatchDoesNotCallGetSameSite() { CookieSameSiteSupplier supplier = (cookie) -> fail("Supplier Called"); assertThat(supplier.when((cookie) -> cookie.getName().equals("test")).getSameSite(new Cookie("tset", "x"))) - .isNull(); + .isNull(); } @Test @@ -166,13 +166,13 @@ class CookieSameSiteSupplierTests { @Test void ofWhenNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> CookieSameSiteSupplier.of(null)) - .withMessage("SameSite must not be null"); + .withMessage("SameSite must not be null"); } @Test void ofSuppliesValue() { assertThat(CookieSameSiteSupplier.of(SameSite.STRICT).getSameSite(new Cookie("test", "x"))) - .isEqualTo(SameSite.STRICT); + .isEqualTo(SameSite.STRICT); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/MockServletWebServerFactory.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/MockServletWebServerFactory.java index ab5ea2c14a..0372da6c07 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/MockServletWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/MockServletWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,8 +63,9 @@ public class MockServletWebServerFactory extends AbstractServletWebServerFactory extends org.springframework.boot.testsupport.web.servlet.MockServletWebServer implements WebServer { MockServletWebServer(ServletContextInitializer[] initializers, int port) { - super(Arrays.stream(initializers).map((initializer) -> (Initializer) initializer::onStartup) - .toArray(Initializer[]::new), port); + super(Arrays.stream(initializers) + .map((initializer) -> (Initializer) initializer::onStartup) + .toArray(Initializer[]::new), port); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterTests.java index 91a1473036..4444dc3c85 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -93,7 +93,7 @@ class ErrorPageFilterTests { this.filter.doFilter(this.request, this.response, this.chain); assertThat(((HttpServletResponse) this.chain.getResponse()).getStatus()).isEqualTo(201); assertThat(((HttpServletResponse) ((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .getStatus()).isEqualTo(201); + .getStatus()).isEqualTo(201); assertThat(this.response.isCommitted()).isTrue(); } @@ -251,7 +251,7 @@ class ErrorPageFilterTests { assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)).isEqualTo("BAD"); Map requestAttributes = getAttributesForDispatch("/500"); assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION_TYPE)) - .isEqualTo(IllegalStateException.class); + .isEqualTo(IllegalStateException.class); assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION)).isInstanceOf(IllegalStateException.class); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)).isNull(); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION)).isNull(); @@ -399,12 +399,12 @@ class ErrorPageFilterTests { assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(500); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)).isEqualTo(500); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) - .isEqualTo("Required request parameter 'test' for method parameter type string is not present"); + .isEqualTo("Required request parameter 'test' for method parameter type string is not present"); Map requestAttributes = getAttributesForDispatch("/500"); assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION_TYPE)) - .isEqualTo(MissingServletRequestParameterException.class); + .isEqualTo(MissingServletRequestParameterException.class); assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION)) - .isInstanceOf(MissingServletRequestParameterException.class); + .isInstanceOf(MissingServletRequestParameterException.class); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)).isNull(); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION)).isNull(); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)).isEqualTo("/test/path"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializerTests.java index 82ec8f217b..cec6bf4490 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,14 +48,14 @@ class ServletContextApplicationContextInitializerTests { void applicationContextIsNotStoredInServletContextByDefault() { new ServletContextApplicationContextInitializer(this.servletContext).initialize(this.applicationContext); then(this.servletContext).should(never()) - .setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.applicationContext); + .setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.applicationContext); } @Test void applicationContextCanBeStoredInServletContext() { new ServletContextApplicationContextInitializer(this.servletContext, true).initialize(this.applicationContext); - then(this.servletContext).should().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, - this.applicationContext); + then(this.servletContext).should() + .setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.applicationContext); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java index 84ac463bcb..3baf38e24f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,9 +81,8 @@ class SpringBootServletInitializerTests { @Test void failsWithoutConfigure() { assertThatIllegalStateException() - .isThrownBy( - () -> new MockSpringBootServletInitializer().createRootApplicationContext(this.servletContext)) - .withMessageContaining("No SpringApplication sources have been defined"); + .isThrownBy(() -> new MockSpringBootServletInitializer().createRootApplicationContext(this.servletContext)) + .withMessageContaining("No SpringApplication sources have been defined"); } @Test @@ -117,7 +116,7 @@ class SpringBootServletInitializerTests { void shutdownHooksAreNotRegistered() throws ServletException { new WithConfigurationAnnotation().onStartup(this.servletContext); assertThat(this.servletContext.getAttribute(LoggingApplicationListener.REGISTER_SHUTDOWN_HOOK_PROPERTY)) - .isEqualTo(false); + .isEqualTo(false); assertThat(this.application).hasFieldOrPropertyWithValue("registerShutdownHook", false); } @@ -125,7 +124,7 @@ class SpringBootServletInitializerTests { void errorPageFilterRegistrationCanBeDisabled() { WebServer webServer = new UndertowServletWebServerFactory(0).getWebServer((servletContext) -> { try (AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilterNotRegistered() - .createRootApplicationContext(servletContext)) { + .createRootApplicationContext(servletContext)) { assertThat(context.getBeansOfType(ErrorPageFilter.class)).hasSize(0); } }); @@ -142,9 +141,9 @@ class SpringBootServletInitializerTests { void errorPageFilterIsRegisteredWithNearHighestPrecedence() { WebServer webServer = new UndertowServletWebServerFactory(0).getWebServer((servletContext) -> { try (AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilter() - .createRootApplicationContext(servletContext)) { + .createRootApplicationContext(servletContext)) { Map registrations = context - .getBeansOfType(FilterRegistrationBean.class); + .getBeansOfType(FilterRegistrationBean.class); assertThat(registrations).hasSize(1); FilterRegistrationBean errorPageFilterRegistration = registrations.get("errorPageFilterRegistration"); assertThat(errorPageFilterRegistration.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE + 1); @@ -163,9 +162,9 @@ class SpringBootServletInitializerTests { void errorPageFilterIsRegisteredForRequestAndAsyncDispatch() { WebServer webServer = new UndertowServletWebServerFactory(0).getWebServer((servletContext) -> { try (AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilter() - .createRootApplicationContext(servletContext)) { + .createRootApplicationContext(servletContext)) { Map registrations = context - .getBeansOfType(FilterRegistrationBean.class); + .getBeansOfType(FilterRegistrationBean.class); assertThat(registrations).hasSize(1); FilterRegistrationBean errorPageFilterRegistration = registrations.get("errorPageFilterRegistration"); assertThat(errorPageFilterRegistration).hasFieldOrPropertyWithValue("dispatcherTypes", @@ -191,11 +190,11 @@ class SpringBootServletInitializerTests { void servletContextPropertySourceIsAvailablePriorToRefresh() { ServletContext servletContext = mock(ServletContext.class); given(servletContext.getInitParameterNames()) - .willReturn(Collections.enumeration(Collections.singletonList("spring.profiles.active"))); + .willReturn(Collections.enumeration(Collections.singletonList("spring.profiles.active"))); given(servletContext.getInitParameter("spring.profiles.active")).willReturn("from-servlet-context"); given(servletContext.getAttributeNames()).willReturn(Collections.emptyEnumeration()); try (ConfigurableApplicationContext context = (ConfigurableApplicationContext) new PropertySourceVerifyingSpringBootServletInitializer() - .createRootApplicationContext(servletContext)) { + .createRootApplicationContext(servletContext)) { assertThat(context.getEnvironment().getActiveProfiles()).containsExactly("from-servlet-context"); } } @@ -325,8 +324,9 @@ class SpringBootServletInitializerTests { @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { - PropertySource propertySource = event.getEnvironment().getPropertySources() - .get(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME); + PropertySource propertySource = event.getEnvironment() + .getPropertySources() + .get(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME); assertThat(propertySource.getProperty("spring.profiles.active")).isEqualTo("from-servlet-context"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestListener.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestListener.java index 0a8b0caeb8..8e944280d6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestListener.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,9 @@ public class TestListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { - sce.getServletContext().addFilter("listenerAddedFilter", new ListenerAddedFilter()) - .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*"); + sce.getServletContext() + .addFilter("listenerAddedFilter", new ListenerAddedFilter()) + .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*"); sce.getServletContext().setAttribute("listenerAttribute", "alpha"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestServlet.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestServlet.java index 0887548827..4e34e00cd0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestServlet.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,9 @@ public class TestServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - resp.getWriter().print(((String) req.getServletContext().getAttribute("listenerAttribute")) + " " - + req.getAttribute("filterAttribute") + " " + req.getAttribute("listenerAddedFilterAttribute")); + resp.getWriter() + .print(((String) req.getServletContext().getAttribute("listenerAttribute")) + " " + + req.getAttribute("filterAttribute") + " " + req.getAttribute("listenerAddedFilterAttribute")); resp.getWriter().flush(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests.java index ca0714134b..045cb0f692 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,8 @@ class HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests { @Test void buildWithCustomTimeouts() { WebServiceMessageSender messageSender = this.builder.setConnectTimeout(Duration.ofSeconds(5)) - .setReadTimeout(Duration.ofSeconds(2)).build(); + .setReadTimeout(Duration.ofSeconds(2)) + .build(); OkHttp3ClientHttpRequestFactory factory = assertOkHttp3RequestFactory(messageSender); OkHttpClient client = (OkHttpClient) ReflectionTestUtils.getField(factory, "client"); assertThat(client).isNotNull(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderSimpleIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderSimpleIntegrationTests.java index d65082cfba..7b0e9a9b00 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderSimpleIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderSimpleIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,8 @@ class HttpWebServiceMessageSenderBuilderSimpleIntegrationTests { @Test void buildWithCustomTimeouts() { WebServiceMessageSender messageSender = this.builder.setConnectTimeout(Duration.ofSeconds(5)) - .setReadTimeout(Duration.ofSeconds(2)).build(); + .setReadTimeout(Duration.ofSeconds(2)) + .build(); SimpleClientHttpRequestFactory requestFactory = assertSimpleClientRequestFactory(messageSender); assertThat(requestFactory).hasFieldOrPropertyWithValue("connectTimeout", 5000); assertThat(requestFactory).hasFieldOrPropertyWithValue("readTimeout", 2000); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderTests.java index 8a625255f9..a135298ba0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,17 +50,19 @@ class HttpWebServiceMessageSenderBuilderTests { void buildWithReadAndConnectTimeout() { ClientHttpRequestMessageSender messageSender = build( new HttpWebServiceMessageSenderBuilder().requestFactory(SimpleClientHttpRequestFactory::new) - .setConnectTimeout(Duration.ofSeconds(5)).setReadTimeout(Duration.ofSeconds(2))); + .setConnectTimeout(Duration.ofSeconds(5)) + .setReadTimeout(Duration.ofSeconds(2))); SimpleClientHttpRequestFactory requestFactory = (SimpleClientHttpRequestFactory) messageSender - .getRequestFactory(); + .getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("connectTimeout", 5000); assertThat(requestFactory).hasFieldOrPropertyWithValue("readTimeout", 2000); } @Test void buildUsesHttpComponentsByDefault() { - ClientHttpRequestMessageSender messageSender = build(new HttpWebServiceMessageSenderBuilder() - .setConnectTimeout(Duration.ofSeconds(5)).setReadTimeout(Duration.ofSeconds(2))); + ClientHttpRequestMessageSender messageSender = build( + new HttpWebServiceMessageSenderBuilder().setConnectTimeout(Duration.ofSeconds(5)) + .setReadTimeout(Duration.ofSeconds(2))); ClientHttpRequestFactory requestFactory = messageSender.getRequestFactory(); assertThat(requestFactory).isInstanceOf(HttpComponentsClientHttpRequestFactory.class); RequestConfig requestConfig = (RequestConfig) ReflectionTestUtils.getField(requestFactory, "requestConfig"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java index 550bc0f8c6..f6987ceb00 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -90,15 +90,15 @@ class WebServiceTemplateBuilderTests { @Test void messageSendersWhenSendersAreAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.messageSenders((WebServiceMessageSender[]) null)) - .withMessageContaining("MessageSenders must not be null"); + .isThrownBy(() -> this.builder.messageSenders((WebServiceMessageSender[]) null)) + .withMessageContaining("MessageSenders must not be null"); } @Test void messageSendersCollectionWhenSendersAreAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.messageSenders((Collection) null)) - .withMessageContaining("MessageSenders must not be null"); + .isThrownBy(() -> this.builder.messageSenders((Collection) null)) + .withMessageContaining("MessageSenders must not be null"); } @Test @@ -110,29 +110,32 @@ class WebServiceTemplateBuilderTests { @Test void messageSendersShouldReplaceExisting() { WebServiceTemplate template = this.builder.messageSenders(new ClientHttpRequestMessageSender()) - .messageSenders(this.messageSender).build(); + .messageSenders(this.messageSender) + .build(); assertThat(template.getMessageSenders()).containsOnly(this.messageSender); } @Test void additionalMessageSendersWhenSendersAreAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalMessageSenders((WebServiceMessageSender[]) null)) - .withMessageContaining("MessageSenders must not be null"); + .isThrownBy(() -> this.builder.additionalMessageSenders((WebServiceMessageSender[]) null)) + .withMessageContaining("MessageSenders must not be null"); } @Test void additionalMessageSendersCollectionWhenSendersAreAreNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.builder.additionalMessageSenders((Collection) null)) - .withMessageContaining("MessageSenders must not be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> this.builder.additionalMessageSenders((Collection) null)) + .withMessageContaining("MessageSenders must not be null"); } @Test void additionalMessageSendersShouldAddToExisting() { ClientHttpRequestMessageSender httpMessageSender = new ClientHttpRequestMessageSender(); WebServiceTemplate template = this.builder.messageSenders(httpMessageSender) - .additionalMessageSenders(this.messageSender).build(); + .additionalMessageSenders(this.messageSender) + .build(); assertThat(template.getMessageSenders()).containsOnly(httpMessageSender, this.messageSender); } @@ -146,14 +149,14 @@ class WebServiceTemplateBuilderTests { @Test void interceptorsWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.builder.interceptors((ClientInterceptor[]) null)) - .withMessageContaining("Interceptors must not be null"); + .withMessageContaining("Interceptors must not be null"); } @Test void interceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.interceptors((Collection) null)) - .withMessageContaining("Interceptors must not be null"); + .isThrownBy(() -> this.builder.interceptors((Collection) null)) + .withMessageContaining("Interceptors must not be null"); } @Test @@ -165,29 +168,31 @@ class WebServiceTemplateBuilderTests { @Test void interceptorsShouldReplaceExisting() { WebServiceTemplate template = this.builder.interceptors(mock(ClientInterceptor.class)) - .interceptors(Collections.singleton(this.interceptor)).build(); + .interceptors(Collections.singleton(this.interceptor)) + .build(); assertThat(template.getInterceptors()).containsOnly(this.interceptor); } @Test void additionalInterceptorsWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalInterceptors((ClientInterceptor[]) null)) - .withMessageContaining("Interceptors must not be null"); + .isThrownBy(() -> this.builder.additionalInterceptors((ClientInterceptor[]) null)) + .withMessageContaining("Interceptors must not be null"); } @Test void additionalInterceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalInterceptors((Set) null)) - .withMessageContaining("Interceptors must not be null"); + .isThrownBy(() -> this.builder.additionalInterceptors((Set) null)) + .withMessageContaining("Interceptors must not be null"); } @Test void additionalInterceptorsShouldAddToExisting() { ClientInterceptor interceptor = mock(ClientInterceptor.class); - WebServiceTemplate template = this.builder.interceptors(interceptor).additionalInterceptors(this.interceptor) - .build(); + WebServiceTemplate template = this.builder.interceptors(interceptor) + .additionalInterceptors(this.interceptor) + .build(); assertThat(template.getInterceptors()).containsOnly(interceptor, this.interceptor); } @@ -204,15 +209,15 @@ class WebServiceTemplateBuilderTests { @Test void customizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.customizers((WebServiceTemplateCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.customizers((WebServiceTemplateCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test void customizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.customizers((Collection) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.customizers((Collection) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -235,7 +240,8 @@ class WebServiceTemplateBuilderTests { WebServiceTemplateCustomizer customizer1 = mock(WebServiceTemplateCustomizer.class); WebServiceTemplateCustomizer customizer2 = mock(WebServiceTemplateCustomizer.class); WebServiceTemplate template = this.builder.customizers(customizer1) - .customizers(Collections.singleton(customizer2)).build(); + .customizers(Collections.singleton(customizer2)) + .build(); then(customizer1).shouldHaveNoInteractions(); then(customizer2).should().customize(template); } @@ -243,15 +249,16 @@ class WebServiceTemplateBuilderTests { @Test void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalCustomizers((WebServiceTemplateCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.additionalCustomizers((WebServiceTemplateCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.builder.additionalCustomizers((Collection) null)) - .withMessageContaining("Customizers must not be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> this.builder.additionalCustomizers((Collection) null)) + .withMessageContaining("Customizers must not be null"); } @Test diff --git a/spring-boot-system-tests/spring-boot-deployment-tests/src/systemTest/java/org/springframework/boot/deployment/AbstractDeploymentTests.java b/spring-boot-system-tests/spring-boot-deployment-tests/src/systemTest/java/org/springframework/boot/deployment/AbstractDeploymentTests.java index 6ca992192b..aabccad35e 100644 --- a/spring-boot-system-tests/spring-boot-deployment-tests/src/systemTest/java/org/springframework/boot/deployment/AbstractDeploymentTests.java +++ b/spring-boot-system-tests/spring-boot-deployment-tests/src/systemTest/java/org/springframework/boot/deployment/AbstractDeploymentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -93,11 +93,11 @@ abstract class AbstractDeploymentTests { private void test(Consumer consumer) { TestRestTemplate rest = new TestRestTemplate(new RestTemplateBuilder() - .rootUri("http://" + this.container.getHost() + ":" + this.container.getMappedPort(this.port) - + "/spring-boot") - .basicAuthentication("test", "test") - .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(HttpClients.custom() - .setRetryHandler(new StandardHttpRequestRetryHandler(10, false)).build()))); + .rootUri("http://" + this.container.getHost() + ":" + this.container.getMappedPort(this.port) + + "/spring-boot") + .basicAuthentication("test", "test") + .requestFactory(() -> new HttpComponentsClientHttpRequestFactory( + HttpClients.custom().setRetryHandler(new StandardHttpRequestRetryHandler(10, false)).build()))); try { Awaitility.await().atMost(Duration.ofMinutes(10)).until(() -> { try { @@ -121,8 +121,9 @@ abstract class AbstractDeploymentTests { WarDeploymentContainer(String baseImage, String deploymentLocation, int port) { super(new ImageFromDockerfile().withFileFromFile("spring-boot.war", findWarToDeploy()) - .withDockerfileFromBuilder((builder) -> builder.from(baseImage) - .add("spring-boot.war", deploymentLocation + "/spring-boot.war").build())); + .withDockerfileFromBuilder((builder) -> builder.from(baseImage) + .add("spring-boot.war", deploymentLocation + "/spring-boot.war") + .build())); withExposedPorts(port).withStartupTimeout(Duration.ofMinutes(5)).withStartupAttempts(3); } diff --git a/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/paketo/LayersIndex.java b/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/paketo/LayersIndex.java index 34460dbbe6..43c5938ab8 100644 --- a/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/paketo/LayersIndex.java +++ b/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/paketo/LayersIndex.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,10 @@ import org.yaml.snakeyaml.constructor.Constructor; class LayersIndex extends ArrayList>> { List getLayer(String layerName) { - return stream().filter((entry) -> entry.containsKey(layerName)).findFirst().map((entry) -> entry.get(layerName)) - .orElse(Collections.emptyList()); + return stream().filter((entry) -> entry.containsKey(layerName)) + .findFirst() + .map((entry) -> entry.get(layerName)) + .orElse(Collections.emptyList()); } static LayersIndex fromArchiveFile(File archiveFile) throws IOException { diff --git a/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/paketo/PaketoBuilderTests.java b/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/paketo/PaketoBuilderTests.java index a04a99a0eb..86ce995ded 100644 --- a/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/paketo/PaketoBuilderTests.java +++ b/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/paketo/PaketoBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,13 +87,16 @@ class PaketoBuilderTests { ContainerConfig config = container.getContainerInfo().getConfig(); assertLabelsMatchManifestAttributes(config); ImageAssertions.assertThat(config).buildMetadata((metadata) -> { - metadata.buildpacks().contains("paketo-buildpacks/ca-certificates", - "paketo-buildpacks/bellsoft-liberica", "paketo-buildpacks/executable-jar", - "paketo-buildpacks/dist-zip", "paketo-buildpacks/spring-boot"); - metadata.processOfType("web").extracting("command", "args").containsExactly("java", - Collections.singletonList("org.springframework.boot.loader.JarLauncher")); - metadata.processOfType("executable-jar").extracting("command", "args").containsExactly("java", - Collections.singletonList("org.springframework.boot.loader.JarLauncher")); + metadata.buildpacks() + .contains("paketo-buildpacks/ca-certificates", "paketo-buildpacks/bellsoft-liberica", + "paketo-buildpacks/executable-jar", "paketo-buildpacks/dist-zip", + "paketo-buildpacks/spring-boot"); + metadata.processOfType("web") + .extracting("command", "args") + .containsExactly("java", Collections.singletonList("org.springframework.boot.loader.JarLauncher")); + metadata.processOfType("executable-jar") + .extracting("command", "args") + .containsExactly("java", Collections.singletonList("org.springframework.boot.loader.JarLauncher")); }); assertImageHasSbomLayer(imageReference, config, "executable-jar"); assertImageLayersMatchLayersIndex(imageReference, config); @@ -157,21 +160,25 @@ class PaketoBuilderTests { container.waitingFor(Wait.forHttp("/test")).start(); ContainerConfig config = container.getContainerInfo().getConfig(); ImageAssertions.assertThat(config).buildMetadata((metadata) -> { - metadata.buildpacks().contains("paketo-buildpacks/ca-certificates", - "paketo-buildpacks/bellsoft-liberica", "paketo-buildpacks/dist-zip", - "paketo-buildpacks/spring-boot"); - metadata.processOfType("web").extracting("command", "args").containsExactly( - "/workspace/" + projectName + "-boot/bin/" + projectName, Collections.emptyList()); - metadata.processOfType("dist-zip").extracting("command", "args").containsExactly( - "/workspace/" + projectName + "-boot/bin/" + projectName, Collections.emptyList()); + metadata.buildpacks() + .contains("paketo-buildpacks/ca-certificates", "paketo-buildpacks/bellsoft-liberica", + "paketo-buildpacks/dist-zip", "paketo-buildpacks/spring-boot"); + metadata.processOfType("web") + .extracting("command", "args") + .containsExactly("/workspace/" + projectName + "-boot/bin/" + projectName, Collections.emptyList()); + metadata.processOfType("dist-zip") + .extracting("command", "args") + .containsExactly("/workspace/" + projectName + "-boot/bin/" + projectName, Collections.emptyList()); }); assertImageHasSbomLayer(imageReference, config, "dist-zip"); DigestCapturingCondition digest = new DigestCapturingCondition(); ImageAssertions.assertThat(config) - .lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(1, digest)); - ImageAssertions.assertThat(imageReference).layer(digest.getDigest(), - (layer) -> layer.entries().contains(projectName + "-boot/bin/" + projectName, - projectName + "-boot/lib/" + projectName + ".jar")); + .lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(1, digest)); + ImageAssertions.assertThat(imageReference) + .layer(digest.getDigest(), + (layer) -> layer.entries() + .contains(projectName + "-boot/bin/" + projectName, + projectName + "-boot/lib/" + projectName + ".jar")); } finally { removeImage(imageReference); @@ -191,19 +198,22 @@ class PaketoBuilderTests { container.waitingFor(Wait.forHttp("/test")).start(); ContainerConfig config = container.getContainerInfo().getConfig(); ImageAssertions.assertThat(config).buildMetadata((metadata) -> { - metadata.buildpacks().contains("paketo-buildpacks/ca-certificates", - "paketo-buildpacks/bellsoft-liberica", "paketo-buildpacks/dist-zip", - "paketo-buildpacks/spring-boot"); - metadata.processOfType("web").extracting("command", "args") - .containsExactly("/workspace/" + projectName + "/bin/" + projectName, Collections.emptyList()); - metadata.processOfType("dist-zip").extracting("command", "args") - .containsExactly("/workspace/" + projectName + "/bin/" + projectName, Collections.emptyList()); + metadata.buildpacks() + .contains("paketo-buildpacks/ca-certificates", "paketo-buildpacks/bellsoft-liberica", + "paketo-buildpacks/dist-zip", "paketo-buildpacks/spring-boot"); + metadata.processOfType("web") + .extracting("command", "args") + .containsExactly("/workspace/" + projectName + "/bin/" + projectName, Collections.emptyList()); + metadata.processOfType("dist-zip") + .extracting("command", "args") + .containsExactly("/workspace/" + projectName + "/bin/" + projectName, Collections.emptyList()); }); assertImageHasSbomLayer(imageReference, config, "dist-zip"); DigestCapturingCondition digest = new DigestCapturingCondition(); ImageAssertions.assertThat(config) - .lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(1, digest)); - ImageAssertions.assertThat(imageReference).layer(digest.getDigest(), (layer) -> layer.entries() + .lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(1, digest)); + ImageAssertions.assertThat(imageReference) + .layer(digest.getDigest(), (layer) -> layer.entries() .contains(projectName + "/bin/" + projectName, projectName + "/lib/" + projectName + "-plain.jar") .anyMatch((s) -> s.startsWith(projectName + "/lib/spring-boot-")) .anyMatch((s) -> s.startsWith(projectName + "/lib/spring-core-")) @@ -228,13 +238,16 @@ class PaketoBuilderTests { ContainerConfig config = container.getContainerInfo().getConfig(); assertLabelsMatchManifestAttributes(config); ImageAssertions.assertThat(config).buildMetadata((metadata) -> { - metadata.buildpacks().contains("paketo-buildpacks/ca-certificates", - "paketo-buildpacks/bellsoft-liberica", "paketo-buildpacks/executable-jar", - "paketo-buildpacks/dist-zip", "paketo-buildpacks/spring-boot"); - metadata.processOfType("web").extracting("command", "args").containsExactly("java", - Collections.singletonList("org.springframework.boot.loader.WarLauncher")); - metadata.processOfType("executable-jar").extracting("command", "args").containsExactly("java", - Collections.singletonList("org.springframework.boot.loader.WarLauncher")); + metadata.buildpacks() + .contains("paketo-buildpacks/ca-certificates", "paketo-buildpacks/bellsoft-liberica", + "paketo-buildpacks/executable-jar", "paketo-buildpacks/dist-zip", + "paketo-buildpacks/spring-boot"); + metadata.processOfType("web") + .extracting("command", "args") + .containsExactly("java", Collections.singletonList("org.springframework.boot.loader.WarLauncher")); + metadata.processOfType("executable-jar") + .extracting("command", "args") + .containsExactly("java", Collections.singletonList("org.springframework.boot.loader.WarLauncher")); }); assertImageHasSbomLayer(imageReference, config, "executable-jar"); assertImageLayersMatchLayersIndex(imageReference, config); @@ -257,20 +270,24 @@ class PaketoBuilderTests { container.waitingFor(Wait.forHttp("/test")).start(); ContainerConfig config = container.getContainerInfo().getConfig(); ImageAssertions.assertThat(config).buildMetadata((metadata) -> { - metadata.buildpacks().contains("paketo-buildpacks/ca-certificates", - "paketo-buildpacks/bellsoft-liberica", "paketo-buildpacks/apache-tomcat", - "paketo-buildpacks/dist-zip", "paketo-buildpacks/spring-boot"); - metadata.processOfType("web").extracting("command", "args").containsExactly("bash", - Arrays.asList("catalina.sh", "run")); - metadata.processOfType("tomcat").extracting("command", "args").containsExactly("bash", - Arrays.asList("catalina.sh", "run")); + metadata.buildpacks() + .contains("paketo-buildpacks/ca-certificates", "paketo-buildpacks/bellsoft-liberica", + "paketo-buildpacks/apache-tomcat", "paketo-buildpacks/dist-zip", + "paketo-buildpacks/spring-boot"); + metadata.processOfType("web") + .extracting("command", "args") + .containsExactly("bash", Arrays.asList("catalina.sh", "run")); + metadata.processOfType("tomcat") + .extracting("command", "args") + .containsExactly("bash", Arrays.asList("catalina.sh", "run")); }); assertImageHasSbomLayer(imageReference, config, "apache-tomcat"); DigestCapturingCondition digest = new DigestCapturingCondition(); ImageAssertions.assertThat(config) - .lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(1, digest)); - ImageAssertions.assertThat(imageReference).layer(digest.getDigest(), - (layer) -> layer.entries() + .lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(1, digest)); + ImageAssertions.assertThat(imageReference) + .layer(digest.getDigest(), + (layer) -> layer.entries() .contains("WEB-INF/classes/example/ExampleApplication.class", "WEB-INF/classes/example/HelloController.class", "META-INF/MANIFEST.MF") .anyMatch((s) -> s.startsWith("WEB-INF/lib/spring-boot-")) @@ -364,21 +381,22 @@ class PaketoBuilderTests { DigestCapturingCondition digest = new DigestCapturingCondition(); ImageAssertions.assertThat(config).lifecycleMetadata((metadata) -> metadata.sbomLayerSha().has(digest)); ImageAssertions.assertThat(imageReference).layer(digest.getDigest(), (layer) -> { - layer.entries().contains("/layers/sbom/launch/paketo-buildpacks_bellsoft-liberica/jre/sbom.syft.json", - "/layers/sbom/launch/paketo-buildpacks_" + buildpack + "/sbom.syft.json", - "/layers/sbom/launch/paketo-buildpacks_" + buildpack + "/sbom.cdx.json"); + layer.entries() + .contains("/layers/sbom/launch/paketo-buildpacks_bellsoft-liberica/jre/sbom.syft.json", + "/layers/sbom/launch/paketo-buildpacks_" + buildpack + "/sbom.syft.json", + "/layers/sbom/launch/paketo-buildpacks_" + buildpack + "/sbom.cdx.json"); layer.jsonEntry("/layers/sbom/launch/paketo-buildpacks_bellsoft-liberica/jre/sbom.syft.json", (json) -> { json.extractingJsonPathStringValue("$.Artifacts[0].Name").isEqualTo("BellSoft Liberica JRE"); json.extractingJsonPathStringValue("$.Artifacts[0].Version").startsWith(javaMajorVersion()); }); layer.jsonEntry("/layers/sbom/launch/paketo-buildpacks_" + buildpack + "/sbom.syft.json", - (json) -> json.extractingJsonPathArrayValue("$.artifacts.[*].name").contains("spring-beans", - "spring-boot", "spring-boot-autoconfigure", "spring-context", "spring-core", - "spring-expression", "spring-jcl", "spring-web", "spring-webmvc")); + (json) -> json.extractingJsonPathArrayValue("$.artifacts.[*].name") + .contains("spring-beans", "spring-boot", "spring-boot-autoconfigure", "spring-context", + "spring-core", "spring-expression", "spring-jcl", "spring-web", "spring-webmvc")); layer.jsonEntry("/layers/sbom/launch/paketo-buildpacks_" + buildpack + "/sbom.cdx.json", - (json) -> json.extractingJsonPathArrayValue("$.components.[*].name").contains("spring-beans", - "spring-boot", "spring-boot-autoconfigure", "spring-context", "spring-core", - "spring-expression", "spring-jcl", "spring-web", "spring-webmvc")); + (json) -> json.extractingJsonPathArrayValue("$.components.[*].name") + .contains("spring-beans", "spring-boot", "spring-boot-autoconfigure", "spring-context", + "spring-core", "spring-expression", "spring-jcl", "spring-web", "spring-webmvc")); }); } @@ -386,18 +404,23 @@ class PaketoBuilderTests { throws IOException { DigestsCapturingCondition digests = new DigestsCapturingCondition(); ImageAssertions.assertThat(config) - .lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(5, digests)); + .lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(5, digests)); LayersIndex layersIndex = LayersIndex.fromArchiveFile(projectArchiveFile()); - ImageAssertions.assertThat(imageReference).layer(digests.getDigest(0), (layer) -> layer.entries() + ImageAssertions.assertThat(imageReference) + .layer(digests.getDigest(0), (layer) -> layer.entries() .allMatch((entry) -> startsWithOneOf(entry, layersIndex.getLayer("dependencies")))); - ImageAssertions.assertThat(imageReference).layer(digests.getDigest(1), (layer) -> layer.entries() + ImageAssertions.assertThat(imageReference) + .layer(digests.getDigest(1), (layer) -> layer.entries() .allMatch((entry) -> startsWithOneOf(entry, layersIndex.getLayer("spring-boot-loader")))); - ImageAssertions.assertThat(imageReference).layer(digests.getDigest(2), (layer) -> layer.entries() + ImageAssertions.assertThat(imageReference) + .layer(digests.getDigest(2), (layer) -> layer.entries() .allMatch((entry) -> startsWithOneOf(entry, layersIndex.getLayer("snapshot-dependencies")))); - ImageAssertions.assertThat(imageReference).layer(digests.getDigest(3), (layer) -> layer.entries() + ImageAssertions.assertThat(imageReference) + .layer(digests.getDigest(3), (layer) -> layer.entries() .allMatch((entry) -> startsWithOneOf(entry, layersIndex.getLayer("application")))); - ImageAssertions.assertThat(imageReference).layer(digests.getDigest(4), - (layer) -> layer.entries().allMatch((entry) -> entry.contains("lib/spring-cloud-bindings-"))); + ImageAssertions.assertThat(imageReference) + .layer(digests.getDigest(4), + (layer) -> layer.entries().allMatch((entry) -> entry.contains("lib/spring-cloud-bindings-"))); } private File projectArchiveFile() { diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/intTest/java/org/springframework/boot/launchscript/AbstractLaunchScriptIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/intTest/java/org/springframework/boot/launchscript/AbstractLaunchScriptIntegrationTests.java index 9ac808f3ef..d2ae746d6e 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/intTest/java/org/springframework/boot/launchscript/AbstractLaunchScriptIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/intTest/java/org/springframework/boot/launchscript/AbstractLaunchScriptIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -100,8 +100,8 @@ abstract class AbstractLaunchScriptIntegrationTests { private LaunchScriptTestContainer(String os, String version, String scriptsDir, String testScript) { super(new ImageFromDockerfile("spring-boot-launch-script/" + os.toLowerCase() + "-" + version) - .withFileFromFile("Dockerfile", - new File("src/intTest/resources/conf/" + os + "/" + version + "/Dockerfile"))); + .withFileFromFile("Dockerfile", + new File("src/intTest/resources/conf/" + os + "/" + version + "/Dockerfile"))); withCopyFileToContainer(MountableFile.forHostPath(findApplication().getAbsolutePath()), "/app.jar"); withCopyFileToContainer( MountableFile.forHostPath("src/intTest/resources/scripts/" + scriptsDir + "test-functions.sh"), diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/intTest/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/intTest/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIntegrationTests.java index 9224877c3f..0275aec325 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/intTest/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/intTest/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,7 +68,7 @@ class SysVinitLaunchScriptIntegrationTests extends AbstractLaunchScriptIntegrati String output = doTest(os, version, "status-when-killed.sh"); assertThat(output).contains("Status: 1"); assertThat(output) - .has(coloredString(AnsiColor.RED, "Not running (process " + extractPid(output) + " not found)")); + .has(coloredString(AnsiColor.RED, "Not running (process " + extractPid(output) + " not found)")); } @ParameterizedTest(name = "{0} {1}") @@ -133,16 +133,16 @@ class SysVinitLaunchScriptIntegrationTests extends AbstractLaunchScriptIntegrati @MethodSource("parameters") void launchWithMissingLogFolderGeneratesAWarning(String os, String version) throws Exception { String output = doTest(os, version, "launch-with-missing-log-folder.sh"); - assertThat(output).has( - coloredString(AnsiColor.YELLOW, "LOG_FOLDER /does/not/exist does not exist. Falling back to /tmp")); + assertThat(output) + .has(coloredString(AnsiColor.YELLOW, "LOG_FOLDER /does/not/exist does not exist. Falling back to /tmp")); } @ParameterizedTest(name = "{0} {1}") @MethodSource("parameters") void launchWithMissingPidFolderGeneratesAWarning(String os, String version) throws Exception { String output = doTest(os, version, "launch-with-missing-pid-folder.sh"); - assertThat(output).has( - coloredString(AnsiColor.YELLOW, "PID_FOLDER /does/not/exist does not exist. Falling back to /tmp")); + assertThat(output) + .has(coloredString(AnsiColor.YELLOW, "PID_FOLDER /does/not/exist does not exist. Falling back to /tmp")); } @ParameterizedTest(name = "{0} {1}") diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-loader-tests/src/intTest/java/org/springframework/boot/loader/LoaderIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-loader-tests/src/intTest/java/org/springframework/boot/loader/LoaderIntegrationTests.java index e51af0d8e7..afcdb9975c 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-loader-tests/src/intTest/java/org/springframework/boot/loader/LoaderIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-loader-tests/src/intTest/java/org/springframework/boot/loader/LoaderIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,16 +54,19 @@ class LoaderIntegrationTests { try (GenericContainer container = createContainer(javaRuntime)) { container.start(); System.out.println(this.output.toUtf8String()); - assertThat(this.output.toUtf8String()).contains(">>>>> 287649 BYTES from").doesNotContain("WARNING:") - .doesNotContain("illegal").doesNotContain("jar written to temp"); + assertThat(this.output.toUtf8String()).contains(">>>>> 287649 BYTES from") + .doesNotContain("WARNING:") + .doesNotContain("illegal") + .doesNotContain("jar written to temp"); } } private GenericContainer createContainer(JavaRuntime javaRuntime) { - return javaRuntime.getContainer().withLogConsumer(this.output) - .withCopyFileToContainer(MountableFile.forHostPath(findApplication().toPath()), "/app.jar") - .withStartupCheckStrategy(new OneShotStartupCheckStrategy().withTimeout(Duration.ofMinutes(5))) - .withCommand("java", "-jar", "app.jar"); + return javaRuntime.getContainer() + .withLogConsumer(this.output) + .withCopyFileToContainer(MountableFile.forHostPath(findApplication().toPath()), "/app.jar") + .withStartupCheckStrategy(new OneShotStartupCheckStrategy().withTimeout(Duration.ofMinutes(5))) + .withCommand("java", "-jar", "app.jar"); } private File findApplication() { @@ -118,7 +121,7 @@ class LoaderIntegrationTests { static JavaRuntime oracleJdk17() { ImageFromDockerfile image = new ImageFromDockerfile("spring-boot-loader/oracle-jdk-17") - .withFileFromFile("Dockerfile", new File("src/intTest/resources/conf/oracle-jdk-17/Dockerfile")); + .withFileFromFile("Dockerfile", new File("src/intTest/resources/conf/oracle-jdk-17/Dockerfile")); return new JavaRuntime("Oracle JDK 17", JavaVersion.SEVENTEEN, () -> new GenericContainer<>(image)); } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServerContainerInvocationContextProvider.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServerContainerInvocationContextProvider.java index 5b779de775..7bd12e09ac 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServerContainerInvocationContextProvider.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServerContainerInvocationContextProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -80,18 +80,15 @@ class EmbeddedServerContainerInvocationContextProvider @Override public Stream provideTestTemplateInvocationContexts(ExtensionContext context) { EmbeddedServletContainerTest annotation = context.getRequiredTestClass() - .getAnnotation(EmbeddedServletContainerTest.class); - return CONTAINERS - .stream().map( - (container) -> getApplication(annotation, container)) - .flatMap( - (builder) -> Stream - .of(annotation.launchers()).map( - (launcherClass) -> getAbstractApplicationLauncher(builder, launcherClass)) - .map((launcher) -> new EmbeddedServletContainerInvocationContext( - StringUtils.capitalize(builder.getContainer()) + ": " - + launcher.getDescription(builder.getPackaging()), - launcher))); + .getAnnotation(EmbeddedServletContainerTest.class); + return CONTAINERS.stream() + .map((container) -> getApplication(annotation, container)) + .flatMap((builder) -> Stream.of(annotation.launchers()) + .map((launcherClass) -> getAbstractApplicationLauncher(builder, launcherClass)) + .map((launcher) -> new EmbeddedServletContainerInvocationContext( + StringUtils.capitalize(builder.getContainer()) + ": " + + launcher.getDescription(builder.getPackaging()), + launcher))); } @Override diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java index 04fe90fd5d..9b768e7fea 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,7 +68,7 @@ class EmbeddedServletContainerJarPackagingIntegrationTests { @TestTemplate void applicationClassesAreNotAvailableViaHttp(RestTemplate rest) { ResponseEntity entity = rest - .getForEntity("/BOOT-INF/classes/com/example/ResourceHandlingApplication.class", String.class); + .getForEntity("/BOOT-INF/classes/com/example/ResourceHandlingApplication.class", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java index e88d247e78..0631a10104 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,7 +77,7 @@ class EmbeddedServletContainerWarDevelopmentIntegrationTests { ResponseEntity entity = rest.getForEntity("/resourcePaths", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(readLines(entity.getBody())) - .noneMatch((resourcePath) -> resourcePath.startsWith("/org/springframework/boot/loader")); + .noneMatch((resourcePath) -> resourcePath.startsWith("/org/springframework/boot/loader")); } private List readLines(String input) { diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java index 5ec90ffd94..dc30d8b9e2 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -75,7 +75,7 @@ class EmbeddedServletContainerWarPackagingIntegrationTests { @TestTemplate void applicationClassesAreNotAvailableViaHttp(RestTemplate rest) { ResponseEntity entity = rest - .getForEntity("/WEB-INF/classes/com/example/ResourceHandlingApplication.class", String.class); + .getForEntity("/WEB-INF/classes/com/example/ResourceHandlingApplication.class", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @@ -99,14 +99,14 @@ class EmbeddedServletContainerWarPackagingIntegrationTests { ResponseEntity entity = rest.getForEntity("/resourcePaths", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(readLines(entity.getBody())) - .noneMatch((resourcePath) -> resourcePath.startsWith("/org/springframework/boot/loader")); + .noneMatch((resourcePath) -> resourcePath.startsWith("/org/springframework/boot/loader")); } @TestTemplate void conditionalOnWarDeploymentBeanIsNotAvailableForEmbeddedServer(RestTemplate rest) { assertThat(rest.getForEntity("/always", String.class).getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(rest.getForEntity("/conditionalOnWar", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); } private List readLines(String input) { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/main/java/smoketest/actuator/customsecurity/SecurityConfiguration.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/main/java/smoketest/actuator/customsecurity/SecurityConfiguration.java index 42a9396683..3d4e6a6747 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/main/java/smoketest/actuator/customsecurity/SecurityConfiguration.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/main/java/smoketest/actuator/customsecurity/SecurityConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,7 +59,7 @@ public class SecurityConfiguration { requests.mvcMatchers("/actuator/beans").hasRole("BEANS"); requests.requestMatchers(EndpointRequest.to("health")).permitAll(); requests.requestMatchers(EndpointRequest.toAnyEndpoint().excluding(MappingsEndpoint.class)) - .hasRole("ACTUATOR"); + .hasRole("ACTUATOR"); requests.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll(); requests.antMatchers("/foo").permitAll(); requests.antMatchers("/**").hasRole("USER"); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/AbstractSampleActuatorCustomSecurityTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/AbstractSampleActuatorCustomSecurityTests.java index 17913301f4..f393b16c58 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/AbstractSampleActuatorCustomSecurityTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/AbstractSampleActuatorCustomSecurityTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -152,21 +152,21 @@ abstract class AbstractSampleActuatorCustomSecurityTests { @Test void actuatorCustomMvcSecureEndpointWithAnonymous() { ResponseEntity entity = restTemplate() - .getForEntity(getManagementPath() + "/actuator/example/echo?text={t}", String.class, "test"); + .getForEntity(getManagementPath() + "/actuator/example/echo?text={t}", String.class, "test"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void actuatorCustomMvcSecureEndpointWithUnauthorizedUser() { ResponseEntity entity = userRestTemplate() - .getForEntity(getManagementPath() + "/actuator/example/echo?text={t}", String.class, "test"); + .getForEntity(getManagementPath() + "/actuator/example/echo?text={t}", String.class, "test"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test void actuatorCustomMvcSecureEndpointWithAuthorizedUser() { ResponseEntity entity = adminRestTemplate() - .getForEntity(getManagementPath() + "/actuator/example/echo?text={t}", String.class, "test"); + .getForEntity(getManagementPath() + "/actuator/example/echo?text={t}", String.class, "test"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("test"); assertThat(entity.getHeaders().getFirst("echo")).isEqualTo("test"); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/CorsSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/CorsSampleActuatorApplicationTests.java index 13d44c7d68..d560ab4a1d 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/CorsSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/CorsSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,7 +67,9 @@ class CorsSampleActuatorApplicationTests { @Test void preflightRequestToEndpointShouldReturnOk() throws Exception { RequestEntity envRequest = RequestEntity.options(new URI("/actuator/env")) - .header("Origin", "http://localhost:8080").header("Access-Control-Request-Method", "GET").build(); + .header("Origin", "http://localhost:8080") + .header("Access-Control-Request-Method", "GET") + .build(); ResponseEntity exchange = this.testRestTemplate.exchange(envRequest, Map.class); assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -75,7 +77,9 @@ class CorsSampleActuatorApplicationTests { @Test void preflightRequestWhenCorsConfigInvalidShouldReturnForbidden() throws Exception { RequestEntity entity = RequestEntity.options(new URI("/actuator/env")) - .header("Origin", "http://localhost:9095").header("Access-Control-Request-Method", "GET").build(); + .header("Origin", "http://localhost:9095") + .header("Access-Control-Request-Method", "GET") + .build(); ResponseEntity exchange = this.testRestTemplate.exchange(entity, byte[].class); assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementPortAndPathSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementPortAndPathSampleActuatorApplicationTests.java index 9c24a32708..29384b280c 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementPortAndPathSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementPortAndPathSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ class ManagementPortAndPathSampleActuatorApplicationTests extends AbstractSample @Test void testMissing() { ResponseEntity entity = new TestRestTemplate("admin", "admin") - .getForEntity("http://localhost:" + this.managementPort + "/management/actuator/missing", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/management/actuator/missing", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); assertThat(entity.getBody()).contains("\"status\":404"); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementPortCustomServletPathSampleActuatorTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementPortCustomServletPathSampleActuatorTests.java index ce2fb6f68b..f0253cacc7 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementPortCustomServletPathSampleActuatorTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementPortCustomServletPathSampleActuatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,7 @@ class ManagementPortCustomServletPathSampleActuatorTests extends AbstractSampleA @Test void actuatorPathOnMainPortShouldNotMatch() { ResponseEntity entity = new TestRestTemplate() - .getForEntity("http://localhost:" + this.port + "/example/actuator/health", String.class); + .getForEntity("http://localhost:" + this.port + "/example/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-log4j2/src/test/java/smoketest/actuator/log4j2/SampleActuatorLog4J2ApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-log4j2/src/test/java/smoketest/actuator/log4j2/SampleActuatorLog4J2ApplicationTests.java index 03c9be6679..a022ca9389 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-log4j2/src/test/java/smoketest/actuator/log4j2/SampleActuatorLog4J2ApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-log4j2/src/test/java/smoketest/actuator/log4j2/SampleActuatorLog4J2ApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,9 +59,11 @@ class SampleActuatorLog4J2ApplicationTests { @Test void validateLoggersEndpoint() throws Exception { - this.mvc.perform(get("/actuator/loggers/org.apache.coyote.http11.Http11NioProtocol").header("Authorization", - getBasicAuth())).andExpect(status().isOk()) - .andExpect(content().string("{\"configuredLevel\":\"WARN\",\"effectiveLevel\":\"WARN\"}")); + this.mvc + .perform(get("/actuator/loggers/org.apache.coyote.http11.Http11NioProtocol").header("Authorization", + getBasicAuth())) + .andExpect(status().isOk()) + .andExpect(content().string("{\"configuredLevel\":\"WARN\",\"effectiveLevel\":\"WARN\"}")); } private String getBasicAuth() { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationPortTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationPortTests.java index 878c403c4c..d2bd9e6593 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationPortTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationPortTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,14 +55,14 @@ class SampleActuatorUiApplicationPortTests { void testMetrics() { @SuppressWarnings("rawtypes") ResponseEntity entity = new TestRestTemplate() - .getForEntity("http://localhost:" + this.managementPort + "/actuator/metrics", Map.class); + .getForEntity("http://localhost:" + this.managementPort + "/actuator/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void testHealth() { ResponseEntity entity = new TestRestTemplate().withBasicAuth("user", getPassword()) - .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationTests.java index 6ca9b19981..a5199c4b0f 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,8 @@ class SampleActuatorUiApplicationTests { void testHome() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity entity = this.restTemplate.withBasicAuth("user", getPassword()).exchange("/", - HttpMethod.GET, new HttpEntity(headers), String.class); + ResponseEntity entity = this.restTemplate.withBasicAuth("user", getPassword()) + .exchange("/", HttpMethod.GET, new HttpEntity(headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("Hello"); } @@ -73,11 +73,12 @@ class SampleActuatorUiApplicationTests { void testError() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).exchange("/error", - HttpMethod.GET, new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()) + .exchange("/error", HttpMethod.GET, new HttpEntity<Void>(headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - assertThat(entity.getBody()).contains("<html>").contains("<body>") - .contains("Please contact the operator with the above information"); + assertThat(entity.getBody()).contains("<html>") + .contains("<body>") + .contains("Please contact the operator with the above information"); } private String getPassword() { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/AbstractManagementPortAndPathSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/AbstractManagementPortAndPathSampleActuatorApplicationTests.java index 79bd73ce27..08866dd551 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/AbstractManagementPortAndPathSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/AbstractManagementPortAndPathSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,14 +58,14 @@ abstract class AbstractManagementPortAndPathSampleActuatorApplicationTests { void testMetrics() { testHome(); // makes sure some requests have been made ResponseEntity<Map<String, Object>> entity = asMapEntity(new TestRestTemplate() - .getForEntity("http://localhost:" + this.managementPort + "/admin/metrics", Map.class)); + .getForEntity("http://localhost:" + this.managementPort + "/admin/metrics", Map.class)); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void testHealth() { ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/admin/health", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/admin/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("{\"status\":\"UP\",\"groups\":[\"comp\",\"live\",\"ready\"]}"); } @@ -73,7 +73,7 @@ abstract class AbstractManagementPortAndPathSampleActuatorApplicationTests { @Test void testGroupWithComposite() { ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/admin/health/comp", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/admin/health/comp", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains( "components\":{\"a\":{\"status\":\"UP\",\"details\":{\"hello\":\"spring-a\"}},\"c\":{\"status\":\"UP\",\"details\":{\"hello\":\"spring-c\"}}"); @@ -83,15 +83,15 @@ abstract class AbstractManagementPortAndPathSampleActuatorApplicationTests { void testEnvNotFound() { String unknownProperty = "test-does-not-exist"; assertThat(this.environment.containsProperty(unknownProperty)).isFalse(); - ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password").getForEntity( - "http://localhost:" + this.managementPort + "/admin/env/" + unknownProperty, String.class); + ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") + .getForEntity("http://localhost:" + this.managementPort + "/admin/env/" + unknownProperty, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test void testMissing() { ResponseEntity<String> entity = new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/admin/missing", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/admin/missing", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); assertThat(entity.getBody()).contains("\"status\":404"); } @@ -99,7 +99,7 @@ abstract class AbstractManagementPortAndPathSampleActuatorApplicationTests { @Test void testErrorPage() { ResponseEntity<Map<String, Object>> entity = asMapEntity(new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.port + "/error", Map.class)); + .getForEntity("http://localhost:" + this.port + "/error", Map.class)); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); assertThat(entity.getBody().get("status")).isEqualTo(999); } @@ -107,7 +107,7 @@ abstract class AbstractManagementPortAndPathSampleActuatorApplicationTests { @Test void testManagementErrorPage() { ResponseEntity<Map<String, Object>> entity = asMapEntity(new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/error", Map.class)); + .getForEntity("http://localhost:" + this.managementPort + "/error", Map.class)); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody().get("status")).isEqualTo(999); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/CorsSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/CorsSampleActuatorApplicationTests.java index 68bc6f9c79..32eab95153 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/CorsSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/CorsSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,7 +67,9 @@ class CorsSampleActuatorApplicationTests { @Test void preflightRequestToEndpointShouldReturnOk() throws Exception { RequestEntity<?> healthRequest = RequestEntity.options(new URI("/actuator/env")) - .header("Origin", "http://localhost:8080").header("Access-Control-Request-Method", "GET").build(); + .header("Origin", "http://localhost:8080") + .header("Access-Control-Request-Method", "GET") + .build(); ResponseEntity<?> exchange = this.testRestTemplate.exchange(healthRequest, Map.class); assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -75,7 +77,9 @@ class CorsSampleActuatorApplicationTests { @Test void preflightRequestWhenCorsConfigInvalidShouldReturnForbidden() throws Exception { RequestEntity<?> entity = RequestEntity.options(new URI("/actuator/env")) - .header("Origin", "http://localhost:9095").header("Access-Control-Request-Method", "GET").build(); + .header("Origin", "http://localhost:9095") + .header("Access-Control-Request-Method", "GET") + .build(); ResponseEntity<byte[]> exchange = this.testRestTemplate.exchange(entity, byte[].class); assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java index da6256e470..7d00e31748 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,7 +55,7 @@ class EndpointsPropertiesSampleActuatorApplicationTests { @Test void testCustomContextPath() { ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password") - .getForEntity("/admin/health", String.class); + .getForEntity("/admin/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); assertThat(entity.getBody()).contains("\"hello\":\"world\""); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementAddressActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementAddressActuatorApplicationTests.java index 6e9a137baa..7f2fcd2043 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementAddressActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementAddressActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,7 +55,7 @@ class ManagementAddressActuatorApplicationTests { @Test void testHealth() { ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/admin/actuator/health", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/admin/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortAndEndpointWithExceptionHandlerSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortAndEndpointWithExceptionHandlerSampleActuatorApplicationTests.java index 89e0392177..3b2f52f533 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortAndEndpointWithExceptionHandlerSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortAndEndpointWithExceptionHandlerSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,7 @@ class ManagementDifferentPortAndEndpointWithExceptionHandlerSampleActuatorApplic @Test void testExceptionHandlerRestControllerEndpoint() { ResponseEntity<String> entity = new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/actuator/exception", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/actuator/exception", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.I_AM_A_TEAPOT); assertThat(entity.getBody()).isEqualTo("this is a custom exception body"); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortSampleActuatorApplicationTests.java index 9e3b73ac51..1d70bf5ca2 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class ManagementDifferentPortSampleActuatorApplicationTests { @Test void linksEndpointShouldBeAvailable() { ResponseEntity<String> entity = new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"_links\""); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPathSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPathSampleActuatorApplicationTests.java index 53767d4b13..ae97c9a256 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPathSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPathSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ class ManagementPathSampleActuatorApplicationTests { @Test void testHealth() { ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password") - .getForEntity("/admin/health", String.class); + .getForEntity("/admin/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortSampleActuatorApplicationTests.java index 20a86d394a..bb7ad145e3 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,14 +69,14 @@ class ManagementPortSampleActuatorApplicationTests { void testMetrics() { testHome(); // makes sure some requests have been made ResponseEntity<Map<String, Object>> entity = asMapEntity(new TestRestTemplate() - .getForEntity("http://localhost:" + this.managementPort + "/actuator/metrics", Map.class)); + .getForEntity("http://localhost:" + this.managementPort + "/actuator/metrics", Map.class)); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void testHealth() { ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); assertThat(entity.getBody()).contains("\"example\""); @@ -86,7 +86,7 @@ class ManagementPortSampleActuatorApplicationTests { @Test void testErrorPage() { ResponseEntity<Map<String, Object>> entity = asMapEntity(new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/error", Map.class)); + .getForEntity("http://localhost:" + this.managementPort + "/error", Map.class)); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody().get("status")).isEqualTo(999); } @@ -95,7 +95,7 @@ class ManagementPortSampleActuatorApplicationTests { void securityContextIsAvailableToErrorHandling() { this.errorAttributes.securityContext = null; ResponseEntity<Map<String, Object>> entity = asMapEntity(new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/404", Map.class)); + .getForEntity("http://localhost:" + this.managementPort + "/404", Map.class)); assertThat(this.errorAttributes.securityContext.getAuthentication()).isNotNull(); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); assertThat(entity.getBody().get("status")).isEqualTo(404); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortWithLazyInitializationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortWithLazyInitializationTests.java index 301befa381..6ab315da4e 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortWithLazyInitializationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortWithLazyInitializationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class ManagementPortWithLazyInitializationTests { @Test void testHealth() { ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationTests.java index 9c4afa08ec..3402731a30 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -111,8 +111,8 @@ class SampleActuatorApplicationTests { @Test void testErrorPage() { - ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password").getForEntity("/foo", - String.class); + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password") + .getForEntity("/foo", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); String body = entity.getBody(); assertThat(body).contains("\"error\":"); @@ -123,8 +123,8 @@ class SampleActuatorApplicationTests { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); HttpEntity<?> request = new HttpEntity<Void>(headers); - ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password").exchange("/foo", - HttpMethod.GET, request, String.class); + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password") + .exchange("/foo", HttpMethod.GET, request, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); String body = entity.getBody(); assertThat(body).as("Body was null").isNotNull(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ServletPathSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ServletPathSampleActuatorApplicationTests.java index 77b96e9974..5e3294e952 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ServletPathSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ServletPathSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ class ServletPathSampleActuatorApplicationTests { @Test void testHealth() { ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password") - .getForEntity("/spring/actuator/health", String.class); + .getForEntity("/spring/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ShutdownSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ShutdownSampleActuatorApplicationTests.java index 7e4a50a146..e544baa5f6 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ShutdownSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ShutdownSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,7 +59,7 @@ class ShutdownSampleActuatorApplicationTests { @DirtiesContext void testShutdown() { ResponseEntity<Map<String, Object>> entity = asMapEntity(this.restTemplate.withBasicAuth("user", "password") - .postForEntity("/actuator/shutdown", null, Map.class)); + .postForEntity("/actuator/shutdown", null, Map.class)); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(((String) entity.getBody().get("message"))).contains("Shutting down"); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-ant/src/test/java/smoketest/ant/SampleAntApplicationIT.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-ant/src/test/java/smoketest/ant/SampleAntApplicationIT.java index e13efd01e2..2946e50ec2 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-ant/src/test/java/smoketest/ant/SampleAntApplicationIT.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-ant/src/test/java/smoketest/ant/SampleAntApplicationIT.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,9 @@ public class SampleAntApplicationIT { @Test void runJar() throws Exception { File libs = new File("build/ant/libs"); - Process process = new JavaExecutable().processBuilder("-jar", "spring-boot-smoke-test-ant.jar").directory(libs) - .start(); + Process process = new JavaExecutable().processBuilder("-jar", "spring-boot-smoke-test-ant.jar") + .directory(libs) + .start(); process.waitFor(5, TimeUnit.MINUTES); assertThat(process.exitValue()).isEqualTo(0); String output = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream())); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-atmosphere/src/test/java/smoketest/atmosphere/SampleAtmosphereApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-atmosphere/src/test/java/smoketest/atmosphere/SampleAtmosphereApplicationTests.java index 965d7e2ba8..36a25d3e12 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-atmosphere/src/test/java/smoketest/atmosphere/SampleAtmosphereApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-atmosphere/src/test/java/smoketest/atmosphere/SampleAtmosphereApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,8 @@ class SampleAtmosphereApplicationTests { void chatEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/chat/websocket") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/chat/websocket") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/main/java/smoketest/bootstrapregistry/external/svn/SubversionConfigDataLoader.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/main/java/smoketest/bootstrapregistry/external/svn/SubversionConfigDataLoader.java index 19009571b4..6b84c1a4d5 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/main/java/smoketest/bootstrapregistry/external/svn/SubversionConfigDataLoader.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/main/java/smoketest/bootstrapregistry/external/svn/SubversionConfigDataLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,8 +52,8 @@ class SubversionConfigDataLoader implements ConfigDataLoader<SubversionConfigDat @Override public ConfigData load(ConfigDataLoaderContext context, SubversionConfigDataResource resource) throws IOException, ConfigDataLocationNotFoundException { - context.getBootstrapContext().registerIfAbsent(SubversionServerCertificate.class, - InstanceSupplier.of(resource.getServerCertificate())); + context.getBootstrapContext() + .registerIfAbsent(SubversionServerCertificate.class, InstanceSupplier.of(resource.getServerCertificate())); SubversionClient client = context.getBootstrapContext().get(SubversionClient.class); String loaded = client.load(resource.getLocation()); PropertySource<?> propertySource = new MapPropertySource("svn", Collections.singletonMap("svn", loaded)); @@ -61,8 +61,9 @@ class SubversionConfigDataLoader implements ConfigDataLoader<SubversionConfigDat } private static void onBootstrapContextClosed(BootstrapContextClosedEvent event) { - event.getApplicationContext().getBeanFactory().registerSingleton("subversionClient", - event.getBootstrapContext().get(SubversionClient.class)); + event.getApplicationContext() + .getBeanFactory() + .registerSingleton("subversionClient", event.getBootstrapContext().get(SubversionClient.class)); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/main/java/smoketest/bootstrapregistry/external/svn/SubversionConfigDataLocationResolver.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/main/java/smoketest/bootstrapregistry/external/svn/SubversionConfigDataLocationResolver.java index beac974635..a04b7330ae 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/main/java/smoketest/bootstrapregistry/external/svn/SubversionConfigDataLocationResolver.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/main/java/smoketest/bootstrapregistry/external/svn/SubversionConfigDataLocationResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,8 +44,8 @@ class SubversionConfigDataLocationResolver implements ConfigDataLocationResolver ConfigDataLocation location) throws ConfigDataLocationNotFoundException, ConfigDataResourceNotFoundException { String serverCertificate = context.getBinder().bind("spring.svn.server.certificate", String.class).orElse(null); - return Collections.singletonList( - new SubversionConfigDataResource(location.getNonPrefixedValue(PREFIX), serverCertificate)); + return Collections + .singletonList(new SubversionConfigDataResource(location.getNonPrefixedValue(PREFIX), serverCertificate)); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/test/java/smoketest/bootstrapregistry/app/SampleBootstrapRegistryApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/test/java/smoketest/bootstrapregistry/app/SampleBootstrapRegistryApplicationTests.java index edb750f5e5..c0549aa755 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/test/java/smoketest/bootstrapregistry/app/SampleBootstrapRegistryApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/test/java/smoketest/bootstrapregistry/app/SampleBootstrapRegistryApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ class SampleBootstrapRegistryApplicationTests { void testBootstrapper(CapturedOutput output) { SampleBootstrapRegistryApplication.main(new String[0]); assertThat(output).contains("svn my-data from svn / example.com[secret]") - .contains("client smoketest.bootstrapregistry.app.MySubversionClient"); + .contains("client smoketest.bootstrapregistry.app.MySubversionClient"); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jdbc/src/test/java/smoketest/data/jdbc/SampleDataJdbcApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jdbc/src/test/java/smoketest/data/jdbc/SampleDataJdbcApplicationTests.java index 52ee22cd1d..fd17c9947c 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jdbc/src/test/java/smoketest/data/jdbc/SampleDataJdbcApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jdbc/src/test/java/smoketest/data/jdbc/SampleDataJdbcApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,9 @@ class SampleDataJdbcApplicationTests { @Test void testCustomers() throws Exception { - this.mvc.perform(get("/").param("name", "merEDith")).andExpect(status().isOk()) - .andExpect(content().string(containsString("Meredith"))); + this.mvc.perform(get("/").param("name", "merEDith")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("Meredith"))); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jpa/src/test/java/smoketest/data/jpa/SampleDataJpaApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jpa/src/test/java/smoketest/data/jpa/SampleDataJpaApplicationTests.java index db319a3abf..0917738ec8 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jpa/src/test/java/smoketest/data/jpa/SampleDataJpaApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jpa/src/test/java/smoketest/data/jpa/SampleDataJpaApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,7 +66,7 @@ class SampleDataJpaApplicationTests { @Test void testJmx() throws Exception { assertThat(ManagementFactory.getPlatformMBeanServer() - .queryMBeans(new ObjectName("jpa.sample:type=HikariDataSource,*"), null)).hasSize(1); + .queryMBeans(new ObjectName("jpa.sample:type=HikariDataSource,*"), null)).hasSize(1); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc-flyway/src/test/java/smoketest/data/r2dbc/CityRepositoryTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc-flyway/src/test/java/smoketest/data/r2dbc/CityRepositoryTests.java index 971768491b..9c082c3f3b 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc-flyway/src/test/java/smoketest/data/r2dbc/CityRepositoryTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc-flyway/src/test/java/smoketest/data/r2dbc/CityRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ class CityRepositoryTests { @Container static PostgreSQLContainer<?> postgresql = new PostgreSQLContainer<>(DockerImageNames.postgresql()) - .withDatabaseName("test_flyway"); + .withDatabaseName("test_flyway"); @DynamicPropertySource static void postgresqlProperties(DynamicPropertyRegistry registry) { @@ -59,7 +59,8 @@ class CityRepositoryTests { @Test void databaseHasBeenInitialized() { StepVerifier.create(this.repository.findByState("DC").filter((city) -> city.getName().equals("Washington"))) - .consumeNextWith((city) -> assertThat(city.getId()).isNotNull()).verifyComplete(); + .consumeNextWith((city) -> assertThat(city.getId()).isNotNull()) + .verifyComplete(); } private static String r2dbcUrl() { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc-liquibase/src/test/java/smoketest/data/r2dbc/CityRepositoryTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc-liquibase/src/test/java/smoketest/data/r2dbc/CityRepositoryTests.java index af1ec7a5c2..c0de6abc3f 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc-liquibase/src/test/java/smoketest/data/r2dbc/CityRepositoryTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc-liquibase/src/test/java/smoketest/data/r2dbc/CityRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ class CityRepositoryTests { @Container static PostgreSQLContainer<?> postgresql = new PostgreSQLContainer<>(DockerImageNames.postgresql()) - .withDatabaseName("test_liquibase"); + .withDatabaseName("test_liquibase"); @DynamicPropertySource static void postgresqlProperties(DynamicPropertyRegistry registry) { @@ -59,7 +59,8 @@ class CityRepositoryTests { @Test void databaseHasBeenInitialized() { StepVerifier.create(this.repository.findByState("DC").filter((city) -> city.getName().equals("Washington"))) - .consumeNextWith((city) -> assertThat(city.getId()).isNotNull()).verifyComplete(); + .consumeNextWith((city) -> assertThat(city.getId()).isNotNull()) + .verifyComplete(); } private static String r2dbcUrl() { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc/src/test/java/smoketest/data/r2dbc/SampleR2dbcApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc/src/test/java/smoketest/data/r2dbc/SampleR2dbcApplicationTests.java index cc414e16c0..9c14f60221 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc/src/test/java/smoketest/data/r2dbc/SampleR2dbcApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc/src/test/java/smoketest/data/r2dbc/SampleR2dbcApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,8 +40,12 @@ class SampleR2dbcApplicationTests { @Test void citiesEndpointReturnInitialState() { - this.webClient.get().uri("/cities").exchange().expectBody().jsonPath("$[*].id") - .isEqualTo(new JSONArray().appendElement(2000).appendElement(2001)); + this.webClient.get() + .uri("/cities") + .exchange() + .expectBody() + .jsonPath("$[*].id") + .isEqualTo(new JSONArray().appendElement(2000).appendElement(2001)); } @Test @@ -51,9 +55,16 @@ class SampleR2dbcApplicationTests { @Test void healthEndpointHasR2dbcEntry() { - this.webClient.get().uri("/actuator/health").exchange().expectStatus().isOk().expectBody() - .jsonPath("components.r2dbc.status").isEqualTo("UP").jsonPath("components.r2dbc.details.database") - .isEqualTo("H2"); + this.webClient.get() + .uri("/actuator/health") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("components.r2dbc.status") + .isEqualTo("UP") + .jsonPath("components.r2dbc.details.database") + .isEqualTo("H2"); } @Test diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-rest/src/test/java/smoketest/data/rest/SampleDataRestApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-rest/src/test/java/smoketest/data/rest/SampleDataRestApplicationTests.java index 57f0456269..c6d5006e2f 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-rest/src/test/java/smoketest/data/rest/SampleDataRestApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-rest/src/test/java/smoketest/data/rest/SampleDataRestApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,15 +61,17 @@ class SampleDataRestApplicationTests { @Test void findByNameAndCountry() throws Exception { this.mvc.perform(get("/api/cities/search/findByNameAndCountryAllIgnoringCase?name=Melbourne&country=Australia")) - .andExpect(status().isOk()).andExpect(jsonPath("state", equalTo("Victoria"))) - .andExpect(jsonPath("name", equalTo("Melbourne"))); + .andExpect(status().isOk()) + .andExpect(jsonPath("state", equalTo("Victoria"))) + .andExpect(jsonPath("name", equalTo("Melbourne"))); } @Test void findByContaining() throws Exception { - this.mvc.perform( - get("/api/cities/search/findByNameContainingAndCountryContainingAllIgnoringCase?name=&country=UK")) - .andExpect(status().isOk()).andExpect(jsonPath("_embedded.cities", hasSize(3))); + this.mvc + .perform(get("/api/cities/search/findByNameContainingAndCountryContainingAllIgnoringCase?name=&country=UK")) + .andExpect(status().isOk()) + .andExpect(jsonPath("_embedded.cities", hasSize(3))); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/main/java/smoketest/graphql/SecurityConfig.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/main/java/smoketest/graphql/SecurityConfig.java index ec1a87f030..981b5e05d3 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/main/java/smoketest/graphql/SecurityConfig.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/main/java/smoketest/graphql/SecurityConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,9 +36,11 @@ public class SecurityConfig { @Bean public DefaultSecurityFilterChain springWebFilterChain(HttpSecurity http) throws Exception { return http.csrf((csrf) -> csrf.disable()) - // Demonstrate that method security works - // Best practice to use both for defense in depth - .authorizeRequests((requests) -> requests.anyRequest().permitAll()).httpBasic(withDefaults()).build(); + // Demonstrate that method security works + // Best practice to use both for defense in depth + .authorizeRequests((requests) -> requests.anyRequest().permitAll()) + .httpBasic(withDefaults()) + .build(); } @Bean diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/test/java/smoketest/graphql/GreetingControllerTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/test/java/smoketest/graphql/GreetingControllerTests.java index 27ddea4659..086ab12f83 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/test/java/smoketest/graphql/GreetingControllerTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/test/java/smoketest/graphql/GreetingControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,22 +44,29 @@ class GreetingControllerTests { @Test void shouldGreetWithSpecificName() { HttpGraphQlTester authenticated = withAdminCredentials(this.graphQlTester); - authenticated.documentName("greeting").variable("name", "Brian").execute().path("greeting").entity(String.class) - .isEqualTo("Hello, Brian!"); + authenticated.documentName("greeting") + .variable("name", "Brian") + .execute() + .path("greeting") + .entity(String.class) + .isEqualTo("Hello, Brian!"); } @Test void shouldGreetWithDefaultName() { HttpGraphQlTester authenticated = withAdminCredentials(this.graphQlTester); - authenticated.document("{ greeting }").execute().path("greeting").entity(String.class) - .isEqualTo("Hello, Spring!"); + authenticated.document("{ greeting }") + .execute() + .path("greeting") + .entity(String.class) + .isEqualTo("Hello, Spring!"); } private HttpGraphQlTester withAdminCredentials(HttpGraphQlTester graphQlTester) { return graphQlTester.mutate() - .webTestClient( - (httpClient) -> httpClient.defaultHeaders((headers) -> headers.setBasicAuth("admin", "admin"))) - .build(); + .webTestClient( + (httpClient) -> httpClient.defaultHeaders((headers) -> headers.setBasicAuth("admin", "admin"))) + .build(); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/test/java/smoketest/graphql/ProjectControllerTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/test/java/smoketest/graphql/ProjectControllerTests.java index a9a76eee10..0ad99df70d 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/test/java/smoketest/graphql/ProjectControllerTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/test/java/smoketest/graphql/ProjectControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,14 +30,19 @@ class ProjectControllerTests { @Test void shouldFindSpringGraphQl() { - this.graphQlTester.document("{ project(slug: \"spring-graphql\") { name } }").execute().path("project.name") - .entity(String.class).isEqualTo("Spring GraphQL"); + this.graphQlTester.document("{ project(slug: \"spring-graphql\") { name } }") + .execute() + .path("project.name") + .entity(String.class) + .isEqualTo("Spring GraphQL"); } @Test void shouldNotFindUnknownProject() { - this.graphQlTester.document("{ project(slug: \"spring-unknown\") { name } }").execute().path("project.name") - .pathDoesNotExist(); + this.graphQlTester.document("{ project(slug: \"spring-unknown\") { name } }") + .execute() + .path("project.name") + .pathDoesNotExist(); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-hazelcast3/src/test/java/smoketest/hazelcast3/SampleHazelcast3ApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-hazelcast3/src/test/java/smoketest/hazelcast3/SampleHazelcast3ApplicationTests.java index b55194cb4d..b8a322ecf3 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-hazelcast3/src/test/java/smoketest/hazelcast3/SampleHazelcast3ApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-hazelcast3/src/test/java/smoketest/hazelcast3/SampleHazelcast3ApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,9 +45,18 @@ class SampleHazelcast3ApplicationTests { @Test void healthEndpointHasHazelcastContributor() { - this.webClient.get().uri("/actuator/health/hazelcast").exchange().expectStatus().isOk().expectBody() - .jsonPath("status").isEqualTo("UP").jsonPath("details.name").isNotEmpty().jsonPath("details.uuid") - .isNotEmpty(); + this.webClient.get() + .uri("/actuator/health/hazelcast") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("status") + .isEqualTo("UP") + .jsonPath("details.name") + .isNotEmpty() + .jsonPath("details.uuid") + .isNotEmpty(); } @Test diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-hazelcast4/src/test/java/smoketest/hazelcast4/SampleHazelcast4ApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-hazelcast4/src/test/java/smoketest/hazelcast4/SampleHazelcast4ApplicationTests.java index f16bda4375..7e1efa71f4 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-hazelcast4/src/test/java/smoketest/hazelcast4/SampleHazelcast4ApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-hazelcast4/src/test/java/smoketest/hazelcast4/SampleHazelcast4ApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,9 +45,18 @@ class SampleHazelcast4ApplicationTests { @Test void healthEndpointHasHazelcastContributor() { - this.webClient.get().uri("/actuator/health/hazelcast").exchange().expectStatus().isOk().expectBody() - .jsonPath("status").isEqualTo("UP").jsonPath("details.name").isNotEmpty().jsonPath("details.uuid") - .isNotEmpty(); + this.webClient.get() + .uri("/actuator/health/hazelcast") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("status") + .isEqualTo("UP") + .jsonPath("details.name") + .isNotEmpty() + .jsonPath("details.uuid") + .isNotEmpty(); } @Test diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-integration/src/main/java/smoketest/integration/SampleIntegrationApplication.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-integration/src/main/java/smoketest/integration/SampleIntegrationApplication.java index 576a2bd9be..ceea7a37ea 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-integration/src/main/java/smoketest/integration/SampleIntegrationApplication.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-integration/src/main/java/smoketest/integration/SampleIntegrationApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,8 +64,12 @@ public class SampleIntegrationApplication { @Bean public IntegrationFlow integrationFlow(SampleEndpoint endpoint) { - return IntegrationFlows.from(fileReader(), new FixedRatePoller()).channel(inputChannel()).handle(endpoint) - .channel(outputChannel()).handle(fileWriter()).get(); + return IntegrationFlows.from(fileReader(), new FixedRatePoller()) + .channel(inputChannel()) + .handle(endpoint) + .channel(outputChannel()) + .handle(fileWriter()) + .get(); } public static void main(String[] args) { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-integration/src/test/java/smoketest/integration/consumer/SampleIntegrationApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-integration/src/test/java/smoketest/integration/consumer/SampleIntegrationApplicationTests.java index 0241aa0c5a..0424c7ee7d 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-integration/src/test/java/smoketest/integration/consumer/SampleIntegrationApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-integration/src/test/java/smoketest/integration/consumer/SampleIntegrationApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,8 +77,8 @@ class SampleIntegrationApplicationTests { } private void awaitOutputContaining(File outputDir, String requiredContents) { - Awaitility.waitAtMost(Duration.ofSeconds(30)).until(() -> outputIn(outputDir), - containsString(requiredContents)); + Awaitility.waitAtMost(Duration.ofSeconds(30)) + .until(() -> outputIn(outputDir), containsString(requiredContents)); } private String outputIn(File outputDir) throws IOException { @@ -91,7 +91,7 @@ class SampleIntegrationApplicationTests { private Resource[] findResources(File outputDir) throws IOException { return ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader()) - .getResources("file:" + outputDir.getAbsolutePath() + "/*.txt"); + .getResources("file:" + outputDir.getAbsolutePath() + "/*.txt"); } private String readResources(Resource[] resources) throws IOException { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/AbstractJerseyManagementPortTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/AbstractJerseyManagementPortTests.java index 03aad770f9..072a372558 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/AbstractJerseyManagementPortTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/AbstractJerseyManagementPortTests.java @@ -66,21 +66,21 @@ class AbstractJerseyManagementPortTests { @Test void resourceShouldNotBeAvailableOnManagementPort() { ResponseEntity<String> entity = this.testRestTemplate - .getForEntity("http://localhost:" + this.managementPort + "/test", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/test", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test void actuatorShouldBeAvailableOnManagementPort() { ResponseEntity<String> entity = this.testRestTemplate - .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test void actuatorShouldNotBeAvailableOnMainPort() { ResponseEntity<String> entity = this.testRestTemplate - .getForEntity("http://localhost:" + this.port + "/actuator/health", String.class); + .getForEntity("http://localhost:" + this.port + "/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyApplicationPathAndManagementPortTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyApplicationPathAndManagementPortTests.java index 5843f0a0fc..8336494fbd 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyApplicationPathAndManagementPortTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyApplicationPathAndManagementPortTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ class JerseyApplicationPathAndManagementPortTests { @Test void applicationPathShouldNotAffectActuators() { ResponseEntity<String> entity = this.testRestTemplate - .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyDifferentPortSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyDifferentPortSampleActuatorApplicationTests.java index e5e332e601..68a59efdff 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyDifferentPortSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyDifferentPortSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class JerseyDifferentPortSampleActuatorApplicationTests { @Test void linksEndpointShouldBeAvailable() { ResponseEntity<String> entity = new TestRestTemplate("user", getPassword()) - .getForEntity("http://localhost:" + this.managementPort + "/", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"_links\""); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jetty10/src/test/java/smoketest/jetty10/Jetty10Http2OverTlsTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jetty10/src/test/java/smoketest/jetty10/Jetty10Http2OverTlsTests.java index e23d86e8fe..1b3445fdfe 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jetty10/src/test/java/smoketest/jetty10/Jetty10Http2OverTlsTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jetty10/src/test/java/smoketest/jetty10/Jetty10Http2OverTlsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,8 +58,9 @@ class Jetty10Http2OverTlsTests { void httpOverTlsGetWhenHttp2AndSslAreEnabledSucceeds() throws Exception { SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustAllStrategy()).build(); TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create().setSslContext(sslContext).build(); - try (CloseableHttpAsyncClient http2Client = HttpAsyncClients.customHttp2().setTlsStrategy(tlsStrategy) - .build()) { + try (CloseableHttpAsyncClient http2Client = HttpAsyncClients.customHttp2() + .setTlsStrategy(tlsStrategy) + .build()) { http2Client.start(); SimpleHttpRequest request = SimpleRequestBuilder.get("https://localhost:" + this.port).build(); request.setBody("Hello World", ContentType.TEXT_PLAIN); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-liquibase/src/test/java/smoketest/liquibase/SampleLiquibaseApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-liquibase/src/test/java/smoketest/liquibase/SampleLiquibaseApplicationTests.java index 14e068e3b9..b1f0ae0d11 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-liquibase/src/test/java/smoketest/liquibase/SampleLiquibaseApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-liquibase/src/test/java/smoketest/liquibase/SampleLiquibaseApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,14 +57,14 @@ class SampleLiquibaseApplicationTests { } } assertThat(output).contains("Successfully acquired change log lock") - .contains("Creating database history table with name: PUBLIC.DATABASECHANGELOG") - .contains("Table person created") - .contains("ChangeSet classpath:/db/changelog/db.changelog-master.yaml::1::" - + "marceloverdijk ran successfully") - .contains("New row inserted into person") - .contains("ChangeSet classpath:/db/changelog/" - + "db.changelog-master.yaml::2::marceloverdijk ran successfully") - .contains("Successfully released change log lock"); + .contains("Creating database history table with name: PUBLIC.DATABASECHANGELOG") + .contains("Table person created") + .contains("ChangeSet classpath:/db/changelog/db.changelog-master.yaml::1::" + + "marceloverdijk ran successfully") + .contains("New row inserted into person") + .contains("ChangeSet classpath:/db/changelog/" + + "db.changelog-master.yaml::2::marceloverdijk ran successfully") + .contains("Successfully released change log lock"); } private boolean serverNotRunning(IllegalStateException ex) { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleOauth2ResourceServerApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleOauth2ResourceServerApplicationTests.java index 23fe1d000f..ae2908cf5f 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleOauth2ResourceServerApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleOauth2ResourceServerApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -100,7 +100,8 @@ class SampleOauth2ResourceServerApplicationTests { + "8CJ453lo4gcBm1efURN3LIVc1V9NQY_ESBKVdwqYyoJPEanURLVGRd6cQKn6YrCbbIRHjqAyqOE-z3KmgDJnPriljfR5XhSGyM9eq" + "D9Xpy6zu_MAeMJJfSArp857zLPk-Wf5VP9STAcjyfdBIybMKnwBYr2qHMT675hQ\"}]}"; return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .setResponseCode(200).setBody(body); + .setResponseCode(200) + .setBody(body); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-parent-context/src/main/java/smoketest/parent/SampleParentContextApplication.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-parent-context/src/main/java/smoketest/parent/SampleParentContextApplication.java index 34af61a72e..be15ab8546 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-parent-context/src/main/java/smoketest/parent/SampleParentContextApplication.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-parent-context/src/main/java/smoketest/parent/SampleParentContextApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,8 +74,12 @@ public class SampleParentContextApplication { @Bean public IntegrationFlow integrationFlow(SampleEndpoint endpoint) { - return IntegrationFlows.from(fileReader(), new FixedRatePoller()).channel(inputChannel()).handle(endpoint) - .channel(outputChannel()).handle(fileWriter()).get(); + return IntegrationFlows.from(fileReader(), new FixedRatePoller()) + .channel(inputChannel()) + .handle(endpoint) + .channel(outputChannel()) + .handle(fileWriter()) + .get(); } private static class FixedRatePoller implements Consumer<SourcePollingChannelAdapterSpec> { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-parent-context/src/test/java/smoketest/parent/consumer/SampleIntegrationParentApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-parent-context/src/test/java/smoketest/parent/consumer/SampleIntegrationParentApplicationTests.java index b918d093b1..c179e39047 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-parent-context/src/test/java/smoketest/parent/consumer/SampleIntegrationParentApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-parent-context/src/test/java/smoketest/parent/consumer/SampleIntegrationParentApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,8 +59,8 @@ class SampleIntegrationParentApplicationTests { } private void awaitOutputContaining(File outputDir, String requiredContents) { - Awaitility.waitAtMost(Duration.ofSeconds(30)).until(() -> outputIn(outputDir), - containsString(requiredContents)); + Awaitility.waitAtMost(Duration.ofSeconds(30)) + .until(() -> outputIn(outputDir), containsString(requiredContents)); } private String outputIn(File outputDir) throws IOException { @@ -73,7 +73,7 @@ class SampleIntegrationParentApplicationTests { private Resource[] findResources(File outputDir) throws IOException { return ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader()) - .getResources("file:" + outputDir.getAbsolutePath() + "/*.txt"); + .getResources("file:" + outputDir.getAbsolutePath() + "/*.txt"); } private String readResources(Resource[] resources) throws IOException { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-property-validation/src/test/java/smoketest/propertyvalidation/SamplePropertyValidationApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-property-validation/src/test/java/smoketest/propertyvalidation/SamplePropertyValidationApplicationTests.java index 4e6919b7e6..5fb9433c09 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-property-validation/src/test/java/smoketest/propertyvalidation/SamplePropertyValidationApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-property-validation/src/test/java/smoketest/propertyvalidation/SamplePropertyValidationApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,14 +57,14 @@ class SamplePropertyValidationApplicationTests { this.context.register(SamplePropertyValidationApplication.class); TestPropertyValues.of("sample.host:xxxxxx", "sample.port:9090").applyTo(this.context); assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> this.context.refresh()) - .withMessageContaining("Failed to bind properties under 'sample'"); + .withMessageContaining("Failed to bind properties under 'sample'"); } @Test void bindNullHost() { this.context.register(SamplePropertyValidationApplication.class); assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> this.context.refresh()) - .withMessageContaining("Failed to bind properties under 'sample'"); + .withMessageContaining("Failed to bind properties under 'sample'"); } @Test diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-quartz/src/main/java/smoketest/quartz/SampleQuartzApplication.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-quartz/src/main/java/smoketest/quartz/SampleQuartzApplication.java index 221cde31f8..3013acc99d 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-quartz/src/main/java/smoketest/quartz/SampleQuartzApplication.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-quartz/src/main/java/smoketest/quartz/SampleQuartzApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,49 +42,69 @@ public class SampleQuartzApplication { @Bean public JobDetail helloJobDetail() { - return JobBuilder.newJob(SampleJob.class).withIdentity("helloJob", "samples").usingJobData("name", "World") - .storeDurably().build(); + return JobBuilder.newJob(SampleJob.class) + .withIdentity("helloJob", "samples") + .usingJobData("name", "World") + .storeDurably() + .build(); } @Bean public JobDetail anotherJobDetail() { - return JobBuilder.newJob(SampleJob.class).withIdentity("anotherJob", "samples").usingJobData("name", "Everyone") - .storeDurably().build(); + return JobBuilder.newJob(SampleJob.class) + .withIdentity("anotherJob", "samples") + .usingJobData("name", "Everyone") + .storeDurably() + .build(); } @Bean public Trigger everyTwoSecTrigger() { - return TriggerBuilder.newTrigger().forJob("helloJob", "samples").withIdentity("sampleTrigger") - .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever()).build(); + return TriggerBuilder.newTrigger() + .forJob("helloJob", "samples") + .withIdentity("sampleTrigger") + .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever()) + .build(); } @Bean public Trigger everyDayTrigger() { - return TriggerBuilder.newTrigger().forJob("helloJob", "samples").withIdentity("every-day", "samples") - .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(24)).build(); + return TriggerBuilder.newTrigger() + .forJob("helloJob", "samples") + .withIdentity("every-day", "samples") + .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(24)) + .build(); } @Bean public Trigger threeAmWeekdaysTrigger() { - return TriggerBuilder.newTrigger().forJob("anotherJob", "samples").withIdentity("3am-weekdays", "samples") - .withSchedule(CronScheduleBuilder.atHourAndMinuteOnGivenDaysOfWeek(3, 0, 1, 2, 3, 4, 5)).build(); + return TriggerBuilder.newTrigger() + .forJob("anotherJob", "samples") + .withIdentity("3am-weekdays", "samples") + .withSchedule(CronScheduleBuilder.atHourAndMinuteOnGivenDaysOfWeek(3, 0, 1, 2, 3, 4, 5)) + .build(); } @Bean public Trigger onceAWeekTrigger() { - return TriggerBuilder.newTrigger().forJob("anotherJob", "samples").withIdentity("once-a-week", "samples") - .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(1)) - .build(); + return TriggerBuilder.newTrigger() + .forJob("anotherJob", "samples") + .withIdentity("once-a-week", "samples") + .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(1)) + .build(); } @Bean public Trigger everyHourWorkingHourTuesdayAndThursdayTrigger() { - return TriggerBuilder.newTrigger().forJob("helloJob", "samples").withIdentity("every-hour-tue-thu", "samples") - .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() - .onDaysOfTheWeek(Calendar.TUESDAY, Calendar.THURSDAY) - .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)) - .endingDailyAt(TimeOfDay.hourAndMinuteOfDay(18, 0)).withInterval(1, IntervalUnit.HOUR)) - .build(); + return TriggerBuilder.newTrigger() + .forJob("helloJob", "samples") + .withIdentity("every-hour-tue-thu", "samples") + .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() + .onDaysOfTheWeek(Calendar.TUESDAY, Calendar.THURSDAY) + .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)) + .endingDailyAt(TimeOfDay.hourAndMinuteOfDay(18, 0)) + .withInterval(1, IntervalUnit.HOUR)) + .build(); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-quartz/src/test/java/smoketest/quartz/SampleQuartzApplicationWebTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-quartz/src/test/java/smoketest/quartz/SampleQuartzApplicationWebTests.java index 8cd28f34b4..80dafc706e 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-quartz/src/test/java/smoketest/quartz/SampleQuartzApplicationWebTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-quartz/src/test/java/smoketest/quartz/SampleQuartzApplicationWebTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,7 +87,7 @@ class SampleQuartzApplicationWebTests { @Test void quartzTriggerDetailWhenNameDoesNotExistReturns404() { ResponseEntity<String> response = this.restTemplate - .getForEntity("/actuator/quartz/triggers/samples/does-not-exist", String.class); + .getForEntity("/actuator/quartz/triggers/samples/does-not-exist", String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-reactive-oauth2-client/src/test/java/smoketest/oauth2/client/SampleReactiveOAuth2ClientApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-reactive-oauth2-client/src/test/java/smoketest/oauth2/client/SampleReactiveOAuth2ClientApplicationTests.java index 2b170de1ba..20e777f81b 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-reactive-oauth2-client/src/test/java/smoketest/oauth2/client/SampleReactiveOAuth2ClientApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-reactive-oauth2-client/src/test/java/smoketest/oauth2/client/SampleReactiveOAuth2ClientApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,14 +34,24 @@ class SampleReactiveOAuth2ClientApplicationTests { @Test void everythingShouldRedirectToLogin() { - this.webTestClient.get().uri("/").exchange().expectStatus().isFound().expectHeader().valueEquals("Location", - "/login"); + this.webTestClient.get() + .uri("/") + .exchange() + .expectStatus() + .isFound() + .expectHeader() + .valueEquals("Location", "/login"); } @Test void loginShouldHaveBothOAuthClientsToChooseFrom() { - byte[] body = this.webTestClient.get().uri("/login").exchange().expectStatus().isOk().returnResult(String.class) - .getResponseBodyContent(); + byte[] body = this.webTestClient.get() + .uri("/login") + .exchange() + .expectStatus() + .isOk() + .returnResult(String.class) + .getResponseBodyContent(); String bodyString = new String(body); assertThat(bodyString).contains("/oauth2/authorization/yahoo"); assertThat(bodyString).contains("/oauth2/authorization/github-client-1"); @@ -50,8 +60,13 @@ class SampleReactiveOAuth2ClientApplicationTests { @Test void actuatorShouldBeSecuredByOAuth() { - this.webTestClient.get().uri("/actuator/health").exchange().expectStatus().isFound().expectHeader() - .valueEquals("Location", "/login"); + this.webTestClient.get() + .uri("/actuator/health") + .exchange() + .expectStatus() + .isFound() + .expectHeader() + .valueEquals("Location", "/login"); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-reactive-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleReactiveOAuth2ResourceServerApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-reactive-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleReactiveOAuth2ResourceServerApplicationTests.java index 57eaed7e91..33d36654c7 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-reactive-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleReactiveOAuth2ResourceServerApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-reactive-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleReactiveOAuth2ResourceServerApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,14 +58,25 @@ class SampleReactiveOAuth2ResourceServerApplicationTests { @Test void getWhenValidTokenShouldBeOk() { - this.webTestClient.get().uri("/").headers((headers) -> headers.setBearerAuth(VALID_TOKEN)).exchange() - .expectStatus().isOk().expectBody(String.class).isEqualTo("Hello, subject!"); + this.webTestClient.get() + .uri("/") + .headers((headers) -> headers.setBearerAuth(VALID_TOKEN)) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("Hello, subject!"); } @Test void getWhenNoTokenShouldBeUnauthorized() { - this.webTestClient.get().uri("/").exchange().expectStatus().isUnauthorized().expectHeader() - .valueEquals(HttpHeaders.WWW_AUTHENTICATE, "Bearer"); + this.webTestClient.get() + .uri("/") + .exchange() + .expectStatus() + .isUnauthorized() + .expectHeader() + .valueEquals(HttpHeaders.WWW_AUTHENTICATE, "Bearer"); } private static MockResponse mockResponse() { @@ -87,7 +98,8 @@ class SampleReactiveOAuth2ResourceServerApplicationTests { + "8CJ453lo4gcBm1efURN3LIVc1V9NQY_ESBKVdwqYyoJPEanURLVGRd6cQKn6YrCbbIRHjqAyqOE-z3KmgDJnPriljfR5XhSGyM9eq" + "D9Xpy6zu_MAeMJJfSArp857zLPk-Wf5VP9STAcjyfdBIybMKnwBYr2qHMT675hQ\"}]}"; return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .setResponseCode(200).setBody(body); + .setResponseCode(200) + .setBody(body); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-rsocket/src/test/java/smoketest/rsocket/SampleRSocketApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-rsocket/src/test/java/smoketest/rsocket/SampleRSocketApplicationTests.java index 97a5899cbd..61a85d4801 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-rsocket/src/test/java/smoketest/rsocket/SampleRSocketApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-rsocket/src/test/java/smoketest/rsocket/SampleRSocketApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,14 +49,14 @@ class SampleRSocketApplicationTests { @Test void rSocketEndpoint() { RSocketRequester requester = this.builder - .rsocketStrategies((builder) -> builder.encoder(new SimpleAuthenticationEncoder())) - .setupMetadata(new UsernamePasswordMetadata("user", "password"), - MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString())) - .tcp("localhost", this.port); + .rsocketStrategies((builder) -> builder.encoder(new SimpleAuthenticationEncoder())) + .setupMetadata(new UsernamePasswordMetadata("user", "password"), + MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString())) + .tcp("localhost", this.port); Mono<Project> result = requester.route("find.project.spring-boot").retrieveMono(Project.class); StepVerifier.create(result) - .assertNext((project) -> Assertions.assertThat(project.getName()).isEqualTo("spring-boot")) - .verifyComplete(); + .assertNext((project) -> Assertions.assertThat(project.getName()).isEqualTo("spring-boot")) + .verifyComplete(); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/main/java/smoketest/secure/jersey/SecurityConfiguration.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/main/java/smoketest/secure/jersey/SecurityConfiguration.java index 9cf97b4467..2315d574f6 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/main/java/smoketest/secure/jersey/SecurityConfiguration.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/main/java/smoketest/secure/jersey/SecurityConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,10 +32,16 @@ public class SecurityConfiguration { @Bean public InMemoryUserDetailsManager inMemoryUserDetailsManager() { return new InMemoryUserDetailsManager( - User.withDefaultPasswordEncoder().username("user").password("password").authorities("ROLE_USER") - .build(), - User.withDefaultPasswordEncoder().username("admin").password("admin") - .authorities("ROLE_ACTUATOR", "ROLE_USER").build()); + User.withDefaultPasswordEncoder() + .username("user") + .password("password") + .authorities("ROLE_USER") + .build(), + User.withDefaultPasswordEncoder() + .username("admin") + .password("admin") + .authorities("ROLE_ACTUATOR", "ROLE_USER") + .build()); } @Bean diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortAndPathJerseyApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortAndPathJerseyApplicationTests.java index 633f48ac03..c412a5c561 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortAndPathJerseyApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortAndPathJerseyApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ class ManagementPortAndPathJerseyApplicationTests extends AbstractJerseySecureTe @Test void testMissing() { ResponseEntity<String> entity = new TestRestTemplate("admin", "admin") - .getForEntity("http://localhost:" + this.managementPort + "/management/actuator/missing", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/management/actuator/missing", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortCustomApplicationPathJerseyTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortCustomApplicationPathJerseyTests.java index 355f12b98d..5c4676f884 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortCustomApplicationPathJerseyTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortCustomApplicationPathJerseyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ class ManagementPortCustomApplicationPathJerseyTests extends AbstractJerseySecur @Test void actuatorPathOnMainPortShouldNotMatch() { ResponseEntity<String> entity = new TestRestTemplate() - .getForEntity("http://localhost:" + this.port + "/example/actuator/health", String.class); + .getForEntity("http://localhost:" + this.port + "/example/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/CorsSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/CorsSampleActuatorApplicationTests.java index f898c6f2fd..837efbc0b1 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/CorsSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/CorsSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,14 +42,24 @@ class CorsSampleActuatorApplicationTests { @Test void preflightRequestToEndpointShouldReturnOk() { - this.webClient.options().uri("/actuator/env").header("Origin", "http://localhost:8080") - .header("Access-Control-Request-Method", "GET").exchange().expectStatus().isOk(); + this.webClient.options() + .uri("/actuator/env") + .header("Origin", "http://localhost:8080") + .header("Access-Control-Request-Method", "GET") + .exchange() + .expectStatus() + .isOk(); } @Test void preflightRequestWhenCorsConfigInvalidShouldReturnForbidden() { - this.webClient.options().uri("/actuator/env").header("Origin", "http://localhost:9095") - .header("Access-Control-Request-Method", "GET").exchange().expectStatus().isForbidden(); + this.webClient.options() + .uri("/actuator/env") + .header("Origin", "http://localhost:9095") + .header("Access-Control-Request-Method", "GET") + .exchange() + .expectStatus() + .isForbidden(); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/ManagementPortSampleSecureWebFluxTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/ManagementPortSampleSecureWebFluxTests.java index a0cebf047d..0274529374 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/ManagementPortSampleSecureWebFluxTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/ManagementPortSampleSecureWebFluxTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,29 +56,49 @@ class ManagementPortSampleSecureWebFluxTests { @Test void testHome() { - this.webClient.get().uri("http://localhost:" + this.port, String.class).header("Authorization", getBasicAuth()) - .exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("Hello user"); + this.webClient.get() + .uri("http://localhost:" + this.port, String.class) + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("Hello user"); } @Test void actuatorPathOnMainPortShouldNotMatch() { - this.webClient.get().uri("http://localhost:" + this.port + "/actuator", String.class).exchange().expectStatus() - .isUnauthorized(); - this.webClient.get().uri("http://localhost:" + this.port + "/actuator/health", String.class).exchange() - .expectStatus().isUnauthorized(); + this.webClient.get() + .uri("http://localhost:" + this.port + "/actuator", String.class) + .exchange() + .expectStatus() + .isUnauthorized(); + this.webClient.get() + .uri("http://localhost:" + this.port + "/actuator/health", String.class) + .exchange() + .expectStatus() + .isUnauthorized(); } @Test void testSecureActuator() { - this.webClient.get().uri("http://localhost:" + this.managementPort + "/actuator/env", String.class).exchange() - .expectStatus().isUnauthorized(); + this.webClient.get() + .uri("http://localhost:" + this.managementPort + "/actuator/env", String.class) + .exchange() + .expectStatus() + .isUnauthorized(); } @Test void testInsecureActuator() { String responseBody = this.webClient.get() - .uri("http://localhost:" + this.managementPort + "/actuator/health", String.class).exchange() - .expectStatus().isOk().expectBody(String.class).returnResult().getResponseBody(); + .uri("http://localhost:" + this.managementPort + "/actuator/health", String.class) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .returnResult() + .getResponseBody(); assertThat(responseBody).contains("\"status\":\"UP\""); } @@ -94,7 +114,7 @@ class ManagementPortSampleSecureWebFluxTests { http.authorizeExchange((exchanges) -> { exchanges.matchers(EndpointRequest.to("health")).permitAll(); exchanges.matchers(EndpointRequest.toAnyEndpoint().excluding(MappingsEndpoint.class)) - .hasRole("ACTUATOR"); + .hasRole("ACTUATOR"); exchanges.matchers(PathRequest.toStaticResources().atCommonLocations()).permitAll(); exchanges.pathMatchers("/login").permitAll(); exchanges.anyExchange().authenticated(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/SampleSecureWebFluxApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/SampleSecureWebFluxApplicationTests.java index 287acc91f0..c1b329214f 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/SampleSecureWebFluxApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/SampleSecureWebFluxApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,33 +40,54 @@ class SampleSecureWebFluxApplicationTests { @Test void userDefinedMappingsSecureByDefault() { - this.webClient.get().uri("/").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isEqualTo(HttpStatus.UNAUTHORIZED); + this.webClient.get() + .uri("/") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void healthInsecureByDefault() { - this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isOk(); + this.webClient.get() + .uri("/actuator/health") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk(); } @Test void otherActuatorsSecureByDefault() { - this.webClient.get().uri("/actuator/env").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isUnauthorized(); + this.webClient.get() + .uri("/actuator/env") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isUnauthorized(); } @Test void userDefinedMappingsAccessibleOnLogin() { - this.webClient.get().uri("/").accept(MediaType.APPLICATION_JSON).header("Authorization", getBasicAuth()) - .exchange().expectBody(String.class).isEqualTo("Hello user"); + this.webClient.get() + .uri("/") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", getBasicAuth()) + .exchange() + .expectBody(String.class) + .isEqualTo("Hello user"); } @Test void actuatorsAccessibleOnLogin() { - this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON) - .header("Authorization", getBasicAuth()).exchange().expectBody(String.class) - .isEqualTo("{\"status\":\"UP\"}"); + this.webClient.get() + .uri("/actuator/health") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", getBasicAuth()) + .exchange() + .expectBody(String.class) + .isEqualTo("{\"status\":\"UP\"}"); } private String getBasicAuth() { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/SampleSecureWebFluxCustomSecurityTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/SampleSecureWebFluxCustomSecurityTests.java index 58ba49ad82..cd3d820e33 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/SampleSecureWebFluxCustomSecurityTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/SampleSecureWebFluxCustomSecurityTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,46 +50,82 @@ class SampleSecureWebFluxCustomSecurityTests { @Test void userDefinedMappingsSecure() { - this.webClient.get().uri("/").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isEqualTo(HttpStatus.UNAUTHORIZED); + this.webClient.get() + .uri("/") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void healthDoesNotRequireAuthentication() { - this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isOk(); + this.webClient.get() + .uri("/actuator/health") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk(); } @Test void actuatorsSecuredByRole() { - this.webClient.get().uri("/actuator/env").accept(MediaType.APPLICATION_JSON) - .header("Authorization", getBasicAuth()).exchange().expectStatus().isForbidden(); + this.webClient.get() + .uri("/actuator/env") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isForbidden(); } @Test void actuatorsAccessibleOnCorrectLogin() { - this.webClient.get().uri("/actuator/env").accept(MediaType.APPLICATION_JSON) - .header("Authorization", getBasicAuthForAdmin()).exchange().expectStatus().isOk(); + this.webClient.get() + .uri("/actuator/env") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", getBasicAuthForAdmin()) + .exchange() + .expectStatus() + .isOk(); } @Test void actuatorExcludedFromEndpointRequestMatcher() { - this.webClient.get().uri("/actuator/mappings").accept(MediaType.APPLICATION_JSON) - .header("Authorization", getBasicAuth()).exchange().expectStatus().isOk(); + this.webClient.get() + .uri("/actuator/mappings") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); } @Test void staticResourceShouldBeAccessible() { - this.webClient.get().uri("/css/bootstrap.min.css").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isOk(); + this.webClient.get() + .uri("/css/bootstrap.min.css") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk(); } @Test void actuatorLinksIsSecure() { - this.webClient.get().uri("/actuator").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isUnauthorized(); - this.webClient.get().uri("/actuator").accept(MediaType.APPLICATION_JSON) - .header("Authorization", getBasicAuthForAdmin()).exchange().expectStatus().isOk(); + this.webClient.get() + .uri("/actuator") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isUnauthorized(); + this.webClient.get() + .uri("/actuator") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", getBasicAuthForAdmin()) + .exchange() + .expectStatus() + .isOk(); } private String getBasicAuth() { @@ -107,10 +143,16 @@ class SampleSecureWebFluxCustomSecurityTests { @Bean MapReactiveUserDetailsService userDetailsService() { return new MapReactiveUserDetailsService( - User.withDefaultPasswordEncoder().username("user").password("password").authorities("ROLE_USER") - .build(), - User.withDefaultPasswordEncoder().username("admin").password("admin") - .authorities("ROLE_ACTUATOR", "ROLE_USER").build()); + User.withDefaultPasswordEncoder() + .username("user") + .password("password") + .authorities("ROLE_USER") + .build(), + User.withDefaultPasswordEncoder() + .username("admin") + .password("admin") + .authorities("ROLE_ACTUATOR", "ROLE_USER") + .build()); } @Bean @@ -118,7 +160,7 @@ class SampleSecureWebFluxCustomSecurityTests { http.authorizeExchange((exchanges) -> { exchanges.matchers(EndpointRequest.to("health")).permitAll(); exchanges.matchers(EndpointRequest.toAnyEndpoint().excluding(MappingsEndpoint.class)) - .hasRole("ACTUATOR"); + .hasRole("ACTUATOR"); exchanges.matchers(PathRequest.toStaticResources().atCommonLocations()).permitAll(); exchanges.pathMatchers("/login").permitAll(); exchanges.anyExchange().authenticated(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure/src/main/java/smoketest/secure/SampleSecureApplication.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure/src/main/java/smoketest/secure/SampleSecureApplication.java index 5927065c76..96c5a67052 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure/src/main/java/smoketest/secure/SampleSecureApplication.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure/src/main/java/smoketest/secure/SampleSecureApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,9 @@ public class SampleSecureApplication implements CommandLineRunner { @Override public void run(String... args) throws Exception { - SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("user", "N/A", - AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"))); + SecurityContextHolder.getContext() + .setAuthentication(new UsernamePasswordAuthenticationToken("user", "N/A", + AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"))); try { System.out.println(this.service.secure()); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure/src/test/java/smoketest/secure/SampleSecureApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure/src/test/java/smoketest/secure/SampleSecureApplicationTests.java index 4a63b387e9..f6a8bf1258 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure/src/test/java/smoketest/secure/SampleSecureApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure/src/test/java/smoketest/secure/SampleSecureApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +57,7 @@ class SampleSecureApplicationTests { @Test void secure() { assertThatExceptionOfType(AuthenticationException.class) - .isThrownBy(() -> SampleSecureApplicationTests.this.service.secure()); + .isThrownBy(() -> SampleSecureApplicationTests.this.service.secure()); } @Test @@ -76,7 +76,7 @@ class SampleSecureApplicationTests { void denied() { SecurityContextHolder.getContext().setAuthentication(this.authentication); assertThatExceptionOfType(AccessDeniedException.class) - .isThrownBy(() -> SampleSecureApplicationTests.this.service.denied()); + .isThrownBy(() -> SampleSecureApplicationTests.this.service.denied()); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-servlet/src/test/java/smoketest/servlet/SampleServletApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-servlet/src/test/java/smoketest/servlet/SampleServletApplicationTests.java index 516bb92635..b1ad40bf0d 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-servlet/src/test/java/smoketest/servlet/SampleServletApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-servlet/src/test/java/smoketest/servlet/SampleServletApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,8 +55,8 @@ class SampleServletApplicationTests { @Test void testHome() { - ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/", - String.class); + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()) + .getForEntity("/", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("Hello World"); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-mongo/src/test/java/smoketest/session/mongodb/SampleSessionMongoApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-mongo/src/test/java/smoketest/session/mongodb/SampleSessionMongoApplicationTests.java index ae6ffc2555..f73650e971 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-mongo/src/test/java/smoketest/session/mongodb/SampleSessionMongoApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-mongo/src/test/java/smoketest/session/mongodb/SampleSessionMongoApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,7 +55,7 @@ public class SampleSessionMongoApplicationTests { @Container static MongoDBContainer mongo = new MongoDBContainer(DockerImageNames.mongo()).withStartupAttempts(3) - .withStartupTimeout(Duration.ofMinutes(2)); + .withStartupTimeout(Duration.ofMinutes(2)); @DynamicPropertySource static void applicationProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-webflux-mongo/src/test/java/smoketest/session/SampleSessionWebFluxMongoApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-webflux-mongo/src/test/java/smoketest/session/SampleSessionWebFluxMongoApplicationTests.java index 438ea6839a..c7ccd4cb02 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-webflux-mongo/src/test/java/smoketest/session/SampleSessionWebFluxMongoApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-webflux-mongo/src/test/java/smoketest/session/SampleSessionWebFluxMongoApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ class SampleSessionWebFluxMongoApplicationTests { @Container private static final MongoDBContainer mongo = new MongoDBContainer(DockerImageNames.mongo()).withStartupAttempts(3) - .withStartupTimeout(Duration.ofMinutes(2)); + .withStartupTimeout(Duration.ofMinutes(2)); @LocalServerPort private int port; @@ -67,20 +67,22 @@ class SampleSessionWebFluxMongoApplicationTests { client.get().header("Authorization", getBasicAuth()).exchangeToMono((response) -> { assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); return response.bodyToMono(String.class) - .map((sessionId) -> Tuples.of(response.cookies().getFirst("SESSION").getValue(), sessionId)); + .map((sessionId) -> Tuples.of(response.cookies().getFirst("SESSION").getValue(), sessionId)); }).flatMap((tuple) -> { String sessionCookie = tuple.getT1(); return client.get().cookie("SESSION", sessionCookie).exchangeToMono((response) -> { assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); return response.bodyToMono(String.class) - .doOnNext((sessionId) -> assertThat(sessionId).isEqualTo(tuple.getT2())) - .thenReturn(sessionCookie); + .doOnNext((sessionId) -> assertThat(sessionId).isEqualTo(tuple.getT2())) + .thenReturn(sessionCookie); }); - }).delayElement(Duration.ofSeconds(10)) - .flatMap((sessionCookie) -> client.get().cookie("SESSION", sessionCookie).exchangeToMono((response) -> { - assertThat(response.statusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - return response.releaseBody(); - })).block(Duration.ofSeconds(30)); + }) + .delayElement(Duration.ofSeconds(10)) + .flatMap((sessionCookie) -> client.get().cookie("SESSION", sessionCookie).exchangeToMono((response) -> { + assertThat(response.statusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + return response.releaseBody(); + })) + .block(Duration.ofSeconds(30)); } private String getBasicAuth() { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-webflux-redis/src/test/java/smoketest/session/SampleSessionWebFluxRedisApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-webflux-redis/src/test/java/smoketest/session/SampleSessionWebFluxRedisApplicationTests.java index 3c7bf07e6c..fe1cc1e5db 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-webflux-redis/src/test/java/smoketest/session/SampleSessionWebFluxRedisApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-webflux-redis/src/test/java/smoketest/session/SampleSessionWebFluxRedisApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,20 +66,22 @@ class SampleSessionWebFluxRedisApplicationTests { client.get().header("Authorization", getBasicAuth()).exchangeToMono((response) -> { assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); return response.bodyToMono(String.class) - .map((sessionId) -> Tuples.of(response.cookies().getFirst("SESSION").getValue(), sessionId)); + .map((sessionId) -> Tuples.of(response.cookies().getFirst("SESSION").getValue(), sessionId)); }).flatMap((tuple) -> { String sessionCookie = tuple.getT1(); return client.get().cookie("SESSION", sessionCookie).exchangeToMono((response) -> { assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); return response.bodyToMono(String.class) - .doOnNext((sessionId) -> assertThat(sessionId).isEqualTo(tuple.getT2())) - .thenReturn(sessionCookie); + .doOnNext((sessionId) -> assertThat(sessionId).isEqualTo(tuple.getT2())) + .thenReturn(sessionCookie); }); - }).delayElement(Duration.ofSeconds(10)) - .flatMap((sessionCookie) -> client.get().cookie("SESSION", sessionCookie).exchangeToMono((response) -> { - assertThat(response.statusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - return response.releaseBody(); - })).block(Duration.ofSeconds(30)); + }) + .delayElement(Duration.ofSeconds(10)) + .flatMap((sessionCookie) -> client.get().cookie("SESSION", sessionCookie).exchangeToMono((response) -> { + assertThat(response.statusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + return response.releaseBody(); + })) + .block(Duration.ofSeconds(30)); } private String getBasicAuth() { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/SampleTestApplicationWebIntegrationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/SampleTestApplicationWebIntegrationTests.java index 832b43d6ef..28e8030511 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/SampleTestApplicationWebIntegrationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/SampleTestApplicationWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,7 +59,7 @@ class SampleTestApplicationWebIntegrationTests { @Test void test() { assertThat(this.restTemplate.getForEntity("/{username}/vehicle", String.class, "sframework").getStatusCode()) - .isEqualTo(HttpStatus.OK); + .isEqualTo(HttpStatus.OK); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/domain/UserEntityTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/domain/UserEntityTests.java index 4ba858a629..939b7ff6fb 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/domain/UserEntityTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/domain/UserEntityTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,19 +41,19 @@ class UserEntityTests { @Test void createWhenUsernameIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new User(null, VIN)) - .withMessage("Username must not be empty"); + .withMessage("Username must not be empty"); } @Test void createWhenUsernameIsEmptyShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new User("", VIN)) - .withMessage("Username must not be empty"); + .withMessage("Username must not be empty"); } @Test void createWhenVinIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new User("sboot", null)) - .withMessage("VIN must not be null"); + .withMessage("VIN must not be null"); } @Test diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/domain/VehicleIdentificationNumberTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/domain/VehicleIdentificationNumberTests.java index eb271a2c71..8127e7a95c 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/domain/VehicleIdentificationNumberTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/domain/VehicleIdentificationNumberTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,19 +36,19 @@ class VehicleIdentificationNumberTests { @Test void createWhenVinIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new VehicleIdentificationNumber(null)) - .withMessage("VIN must not be null"); + .withMessage("VIN must not be null"); } @Test void createWhenVinIsMoreThan17CharsShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new VehicleIdentificationNumber("012345678901234567")) - .withMessage("VIN must be exactly 17 characters"); + .withMessage("VIN must be exactly 17 characters"); } @Test void createWhenVinIsLessThan17CharsShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new VehicleIdentificationNumber("0123456789012345")) - .withMessage("VIN must be exactly 17 characters"); + .withMessage("VIN must be exactly 17 characters"); } @Test diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/service/RemoteVehicleDetailsServiceTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/service/RemoteVehicleDetailsServiceTests.java index ebd4baf9c2..876faf60fe 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/service/RemoteVehicleDetailsServiceTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/service/RemoteVehicleDetailsServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,13 +54,13 @@ class RemoteVehicleDetailsServiceTests { @Test void getVehicleDetailsWhenVinIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.service.getVehicleDetails(null)) - .withMessage("VIN must not be null"); + .withMessage("VIN must not be null"); } @Test void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails() { this.server.expect(requestTo("/vehicle/" + VIN + "/details")) - .andRespond(withSuccess(getClassPathResource("vehicledetails.json"), MediaType.APPLICATION_JSON)); + .andRespond(withSuccess(getClassPathResource("vehicledetails.json"), MediaType.APPLICATION_JSON)); VehicleDetails details = this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN)); assertThat(details.getMake()).isEqualTo("Honda"); assertThat(details.getModel()).isEqualTo("Civic"); @@ -70,14 +70,14 @@ class RemoteVehicleDetailsServiceTests { void getVehicleDetailsWhenResultIsNotFoundShouldThrowException() { this.server.expect(requestTo("/vehicle/" + VIN + "/details")).andRespond(withStatus(HttpStatus.NOT_FOUND)); assertThatExceptionOfType(VehicleIdentificationNumberNotFoundException.class) - .isThrownBy(() -> this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN))); + .isThrownBy(() -> this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN))); } @Test void getVehicleDetailsWhenResultIServerErrorShouldThrowException() { this.server.expect(requestTo("/vehicle/" + VIN + "/details")).andRespond(withServerError()); assertThatExceptionOfType(HttpServerErrorException.class) - .isThrownBy(() -> this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN))); + .isThrownBy(() -> this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN))); } private ClassPathResource getClassPathResource(String path) { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerApplicationTests.java index 55e3f0158d..6f73fdcbb8 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,8 +57,9 @@ class UserVehicleControllerApplicationTests { @Test void getVehicleWhenRequestingTextShouldReturnMakeAndModel() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); - this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)).andExpect(status().isOk()) - .andExpect(content().string("Honda Civic")); + this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)) + .andExpect(status().isOk()) + .andExpect(content().string("Honda Civic")); } @Test diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerTests.java index be22aab13a..e3f2840e3e 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,22 +59,25 @@ class UserVehicleControllerTests { @Test void getVehicleWhenRequestingTextShouldReturnMakeAndModel() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); - this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)).andExpect(status().isOk()) - .andExpect(content().string("Honda Civic")); + this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)) + .andExpect(status().isOk()) + .andExpect(content().string("Honda Civic")); } @Test void getVehicleWhenRequestingJsonShouldReturnMakeAndModel() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); - this.mvc.perform(get("/sboot/vehicle").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andExpect(content().json("{'make':'Honda','model':'Civic'}")); + this.mvc.perform(get("/sboot/vehicle").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json("{'make':'Honda','model':'Civic'}")); } @Test void getVehicleWhenRequestingHtmlShouldReturnMakeAndModel() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); - this.mvc.perform(get("/sboot/vehicle.html").accept(MediaType.TEXT_HTML)).andExpect(status().isOk()) - .andExpect(content().string(containsString("<h1>Honda Civic</h1>"))); + this.mvc.perform(get("/sboot/vehicle.html").accept(MediaType.TEXT_HTML)) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("<h1>Honda Civic</h1>"))); } @Test @@ -86,7 +89,7 @@ class UserVehicleControllerTests { @Test void getVehicleWhenVinNotFoundShouldReturnNotFound() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")) - .willThrow(new VehicleIdentificationNumberNotFoundException(VIN)); + .willThrow(new VehicleIdentificationNumberNotFoundException(VIN)); this.mvc.perform(get("/sboot/vehicle")).andExpect(status().isNotFound()); } @@ -94,7 +97,7 @@ class UserVehicleControllerTests { void welcomeCommandLineRunnerShouldNotBeAvailable() { // Since we're a @WebMvcTest WelcomeCommandLineRunner should not be available. Assertions.assertThatThrownBy(() -> this.applicationContext.getBean(WelcomeCommandLineRunner.class)) - .isInstanceOf(NoSuchBeanDefinitionException.class); + .isInstanceOf(NoSuchBeanDefinitionException.class); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleServiceTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleServiceTests.java index 649f7feaed..33fd031573 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleServiceTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,14 +59,14 @@ class UserVehicleServiceTests { @Test void getVehicleDetailsWhenUsernameIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.service.getVehicleDetails(null)) - .withMessage("Username must not be null"); + .withMessage("Username must not be null"); } @Test void getVehicleDetailsWhenUsernameNotFoundShouldThrowException() { given(this.userRepository.findByUsername(anyString())).willReturn(null); assertThatExceptionOfType(UserNameNotFoundException.class) - .isThrownBy(() -> this.service.getVehicleDetails("sboot")); + .isThrownBy(() -> this.service.getVehicleDetails("sboot")); } @Test diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-tomcat-multi-connectors/src/test/java/smoketest/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-tomcat-multi-connectors/src/test/java/smoketest/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java index 590bddf823..9e429a9321 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-tomcat-multi-connectors/src/test/java/smoketest/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-tomcat-multi-connectors/src/test/java/smoketest/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,7 +69,7 @@ class SampleTomcatTwoConnectorsApplicationTests { assertThat(this.ports.getHttpsPort()).isEqualTo(this.port); assertThat(this.ports.getHttpPort()).isNotEqualTo(this.port); ResponseEntity<String> entity = this.restTemplate - .getForEntity("http://localhost:" + this.ports.getHttpPort() + "/hello", String.class); + .getForEntity("http://localhost:" + this.ports.getHttpPort() + "/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("hello"); ResponseEntity<String> httpsEntity = this.restTemplate.getForEntity("https://localhost:" + this.port + "/hello", diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-groovy-templates/src/test/java/smoketest/groovytemplates/MessageControllerWebTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-groovy-templates/src/test/java/smoketest/groovytemplates/MessageControllerWebTests.java index 377d67eaf8..5be52ecb82 100755 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-groovy-templates/src/test/java/smoketest/groovytemplates/MessageControllerWebTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-groovy-templates/src/test/java/smoketest/groovytemplates/MessageControllerWebTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,20 +57,23 @@ class MessageControllerWebTests { @Test void testHome() throws Exception { - this.mockMvc.perform(get("/")).andExpect(status().isOk()) - .andExpect(content().string(containsString("<title>Messages"))); + this.mockMvc.perform(get("/")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("<title>Messages"))); } @Test void testCreate() throws Exception { - this.mockMvc.perform(post("/").param("text", "FOO text").param("summary", "FOO")).andExpect(status().isFound()) - .andExpect(header().string("location", RegexMatcher.matches("/[0-9]+"))); + this.mockMvc.perform(post("/").param("text", "FOO text").param("summary", "FOO")) + .andExpect(status().isFound()) + .andExpect(header().string("location", RegexMatcher.matches("/[0-9]+"))); } @Test void testCreateValidation() throws Exception { - this.mockMvc.perform(post("/").param("text", "").param("summary", "")).andExpect(status().isOk()) - .andExpect(content().string(containsString("is required"))); + this.mockMvc.perform(post("/").param("text", "").param("summary", "")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("is required"))); } private static class RegexMatcher extends TypeSafeMatcher<String> { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-method-security/src/main/java/smoketest/security/method/SampleMethodSecurityApplication.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-method-security/src/main/java/smoketest/security/method/SampleMethodSecurityApplication.java index 2f77338b65..f0f58a1dac 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-method-security/src/main/java/smoketest/security/method/SampleMethodSecurityApplication.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-method-security/src/main/java/smoketest/security/method/SampleMethodSecurityApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,8 +56,11 @@ public class SampleMethodSecurityApplication implements WebMvcConfigurer { @Bean public InMemoryUserDetailsManager inMemoryUserDetailsManager() { return new InMemoryUserDetailsManager( - User.withDefaultPasswordEncoder().username("admin").password("admin") - .roles("ADMIN", "USER", "ACTUATOR").build(), + User.withDefaultPasswordEncoder() + .username("admin") + .password("admin") + .roles("ADMIN", "USER", "ACTUATOR") + .build(), User.withDefaultPasswordEncoder().username("user").password("user").roles("USER").build()); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractErrorPageTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractErrorPageTests.java index 22605fe0bc..a2926b63b2 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractErrorPageTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractErrorPageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ abstract class AbstractErrorPageTests { @Test void testBadCredentials() { final ResponseEntity<JsonNode> response = this.testRestTemplate.withBasicAuth("username", "wrongpassword") - .exchange("/test", HttpMethod.GET, null, JsonNode.class); + .exchange("/test", HttpMethod.GET, null, JsonNode.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); JsonNode jsonResponse = response.getBody(); assertThat(jsonResponse).isNull(); @@ -77,7 +77,7 @@ abstract class AbstractErrorPageTests { @Test void testPublicNotFoundPageWithCorrectCredentials() { final ResponseEntity<JsonNode> response = this.testRestTemplate.withBasicAuth("username", "password") - .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); + .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); JsonNode jsonResponse = response.getBody(); assertThat(jsonResponse.get("error").asText()).isEqualTo("Not Found"); @@ -86,7 +86,7 @@ abstract class AbstractErrorPageTests { @Test void testPublicNotFoundPageWithBadCredentials() { final ResponseEntity<JsonNode> response = this.testRestTemplate.withBasicAuth("username", "wrong") - .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); + .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); JsonNode jsonResponse = response.getBody(); assertThat(jsonResponse).isNull(); @@ -95,7 +95,7 @@ abstract class AbstractErrorPageTests { @Test void testCorrectCredentialsWithControllerException() { final ResponseEntity<JsonNode> response = this.testRestTemplate.withBasicAuth("username", "password") - .exchange(this.pathPrefix + "/fail", HttpMethod.GET, null, JsonNode.class); + .exchange(this.pathPrefix + "/fail", HttpMethod.GET, null, JsonNode.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); JsonNode jsonResponse = response.getBody(); assertThat(jsonResponse.get("error").asText()).isEqualTo("Internal Server Error"); @@ -104,7 +104,7 @@ abstract class AbstractErrorPageTests { @Test void testCorrectCredentials() { final ResponseEntity<String> response = this.testRestTemplate.withBasicAuth("username", "password") - .exchange(this.pathPrefix + "/test", HttpMethod.GET, null, String.class); + .exchange(this.pathPrefix + "/test", HttpMethod.GET, null, String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); response.getBody(); assertThat(response.getBody()).isEqualTo("test"); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractUnauthenticatedErrorPageTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractUnauthenticatedErrorPageTests.java index fe15a379bc..3bf1e9d926 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractUnauthenticatedErrorPageTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractUnauthenticatedErrorPageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ abstract class AbstractUnauthenticatedErrorPageTests { @Test void testBadCredentials() { final ResponseEntity<JsonNode> response = this.testRestTemplate.withBasicAuth("username", "wrongpassword") - .exchange(this.pathPrefix + "/test", HttpMethod.GET, null, JsonNode.class); + .exchange(this.pathPrefix + "/test", HttpMethod.GET, null, JsonNode.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); JsonNode jsonResponse = response.getBody(); assertThat(jsonResponse.get("error").asText()).isEqualTo("Unauthorized"); @@ -74,7 +74,7 @@ abstract class AbstractUnauthenticatedErrorPageTests { @Test void testPublicNotFoundPageWithCorrectCredentials() { final ResponseEntity<JsonNode> response = this.testRestTemplate.withBasicAuth("username", "password") - .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); + .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); JsonNode jsonResponse = response.getBody(); assertThat(jsonResponse.get("error").asText()).isEqualTo("Not Found"); @@ -83,7 +83,7 @@ abstract class AbstractUnauthenticatedErrorPageTests { @Test void testPublicNotFoundPageWithBadCredentials() { final ResponseEntity<JsonNode> response = this.testRestTemplate.withBasicAuth("username", "wrong") - .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); + .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); JsonNode jsonResponse = response.getBody(); assertThat(jsonResponse.get("error").asText()).isEqualTo("Unauthorized"); @@ -92,7 +92,7 @@ abstract class AbstractUnauthenticatedErrorPageTests { @Test void testCorrectCredentialsWithControllerException() { final ResponseEntity<JsonNode> response = this.testRestTemplate.withBasicAuth("username", "password") - .exchange(this.pathPrefix + "/fail", HttpMethod.GET, null, JsonNode.class); + .exchange(this.pathPrefix + "/fail", HttpMethod.GET, null, JsonNode.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); JsonNode jsonResponse = response.getBody(); assertThat(jsonResponse.get("error").asText()).isEqualTo("Internal Server Error"); @@ -101,7 +101,7 @@ abstract class AbstractUnauthenticatedErrorPageTests { @Test void testCorrectCredentials() { final ResponseEntity<String> response = this.testRestTemplate.withBasicAuth("username", "password") - .exchange(this.pathPrefix + "/test", HttpMethod.GET, null, String.class); + .exchange(this.pathPrefix + "/test", HttpMethod.GET, null, String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(response.getBody()).isEqualTo("test"); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/NoSessionErrorPageTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/NoSessionErrorPageTests.java index 0e9ad9043c..b4a6a8b49c 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/NoSessionErrorPageTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/NoSessionErrorPageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,10 +45,10 @@ class NoSessionErrorPageTests extends AbstractErrorPageTests { @Bean SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { http.sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) - .authorizeRequests((requests) -> { - requests.antMatchers("/public/**").permitAll(); - requests.anyRequest().authenticated(); - }); + .authorizeRequests((requests) -> { + requests.antMatchers("/public/**").permitAll(); + requests.anyRequest().authenticated(); + }); http.httpBasic(); return http.build(); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-thymeleaf/src/test/java/smoketest/web/thymeleaf/MessageControllerWebTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-thymeleaf/src/test/java/smoketest/web/thymeleaf/MessageControllerWebTests.java index 72f070d63c..3f34b60f8c 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-thymeleaf/src/test/java/smoketest/web/thymeleaf/MessageControllerWebTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-thymeleaf/src/test/java/smoketest/web/thymeleaf/MessageControllerWebTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,20 +57,23 @@ class MessageControllerWebTests { @Test void testHome() throws Exception { - this.mockMvc.perform(get("/")).andExpect(status().isOk()) - .andExpect(content().string(containsString("<title>Messages"))); + this.mockMvc.perform(get("/")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("<title>Messages"))); } @Test void testCreate() throws Exception { - this.mockMvc.perform(post("/").param("text", "FOO text").param("summary", "FOO")).andExpect(status().isFound()) - .andExpect(header().string("location", RegexMatcher.matches("/[0-9]+"))); + this.mockMvc.perform(post("/").param("text", "FOO text").param("summary", "FOO")) + .andExpect(status().isFound()) + .andExpect(header().string("location", RegexMatcher.matches("/[0-9]+"))); } @Test void testCreateValidation() throws Exception { - this.mockMvc.perform(post("/").param("text", "").param("summary", "")).andExpect(status().isOk()) - .andExpect(content().string(containsString("is required"))); + this.mockMvc.perform(post("/").param("text", "").param("summary", "")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("is required"))); } private static class RegexMatcher extends TypeSafeMatcher<String> { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationTests.java index 33722d16d9..50627a0438 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,21 +38,36 @@ class SampleWebFluxApplicationTests { @Test void testWelcome() { - this.webClient.get().uri("/").accept(MediaType.TEXT_PLAIN).exchange().expectBody(String.class) - .isEqualTo("Hello World"); + this.webClient.get() + .uri("/") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .expectBody(String.class) + .isEqualTo("Hello World"); } @Test void testEcho() { - this.webClient.post().uri("/echo").contentType(MediaType.TEXT_PLAIN).accept(MediaType.TEXT_PLAIN) - .body(Mono.just("Hello WebFlux!"), String.class).exchange().expectBody(String.class) - .isEqualTo("Hello WebFlux!"); + this.webClient.post() + .uri("/echo") + .contentType(MediaType.TEXT_PLAIN) + .accept(MediaType.TEXT_PLAIN) + .body(Mono.just("Hello WebFlux!"), String.class) + .exchange() + .expectBody(String.class) + .isEqualTo("Hello WebFlux!"); } @Test void testActuatorStatus() { - this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() - .expectBody().json("{\"status\":\"UP\"}"); + this.webClient.get() + .uri("/actuator/health") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .json("{\"status\":\"UP\"}"); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/WebFluxDifferentPortSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/WebFluxDifferentPortSampleActuatorApplicationTests.java index d22383653c..bfb626d8d8 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/WebFluxDifferentPortSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/WebFluxDifferentPortSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ class WebFluxDifferentPortSampleActuatorApplicationTests { @Test void linksEndpointShouldBeAvailable() { ResponseEntity<String> entity = new TestRestTemplate("user", getPassword()) - .getForEntity("http://localhost:" + this.managementPort + "/", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"_links\""); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webservices/src/test/java/smoketest/webservices/WebServiceServerTestSampleWsApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webservices/src/test/java/smoketest/webservices/WebServiceServerTestSampleWsApplicationTests.java index 35879f5b0d..22adb1b021 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webservices/src/test/java/smoketest/webservices/WebServiceServerTestSampleWsApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webservices/src/test/java/smoketest/webservices/WebServiceServerTestSampleWsApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,8 +64,8 @@ class WebServiceServerTestSampleWsApplicationTests { StreamSource source = new StreamSource(new StringReader(request)); this.client.sendRequest(RequestCreators.withPayload(source)).andExpect(ResponseMatchers.noFault()); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - then(this.service).should().bookHoliday(dateFormat.parse("2013-10-20"), dateFormat.parse("2013-11-22"), - "John Doe"); + then(this.service).should() + .bookHoliday(dateFormat.parse("2013-10-20"), dateFormat.parse("2013-11-22"), "John Doe"); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty/src/test/java/smoketest/websocket/jetty/SampleWebSocketsApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty/src/test/java/smoketest/websocket/jetty/SampleWebSocketsApplicationTests.java index e66096c99a..aa50be262a 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty/src/test/java/smoketest/websocket/jetty/SampleWebSocketsApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty/src/test/java/smoketest/websocket/jetty/SampleWebSocketsApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,8 @@ class SampleWebSocketsApplicationTests { void echoEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); @@ -67,8 +67,8 @@ class SampleWebSocketsApplicationTests { void reverseEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty/src/test/java/smoketest/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty/src/test/java/smoketest/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java index ccfb5ff35b..b95b856c2f 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty/src/test/java/smoketest/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty/src/test/java/smoketest/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,8 +59,8 @@ class CustomContainerWebSocketsApplicationTests { void echoEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/ws/echo/websocket") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/echo/websocket") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); @@ -72,8 +72,8 @@ class CustomContainerWebSocketsApplicationTests { void reverseEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/ws/reverse") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/reverse") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty10/src/test/java/smoketest/websocket/jetty10/SampleJetty10WebSocketsApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty10/src/test/java/smoketest/websocket/jetty10/SampleJetty10WebSocketsApplicationTests.java index 5df90d6f9f..40f35d76fa 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty10/src/test/java/smoketest/websocket/jetty10/SampleJetty10WebSocketsApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty10/src/test/java/smoketest/websocket/jetty10/SampleJetty10WebSocketsApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,8 +57,8 @@ class SampleJetty10WebSocketsApplicationTests { void echoEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); @@ -70,8 +70,8 @@ class SampleJetty10WebSocketsApplicationTests { void reverseEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty10/src/test/java/smoketest/websocket/jetty10/echo/CustomContainerWebSocketsApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty10/src/test/java/smoketest/websocket/jetty10/echo/CustomContainerWebSocketsApplicationTests.java index 651d82828c..cdb7d4717b 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty10/src/test/java/smoketest/websocket/jetty10/echo/CustomContainerWebSocketsApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty10/src/test/java/smoketest/websocket/jetty10/echo/CustomContainerWebSocketsApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,8 +62,8 @@ class CustomContainerWebSocketsApplicationTests { void echoEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/ws/echo/websocket") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/echo/websocket") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); @@ -75,8 +75,8 @@ class CustomContainerWebSocketsApplicationTests { void reverseEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/ws/reverse") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/reverse") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-tomcat/src/test/java/smoketest/websocket/tomcat/SampleWebSocketsApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-tomcat/src/test/java/smoketest/websocket/tomcat/SampleWebSocketsApplicationTests.java index 642e60b983..a6bf037cf1 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-tomcat/src/test/java/smoketest/websocket/tomcat/SampleWebSocketsApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-tomcat/src/test/java/smoketest/websocket/tomcat/SampleWebSocketsApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,8 @@ class SampleWebSocketsApplicationTests { void echoEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); @@ -67,8 +67,8 @@ class SampleWebSocketsApplicationTests { void reverseEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-tomcat/src/test/java/smoketest/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-tomcat/src/test/java/smoketest/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java index 5f26119931..68808668e4 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-tomcat/src/test/java/smoketest/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-tomcat/src/test/java/smoketest/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,8 +59,8 @@ class CustomContainerWebSocketsApplicationTests { void echoEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/ws/echo/websocket") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/echo/websocket") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); @@ -72,8 +72,8 @@ class CustomContainerWebSocketsApplicationTests { void reverseEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/ws/reverse") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/reverse") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-undertow/src/test/java/smoketest/websocket/undertow/SampleWebSocketsApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-undertow/src/test/java/smoketest/websocket/undertow/SampleWebSocketsApplicationTests.java index 0ab9771969..426eae68a2 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-undertow/src/test/java/smoketest/websocket/undertow/SampleWebSocketsApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-undertow/src/test/java/smoketest/websocket/undertow/SampleWebSocketsApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,8 @@ class SampleWebSocketsApplicationTests { void echoEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); @@ -67,8 +67,8 @@ class SampleWebSocketsApplicationTests { void reverseEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-undertow/src/test/java/smoketest/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-undertow/src/test/java/smoketest/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java index f0a361fa05..1c4af490be 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-undertow/src/test/java/smoketest/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-undertow/src/test/java/smoketest/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,8 +59,8 @@ class CustomContainerWebSocketsApplicationTests { void echoEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/ws/echo/websocket") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/echo/websocket") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); @@ -72,8 +72,8 @@ class CustomContainerWebSocketsApplicationTests { void reverseEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/ws/reverse") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/reverse") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close();